diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 259c69ab3..79fe195fd 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -29,7 +29,6 @@ "biomejs.biome" ], "settings": { - "rust-analyzer.cargo.features": ["verge-dev"], "rust-analyzer.check.command": "clippy", "editor.formatOnSave": true, "editor.defaultFormatter": "biomejs.biome", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 152f6f95a..634bc9e47 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -81,23 +81,20 @@ pnpm run prebuild pnpm run prebuild --force # Re-download and overwrite Mihomo core and service binaries ``` -### Prepare the Development Service Source +### Service Development -`pnpm dev` builds the development service from a sibling checkout of [`clash-verge-service-ipc`](https://github.com/clash-verge-rev/clash-verge-service-ipc). The binaries downloaded by `pnpm prebuild` do not replace this source checkout. - -Check the `clash_verge_service_ipc` dependency in [`src-tauri/Cargo.toml`](src-tauri/Cargo.toml), then clone the service repository alongside `clash-verge-rev` and check out the matching tag. If the sibling directory already exists, reuse it and check its version rather than overwriting it. Without this checkout, `pnpm dev` fails when it tries to access `../clash-verge-service-ipc/Cargo.toml`. +The app consumes the published `clash_verge_service_ipc` crate from its git tag (see [`src-tauri/Cargo.toml`](src-tauri/Cargo.toml)). To work on the Service itself, clone [`clash-verge-service-ipc`](https://github.com/clash-verge-rev/clash-verge-service-ipc) alongside `clash-verge-rev`, check out the matching tag, and temporarily point the dependency at the local path before building. ### Run the Development Server Run these commands from the root of `clash-verge-rev`: ```bash -pnpm dev # Build the development service and start the desktop app -pnpm dev:diff # Alias of pnpm dev +pnpm dev # Start the desktop app in debug mode pnpm dev:tauri # Run Tauri directly with the tauri-dev feature ``` -For frontend-only development, use `pnpm web:dev`. It does not start the Rust backend or build the development service. +For frontend-only development, use `pnpm web:dev`. It does not start the Rust backend. ### Build the Project diff --git a/Cargo.lock b/Cargo.lock index 01e50c25f..199f753a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1224,8 +1224,8 @@ dependencies = [ [[package]] name = "clash_verge_service_ipc" -version = "2.8.1" -source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.8.1#9d4ea7d27fb3c43804bd18f3bb3b686528763239" +version = "2.8.2" +source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?branch=main#3e06ff153e9cb19ae20e0a61f861b371d3f7b2aa" dependencies = [ "anyhow", "kode-bridge", @@ -1329,7 +1329,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" dependencies = [ "lazy_static", - "windows-sys 0.59.0", + "windows-sys 0.48.0", ] [[package]] @@ -3373,7 +3373,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.62.2", + "windows-core 0.61.2", ] [[package]] @@ -4909,7 +4909,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.45.0", ] [[package]] @@ -7875,7 +7875,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.4", "windows-sys 0.61.2", @@ -9204,7 +9204,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] diff --git a/README.md b/README.md index 551997718..5907b861e 100644 --- a/README.md +++ b/README.md @@ -108,11 +108,10 @@ pnpm run prebuild pnpm dev ``` -`pnpm dev` preserves the Development Channel's installed service state: an -existing service is used, while a previously uninstalled service remains -uninstalled and the app starts in Sidecar mode. Use `pnpm dev:service` to -explicitly install or update the isolated development service before launch, -or `pnpm dev:sidecar` to force the unprivileged Sidecar workflow. +`pnpm dev` runs the desktop app in debug mode against the single Service +channel: an installed service is reused, and an uninstalled one keeps the app +in Sidecar mode. Debug sessions keep their profiles and settings in the +isolated `.dev` application data directory. ## Contributions diff --git a/package.json b/package.json index 8e57b7501..32305609d 100644 --- a/package.json +++ b/package.json @@ -4,11 +4,7 @@ "license": "GPL-3.0-only", "scripts": { "prepare": "husky || true", - "dev": "node scripts/dev.mjs dev", - "dev:service": "node scripts/dev.mjs service", - "dev:sidecar": "node scripts/dev.mjs sidecar", - "dev:diff": "node scripts/dev.mjs dev", - "dev:trace": "node scripts/dev.mjs trace", + "dev": "cross-env RUST_BACKTRACE=full tauri dev", "dev:tauri": "cross-env RUST_BACKTRACE=full tauri dev -f tauri-dev", "build": "cross-env NODE_OPTIONS='--max-old-space-size=4096' tauri build", "build:fast": "cross-env NODE_OPTIONS='--max-old-space-size=4096' tauri build -- --profile fast-release", diff --git a/scripts/dev-control.mjs b/scripts/dev-control.mjs deleted file mode 100644 index 3b9d0e3a7..000000000 --- a/scripts/dev-control.mjs +++ /dev/null @@ -1,280 +0,0 @@ -import { constants } from 'node:fs' -import { open } from 'node:fs/promises' -import { request } from 'node:http' -import { connect } from 'node:net' - -const DEFAULT_TIMEOUT_MS = 10_000 -const DEFAULT_RETRY_DELAY_MS = 100 -const TRANSIENT_REQUEST_ERRORS = new Set([ - 'ECONNREFUSED', - 'ECONNRESET', - 'EPIPE', - 'ETIMEDOUT', -]) -const SAFE_REQUEST_ERROR_CODES = new Set([ - ...TRANSIENT_REQUEST_ERRORS, - 'EACCES', - 'EINVAL', - 'ENOTFOUND', -]) - -function validateInstanceRecord(record) { - if ( - !record || - !Number.isInteger(record.port) || - record.port < 1 || - record.port > 65_535 - ) { - throw new Error('invalid instance record port') - } - if ( - typeof record.token !== 'string' || - !/^[0-9a-f]{64}$/.test(record.token) - ) { - throw new Error('invalid instance record token') - } - return { port: record.port, token: record.token } -} - -function delay(milliseconds) { - return new Promise((resolve) => setTimeout(resolve, milliseconds)) -} - -function safeRequestError(error) { - const code = SAFE_REQUEST_ERROR_CODES.has(error?.code) - ? error.code - : 'UNKNOWN' - const cause = new Error(code) - cause.code = code - return new Error('dev quit request failed', { cause }) -} - -export async function readPrivateInstanceRecord(path, expectedUid) { - let handle - try { - handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW) - const stat = await handle.stat() - if (!stat.isFile()) { - throw new Error('instance record must be an ordinary file') - } - if (stat.uid !== expectedUid) { - throw new Error('instance record has the wrong owner') - } - if ((stat.mode & 0o777) !== 0o600) { - throw new Error('instance record permissions must be 0600') - } - const contents = await handle.readFile({ encoding: 'utf8' }) - let record - try { - record = JSON.parse(contents) - } catch { - throw new Error('instance record is not valid JSON') - } - return validateInstanceRecord(record) - } finally { - await handle?.close() - } -} - -function postDevQuit(record, timeoutMs, requestImpl) { - return new Promise((resolve, reject) => { - let settled = false - const settle = (callback, value) => { - if (settled) return - settled = true - callback(value) - } - const outgoing = requestImpl( - { - host: '127.0.0.1', - port: record.port, - path: '/commands/dev/quit', - method: 'POST', - agent: false, - headers: { - 'X-Instance-Token': record.token, - }, - }, - (response) => { - response.on('aborted', () => {}) - response.on('error', () => {}) - response.on('close', () => {}) - settle(resolve, response.statusCode) - response.destroy() - }, - ) - outgoing.once('error', (error) => settle(reject, error)) - outgoing.setTimeout(timeoutMs, () => { - const error = new Error('dev quit request timed out') - error.code = 'ETIMEDOUT' - outgoing.destroy(error) - }) - outgoing.end() - }) -} - -export async function requestDevQuit( - recordOrReader, - { - timeoutMs = DEFAULT_TIMEOUT_MS, - retryDelayMs = DEFAULT_RETRY_DELAY_MS, - requestImpl = request, - now = Date.now, - sleep = delay, - } = {}, -) { - const deadline = now() + timeoutMs - const readRecord = - typeof recordOrReader === 'function' - ? recordOrReader - : async () => recordOrReader - - while (now() < deadline) { - let record - try { - record = validateInstanceRecord(await readRecord()) - } catch (error) { - if (error?.code !== 'ENOENT') { - throw error - } - await sleep(Math.min(retryDelayMs, Math.max(0, deadline - now()))) - continue - } - - const remainingMs = Math.max(1, deadline - now()) - let status - try { - status = await postDevQuit(record, remainingMs, requestImpl) - } catch (error) { - if (!TRANSIENT_REQUEST_ERRORS.has(error?.code)) { - throw safeRequestError(error) - } - await sleep(Math.min(retryDelayMs, Math.max(0, deadline - now()))) - continue - } - if (status === 202) { - return record - } - if (status !== 503) { - throw new Error( - `dev quit request returned HTTP ${status ?? 'without a status'}`, - ) - } - await sleep(Math.min(retryDelayMs, Math.max(0, deadline - now()))) - } - - throw new Error('timed out waiting for the dev quit request to be accepted') -} - -function portAcceptsConnections(port, timeoutMs) { - return new Promise((resolve) => { - const socket = connect({ host: '127.0.0.1', port }) - let settled = false - const finish = (isOpen) => { - if (settled) return - settled = true - socket.destroy() - resolve(isOpen) - } - socket.once('connect', () => finish(true)) - socket.once('error', () => finish(false)) - socket.setTimeout(Math.max(1, Math.min(1_000, timeoutMs)), () => - finish(false), - ) - }) -} - -export async function waitForPortClosed( - port, - { - timeoutMs = DEFAULT_TIMEOUT_MS, - retryDelayMs = DEFAULT_RETRY_DELAY_MS, - probePort = portAcceptsConnections, - now = Date.now, - sleep = delay, - } = {}, -) { - if (!Number.isInteger(port) || port < 1 || port > 65_535) { - throw new Error('invalid loopback port') - } - const deadline = now() + timeoutMs - while (now() < deadline) { - const remainingMs = deadline - now() - if (!(await probePort(port, remainingMs))) { - return - } - await sleep(Math.min(retryDelayMs, Math.max(0, deadline - now()))) - } - throw new Error('timed out waiting for the dev endpoint to close') -} - -export function createMacosShutdownController({ - requestQuit, - waitForPortClosed: waitForClosed, - waitForChildExit, - terminateGroup, - finalizeGroup = terminateGroup, - exit, - report = (message) => console.error(message), - timeoutMs = DEFAULT_TIMEOUT_MS, - forceTimeoutMs = 2_000, - now = Date.now, -}) { - let signalCount = 0 - let forced = false - let forcedPromise - let groupFinalizationPromise - - const remainingBudget = (deadline) => { - const remaining = deadline - now() - if (remaining <= 0) { - throw new Error('timed out waiting for graceful dev shutdown') - } - return remaining - } - - const finalizeOnce = (operation, budget) => { - groupFinalizationPromise ??= Promise.resolve().then(() => operation(budget)) - return groupFinalizationPromise - } - - const gracefulShutdown = async () => { - const deadline = now() + timeoutMs - try { - const record = await requestQuit(remainingBudget(deadline)) - if (forced) return false - await waitForClosed(record.port, remainingBudget(deadline)) - if (forced) return false - await waitForChildExit(remainingBudget(deadline)) - if (forced) return false - await finalizeOnce(finalizeGroup, remainingBudget(deadline)) - if (forced) return false - exit(130) - return true - } catch (error) { - report( - `Graceful dev shutdown failed: ${error instanceof Error ? error.message : String(error)}`, - ) - return false - } - } - - return { - handleSigint() { - signalCount += 1 - if (signalCount === 1) { - return gracefulShutdown() - } - if (!forcedPromise) { - forced = true - forcedPromise = finalizeOnce(terminateGroup, forceTimeoutMs).then( - () => { - exit(130) - return true - }, - ) - } - return forcedPromise - }, - } -} diff --git a/scripts/dev-service.mjs b/scripts/dev-service.mjs deleted file mode 100644 index 6fc9d69af..000000000 --- a/scripts/dev-service.mjs +++ /dev/null @@ -1,181 +0,0 @@ -import { execFileSync, spawn } from 'node:child_process' -import { access } from 'node:fs/promises' -import { dirname, join, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' - -export const developmentServiceDirectoryEnvironment = - 'CLASH_VERGE_DEV_SERVICE_DIR' -const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') -const serviceRepository = resolve( - repositoryRoot, - '..', - 'clash-verge-service-ipc', -) -const serviceManifest = join(serviceRepository, 'Cargo.toml') -export const developmentServiceWatchPaths = [ - 'src', - 'resources', - 'Cargo.toml', - 'Cargo.lock', -].map((name) => join(serviceRepository, name)) - -function run(command, args, options = {}) { - return new Promise((resolvePromise, reject) => { - const child = spawn(command, args, { - env: options.env ?? process.env, - stdio: options.stdio ?? 'inherit', - windowsHide: true, - }) - let stdout = '' - child.stdout?.setEncoding('utf8') - child.stdout?.on('data', (chunk) => { - stdout += chunk - }) - child.once('error', reject) - child.once('close', (code, signal) => { - if (code === 0) { - resolvePromise(stdout) - return - } - const error = new Error( - `${command} failed with ${signal ? `signal ${signal}` : `exit code ${code}`}`, - ) - error.exitCode = code - reject(error) - }) - }) -} - -async function checkDevelopmentServiceVersion() { - const [guiOutput, daemonOutput] = await Promise.all([ - run( - 'cargo', - [ - 'metadata', - '--locked', - '--format-version=1', - '--manifest-path', - join(repositoryRoot, 'Cargo.toml'), - ], - { stdio: ['inherit', 'pipe', 'inherit'] }, - ), - run( - 'cargo', - [ - 'metadata', - '--locked', - '--no-deps', - '--format-version=1', - '--manifest-path', - serviceManifest, - ], - { stdio: ['inherit', 'pipe', 'inherit'] }, - ), - ]) - const gui = JSON.parse(guiOutput) - const daemon = JSON.parse(daemonOutput).packages.find( - (pkg) => resolve(pkg.manifest_path) === serviceManifest, - ) - const app = gui.packages.find( - (pkg) => - resolve(pkg.manifest_path) === - join(repositoryRoot, 'src-tauri', 'Cargo.toml'), - ) - const dependency = gui.resolve?.nodes - .find((node) => node.id === app?.id) - ?.deps.find((dep) => dep.name === 'clash_verge_service_ipc') - const sdk = gui.packages.find((pkg) => pkg.id === dependency?.pkg) - if (!daemon || !sdk) - throw new Error('Cargo did not resolve the development Service and GUI SDK') - if (daemon.version !== sdk.version) { - throw new Error( - `Development Service ${daemon.version} does not match the resolved GUI SDK ${sdk.version} (${sdk.manifest_path}). ` + - 'Align the GUI dependency explicitly before starting development. Building the sibling daemon does not update the SDK.', - ) - } -} - -export async function prepareDevelopmentService() { - await access(serviceManifest) - await checkDevelopmentServiceVersion() - const output = await run( - 'cargo', - [ - 'build', - '--manifest-path', - serviceManifest, - '--target-dir', - process.env.CARGO_TARGET_DIR || - join(serviceRepository, 'target', 'development'), - '--features', - 'standalone,client,development-channel', - '--bins', - '--message-format=json-render-diagnostics', - ], - { stdio: ['inherit', 'pipe', 'inherit'] }, - ) - - const artifacts = new Map() - for (const line of output.split(/\r?\n/).filter(Boolean)) { - const artifact = JSON.parse(line) - if ( - artifact.reason === 'compiler-artifact' && - resolve(artifact.manifest_path) === serviceManifest && - artifact.target.kind.includes('bin') && - artifact.executable - ) { - artifacts.set(artifact.target.name, resolve(artifact.executable)) - } - } - const executables = [ - 'clash-verge-service', - 'clash-verge-service-install', - 'clash-verge-service-uninstall', - 'service-integration-driver', - ].map((name) => { - const executable = artifacts.get(name) - if (!executable) - throw new Error(`Cargo did not report the ${name} executable`) - return executable - }) - const serviceDirectory = dirname(executables[0]) - for (const executable of executables) { - if (dirname(executable) !== serviceDirectory) { - throw new Error( - 'Development service tools were built in different directories', - ) - } - await access(executable) - } - return serviceDirectory -} - -export async function ensureDevelopmentService({ - platform = process.platform, -} = {}) { - const serviceDirectory = await prepareDevelopmentService() - const extension = platform === 'win32' ? '.exe' : '' - const installer = join( - serviceDirectory, - `clash-verge-service-install${extension}`, - ) - const host = execFileSync('rustc', ['-vV'], { encoding: 'utf8' }).match( - /^host: (.+)$/m, - )?.[1] - if (!host) throw new Error('rustc did not report its host target') - const args = ['--prepare-install', '--ensure'] - for (const name of ['verge-mihomo', 'verge-mihomo-alpha']) { - args.push( - '--core', - `${name}${extension}`, - join( - repositoryRoot, - 'src-tauri', - 'sidecar', - `${name}-${host}${extension}`, - ), - ) - } - await run(installer, args) - return serviceDirectory -} diff --git a/scripts/dev.mjs b/scripts/dev.mjs deleted file mode 100644 index 7235a73d6..000000000 --- a/scripts/dev.mjs +++ /dev/null @@ -1,570 +0,0 @@ -import { spawn } from 'node:child_process' -import { join } from 'node:path' -import { fileURLToPath, pathToFileURL } from 'node:url' - -import { - createMacosShutdownController, - readPrivateInstanceRecord, - requestDevQuit, - waitForPortClosed, -} from './dev-control.mjs' -import { - developmentServiceDirectoryEnvironment, - developmentServiceWatchPaths, - ensureDevelopmentService, - prepareDevelopmentService, -} from './dev-service.mjs' - -const FORCE_GRACE_MS = 2_000 -const SHUTDOWN_TIMEOUT_MS = 10_000 -const FORCE_POLL_MS = 50 -const ANCHOR_EXIT_RESERVE_MS = 100 - -export function buildTauriInvocation( - mode, - environment = process.env, - platform = process.platform, -) { - const env = { ...environment, RUST_BACKTRACE: 'full' } - const features = mode === 'sidecar' ? 'verge-dev,dev-sidecar' : 'verge-dev' - const args = ['exec', 'tauri', 'dev', '-f', features] - if (mode === 'trace') { - env.RUSTFLAGS = '--cfg tokio_unstable' - args.push('tokio-trace') - } - for (const path of developmentServiceWatchPaths) { - args.push('--additional-watch-folders', path) - } - return { - command: 'pnpm', - args, - env, - detached: platform === 'darwin', - } -} - -function wait(milliseconds) { - return new Promise((resolve) => setTimeout(resolve, milliseconds)) -} - -function childLifecycle(child) { - const spawned = new Promise((resolve, reject) => { - child.once('spawn', resolve) - child.once('error', reject) - }) - spawned.catch(() => {}) - const result = new Promise((resolve, reject) => { - child.once('error', reject) - child.once('exit', (code, signal) => resolve({ code, signal })) - }) - result.catch(() => {}) - return { result, spawned } -} - -function waitForPromise(promise, timeoutMs, message) { - if (timeoutMs <= 0) return Promise.reject(new Error(message)) - let timeout - return Promise.race([ - promise, - new Promise((_, reject) => { - timeout = setTimeout(() => reject(new Error(message)), timeoutMs) - }), - ]).finally(() => clearTimeout(timeout)) -} - -function signalDetachedGroup(childPid, signal, signalGroup) { - if (!Number.isInteger(childPid) || childPid <= 0) { - throw new Error('dev command did not provide a valid child PID') - } - try { - signalGroup(-childPid, signal) - return true - } catch (error) { - if (error?.code === 'ESRCH') return false - throw error - } -} - -export async function terminateDetachedGroup( - childPid, - { - signalGroup = process.kill.bind(process), - sleep = wait, - now = Date.now, - graceMs = FORCE_GRACE_MS, - pollMs = FORCE_POLL_MS, - } = {}, -) { - if (!signalDetachedGroup(childPid, 'SIGTERM', signalGroup)) return - - const deadline = now() + graceMs - while (now() < deadline) { - await sleep(Math.min(pollMs, deadline - now())) - if (now() < deadline && !signalDetachedGroup(childPid, 0, signalGroup)) { - return - } - } - signalDetachedGroup(childPid, 'SIGKILL', signalGroup) -} - -export function mirrorChildExit( - { code, signal }, - { - exit = (exitCode) => process.exit(exitCode), - signalSelf = (childSignal) => { - process.removeAllListeners(childSignal) - process.kill(process.pid, childSignal) - }, - } = {}, -) { - if (code !== null) { - exit(code) - return - } - if (signal) { - signalSelf(signal) - return - } - exit(1) -} - -function defaultInstallSigint(handler) { - process.on('SIGINT', handler) - return () => process.off('SIGINT', handler) -} - -function defaultInstallSigterm(handler) { - process.on('SIGTERM', handler) - return () => process.off('SIGTERM', handler) -} - -function defaultInstallMessage(handler) { - process.on('message', handler) - return () => process.off('message', handler) -} - -function defaultInstallDisconnect(handler) { - process.on('disconnect', handler) - return () => process.off('disconnect', handler) -} - -function sendToParent(message) { - if (process.connected && process.send) process.send(message, () => {}) -} - -export async function runDevAnchor(mode, dependencies = {}) { - if (mode !== 'dev' && mode !== 'trace' && mode !== 'sidecar') { - throw new Error('usage: node scripts/dev.mjs --anchor ') - } - - const environment = dependencies.environment ?? process.env - const spawnChild = dependencies.spawnChild ?? spawn - const send = dependencies.send ?? sendToParent - const exit = dependencies.exit ?? ((code) => process.exit(code)) - const report = dependencies.report ?? ((message) => console.error(message)) - const ownPid = dependencies.ownPid ?? process.pid - const terminateGroup = - dependencies.terminateGroup ?? - ((pid) => terminateDetachedGroup(pid, { graceMs: FORCE_GRACE_MS })) - let released = false - let disconnectCleanup - - const installSigterm = dependencies.installSigterm ?? defaultInstallSigterm - installSigterm(() => {}) - const installMessage = dependencies.installMessage ?? defaultInstallMessage - installMessage((message) => { - if (message?.type === 'release' && !disconnectCleanup) { - released = true - exit(0) - } - }) - const installDisconnect = - dependencies.installDisconnect ?? defaultInstallDisconnect - installDisconnect(() => { - if (released || disconnectCleanup) return - disconnectCleanup = Promise.resolve() - .then(() => terminateGroup(ownPid)) - .then(() => exit(1)) - .catch((error) => { - report(`Dev anchor cleanup failed: ${error.message}`) - exit(1) - }) - }) - - const invocation = buildTauriInvocation(mode, environment, 'darwin') - let inner - try { - inner = spawnChild(invocation.command, invocation.args, { - env: invocation.env, - detached: false, - stdio: 'inherit', - }) - } catch { - send({ type: 'inner-error', code: 'SPAWN_FAILED' }) - return - } - if (!inner || typeof inner.once !== 'function') { - send({ type: 'inner-error', code: 'SPAWN_FAILED' }) - return - } - - const innerLifecycle = childLifecycle(inner) - try { - await innerLifecycle.spawned - } catch { - send({ type: 'inner-error', code: 'SPAWN_FAILED' }) - return - } - send({ type: 'ready' }) - innerLifecycle.result.then( - ({ code, signal }) => send({ type: 'inner-result', code, signal }), - () => send({ type: 'inner-error', code: 'INNER_FAILED' }), - ) -} - -function createAnchorChannel(anchor, anchorResult) { - let innerSettled = false - let readySettled = false - let resolveResult - let rejectResult - let resolveReady - let rejectReady - const innerResult = new Promise((resolve, reject) => { - resolveResult = resolve - rejectResult = reject - }) - const ready = new Promise((resolve, reject) => { - resolveReady = resolve - rejectReady = reject - }) - const settleInner = (callback, value) => { - if (innerSettled) return - innerSettled = true - callback(value) - } - const settleReady = (callback, value) => { - if (readySettled) return - readySettled = true - callback(value) - } - anchor.on('message', (message) => { - if (message?.type === 'ready') { - settleReady(resolveReady) - } else if (message?.type === 'inner-result') { - settleInner(resolveResult, { - code: message.code, - signal: message.signal, - }) - } else if (message?.type === 'inner-error') { - const error = new Error( - `inner dev command failed (${message.code ?? 'UNKNOWN'})`, - ) - settleReady(rejectReady, error) - settleInner(rejectResult, error) - } - }) - anchorResult.then( - () => { - const error = new Error( - 'dev group anchor exited before the inner command completed', - ) - settleReady(rejectReady, error) - settleInner(rejectResult, error) - }, - () => { - const error = new Error('dev group anchor failed') - settleReady(rejectReady, error) - settleInner(rejectResult, error) - }, - ) - ready.catch(() => {}) - innerResult.catch(() => {}) - return { innerResult, ready } -} - -function sendRelease(anchor) { - return new Promise((resolve, reject) => { - if (typeof anchor.send !== 'function') { - reject(new Error('dev group anchor IPC is unavailable')) - return - } - anchor.send({ type: 'release' }, (error) => { - if (error) reject(new Error('dev group anchor release failed')) - else resolve() - }) - }) -} - -function unsafeAnchorError() { - return new Error('dev group anchor identity is unsafe') -} - -export async function runDevCommand(mode, dependencies = {}) { - if (mode !== 'dev' && mode !== 'trace' && mode !== 'sidecar') { - throw new Error('usage: node scripts/dev.mjs ') - } - - const platform = dependencies.platform ?? process.platform - const environment = dependencies.environment ?? process.env - const spawnChild = dependencies.spawnChild ?? spawn - const exit = dependencies.exit ?? ((code) => process.exit(code)) - const report = dependencies.report ?? ((message) => console.error(message)) - const mirrorResult = dependencies.mirrorResult ?? mirrorChildExit - let recordPath - let pendingSigints = 0 - let dispatchSigint = () => { - pendingSigints += 1 - } - let removeSigint = () => {} - - if (platform === 'darwin') { - if (!environment.HOME) { - throw new Error('HOME is required to locate the dev instance record') - } - recordPath = join( - environment.HOME, - 'Library/Application Support/io.github.clash-verge-rev.clash-verge-rev.dev/singleton-instance.json', - ) - const installSigint = dependencies.installSigint ?? defaultInstallSigint - removeSigint = installSigint(() => dispatchSigint()) ?? (() => {}) - } - - const tauriInvocation = buildTauriInvocation(mode, environment, platform) - const anchorInvocation = { - command: dependencies.execPath ?? process.execPath, - args: [fileURLToPath(import.meta.url), '--anchor', mode], - env: tauriInvocation.env, - detached: true, - } - const invocation = platform === 'darwin' ? anchorInvocation : tauriInvocation - let child - try { - child = spawnChild(invocation.command, invocation.args, { - shell: platform === 'win32', - env: invocation.env, - detached: invocation.detached, - stdio: - platform === 'darwin' - ? ['inherit', 'inherit', 'inherit', 'ipc'] - : 'inherit', - }) - } catch (error) { - removeSigint() - throw error - } - if (!child || typeof child.once !== 'function') { - removeSigint() - throw new Error('dev command failed to return a child process') - } - const outerLifecycle = childLifecycle(child) - - if (platform !== 'darwin') { - mirrorResult(await outerLifecycle.result) - return - } - - let groupState = 'safe' - let finalKillSent = false - const anchorChannel = createAnchorChannel(child, outerLifecycle.result) - outerLifecycle.result.then( - () => { - if (groupState !== 'released' && !finalKillSent) groupState = 'unsafe' - }, - () => { - groupState = 'unsafe' - }, - ) - - try { - await outerLifecycle.spawned - if (!Number.isInteger(child.pid) || child.pid <= 0) { - throw new Error('dev command did not provide a valid child PID') - } - await waitForPromise( - anchorChannel.ready, - SHUTDOWN_TIMEOUT_MS, - 'timed out waiting for the dev group anchor to initialize', - ) - } catch (error) { - removeSigint() - throw error - } - - const anchorPid = child.pid - const innerResult = anchorChannel.innerResult - let intercepted = false - let observedShutdownOperation - let anchorFinalization - - const signalGroup = dependencies.signalGroup ?? process.kill.bind(process) - const guardedSignalGroup = (pid, signal) => { - if (groupState === 'unsafe') throw unsafeAnchorError() - if (signal === 'SIGKILL') finalKillSent = true - try { - signalGroup(pid, signal) - } catch (error) { - if (error?.code === 'ESRCH') { - groupState = 'unsafe' - throw unsafeAnchorError() - } - throw error - } - } - - const assertGroupAbsent = () => { - try { - signalGroup(-anchorPid, 0) - } catch (error) { - if (error?.code === 'ESRCH') return - throw new Error('unable to verify that the dev process group exited', { - cause: error, - }) - } - throw new Error('dev process group still exists after anchor exit') - } - - const forceAnchor = async (budget) => { - if (groupState === 'unsafe') throw unsafeAnchorError() - groupState = 'terminating' - if (dependencies.terminateGroup) { - await dependencies.terminateGroup(anchorPid, budget) - return - } - const deadline = Date.now() + budget - await terminateDetachedGroup(anchorPid, { - graceMs: Math.max(0, budget - ANCHOR_EXIT_RESERVE_MS), - signalGroup: guardedSignalGroup, - }) - await waitForPromise( - outerLifecycle.result, - Math.max(1, deadline - Date.now()), - 'timed out waiting for the dev group anchor to exit', - ) - } - - const releaseAnchor = async (budget) => { - if (groupState === 'unsafe') throw unsafeAnchorError() - groupState = 'released' - const deadline = Date.now() + budget - await waitForPromise( - sendRelease(child), - Math.max(1, deadline - Date.now()), - 'timed out releasing the dev group anchor', - ) - await waitForPromise( - outerLifecycle.result, - Math.max(1, deadline - Date.now()), - 'timed out waiting for the released dev group anchor', - ) - assertGroupAbsent() - } - - const finalizeAnchorOnce = (kind, budget) => { - anchorFinalization ??= - kind === 'release' ? releaseAnchor(budget) : forceAnchor(budget) - return anchorFinalization - } - - const getUid = dependencies.getUid ?? (() => process.getuid()) - const requestQuit = - dependencies.requestQuit ?? - ((budget) => - requestDevQuit(() => readPrivateInstanceRecord(recordPath, getUid()), { - timeoutMs: budget, - })) - - const controller = createMacosShutdownController({ - requestQuit, - waitForPortClosed: (port, budget) => - (dependencies.waitForPortClosed ?? waitForPortClosed)(port, { - timeoutMs: budget, - }), - waitForChildExit: (budget) => - waitForPromise( - innerResult, - budget, - 'timed out waiting for the inner dev command to exit', - ), - finalizeGroup: (budget) => finalizeAnchorOnce('release', budget), - terminateGroup: (budget) => finalizeAnchorOnce('force', budget), - exit, - report, - timeoutMs: SHUTDOWN_TIMEOUT_MS, - }) - - dispatchSigint = () => { - intercepted = true - const operation = controller.handleSigint() - if (operation !== observedShutdownOperation) { - observedShutdownOperation = operation - void operation.catch((error) => { - report(`Forced dev shutdown failed: ${error.message}`) - exit(1) - }) - } - } - const queuedSigints = pendingSigints - pendingSigints = 0 - for (let index = 0; index < queuedSigints; index += 1) { - dispatchSigint() - } - - innerResult.then( - async (result) => { - if (intercepted) return - try { - await finalizeAnchorOnce('release', SHUTDOWN_TIMEOUT_MS) - if (!intercepted) mirrorResult(result) - } catch (error) { - if (!intercepted) { - report(`Dev command failed: ${error.message}`) - exit(1) - } - } - }, - (error) => { - if (!intercepted) { - report(`Dev command failed: ${error.message}`) - exit(1) - } - }, - ) -} - -export async function prepareDevRuntime(mode, dependencies = {}) { - const ensureService = dependencies.ensureService ?? ensureDevelopmentService - const prepareService = - dependencies.prepareService ?? prepareDevelopmentService - let serviceDirectory - if (mode === 'service') { - serviceDirectory = await ensureService() - } else if (mode === 'dev' || mode === 'trace' || mode === 'sidecar') { - serviceDirectory = await prepareService() - } - return { - mode: mode === 'service' ? 'dev' : mode, - serviceDirectory, - } -} - -async function run() { - if (process.argv[2] === '--anchor') { - await runDevAnchor(process.argv[3]) - } else { - const { mode, serviceDirectory } = await prepareDevRuntime(process.argv[2]) - if (serviceDirectory) { - process.env[developmentServiceDirectoryEnvironment] = serviceDirectory - } - await runDevCommand(mode) - } -} - -if ( - process.argv[1] && - pathToFileURL(process.argv[1]).href === import.meta.url -) { - run().catch((error) => { - console.error(`Unable to start dev command: ${error.message}`) - process.exit(1) - }) -} diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 58272bea8..dd0359bb4 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -17,8 +17,6 @@ crate-type = ["staticlib", "cdylib", "rlib"] [features] default = ["custom-protocol"] custom-protocol = ["tauri/custom-protocol"] -verge-dev = ["clash-verge-logging/color", "clash_verge_service_ipc/development-channel"] -dev-sidecar = ["verge-dev"] tauri-dev = ["dep:tauri-plugin-devtools"] tokio-trace = ["clash-verge-logging/tokio-trace"] chrome-trace = ["clash-verge-logging/chrome-trace"] @@ -93,7 +91,7 @@ tracing = { workspace = true } tauri-plugin-devtools = { version = "2.2.3", optional = true } tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" } async-trait = "0.1.92" -clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.8.1", version = "2.8.1", features = [ +clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [ "client", ] } arc-swap = "1.9.5" diff --git a/src-tauri/src/config/clash.rs b/src-tauri/src/config/clash.rs index 59687278c..8c8de6798 100644 --- a/src-tauri/src/config/clash.rs +++ b/src-tauri/src/config/clash.rs @@ -99,7 +99,7 @@ impl IClashTemp { "tauri://localhost", "http://tauri.localhost", // Only enable this in dev mode - #[cfg(feature = "verge-dev")] + #[cfg(debug_assertions)] "http://localhost:3000", "https://yacd.metacubex.one", "https://metacubex.github.io", diff --git a/src-tauri/src/core/service.rs b/src-tauri/src/core/service.rs index e47b7bed4..a73079279 100644 --- a/src-tauri/src/core/service.rs +++ b/src-tauri/src/core/service.rs @@ -269,9 +269,7 @@ static MACOS_SERVICE_INSTALL_MARKERS: LazyLock> = LazyLock::new(|| { "/Library/PrivilegedHelperTools/{}.bundle", clash_verge_service_ipc::MACOS_SERVICE_ID ), - #[cfg(not(feature = "verge-dev"))] "/Library/LaunchDaemons/io.github.clashverge.helper.plist".to_owned(), - #[cfg(not(feature = "verge-dev"))] "/Library/PrivilegedHelperTools/io.github.clashverge.helper".to_owned(), ] }); @@ -330,13 +328,11 @@ pub(crate) fn service_stop_reason() -> Result> { if status.current_state != ServiceState::Stopped { return Ok(None); } - // The development channel registers an on-demand start. - if !cfg!(feature = "verge-dev") - && service - .query_config() - .context("failed to query Windows service configuration")? - .start_type - != ServiceStartType::AutoStart + if service + .query_config() + .context("failed to query Windows service configuration")? + .start_type + != ServiceStartType::AutoStart { return Ok(Some(SERVICE_NOT_AUTO_STARTED)); } @@ -373,201 +369,6 @@ pub(crate) fn trusted_service_evidence() -> Result { /// Stateless legacy façade over [`RUN_STATE`] retained for existing call sites. pub struct ServiceManager; -#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))] -static SERVICE_CORE_STAGING_GENERATION: AtomicU64 = AtomicU64::new(0); - -#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))] -fn create_service_core_staging_file(directory: &Path, core_name: &std::ffi::OsStr) -> Result<(PathBuf, std::fs::File)> { - use crate::utils::retry::{RetryError, RetryPolicy, retry_sync}; - retry_sync( - RetryPolicy::fixed( - std::num::NonZeroUsize::MIN.saturating_add(31), - std::time::Duration::ZERO, - ), - |_| { - let generation = SERVICE_CORE_STAGING_GENERATION.fetch_add(1, Ordering::Relaxed); - let temporary_name = format!( - ".{}.{}.{generation}.tmp", - core_name.to_string_lossy(), - std::process::id() - ); - let temporary_path = directory.join(temporary_name); - match std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&temporary_path) - { - Ok(file) => Ok((temporary_path, file)), - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - Err(RetryError::Retry(anyhow::anyhow!( - "failed to create a unique temporary development Service core in {}", - directory.display() - ))) - } - Err(error) => Err(RetryError::Stop(anyhow::Error::from(error).context({ - format!( - "failed to create temporary development Service core {}", - temporary_path.display() - ) - }))), - } - }, - ) -} - -#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))] -fn service_core_path_for(source: &Path, home: Option<&Path>, stage_for_macos_dev: bool) -> Result { - service_core_path_for_with_publisher( - source, - home, - stage_for_macos_dev, - "service-core", - |temporary_path, final_path| { - std::fs::rename(temporary_path, final_path).with_context(|| { - format!( - "failed to publish development Service core {} over {}", - temporary_path.display(), - final_path.display() - ) - }) - }, - ) -} - -#[cfg(any(all(target_os = "macos", feature = "verge-dev"), all(test, unix)))] -fn service_tool_path_for(source: &Path, home: Option<&Path>, stage_for_macos_dev: bool) -> Result { - service_core_path_for_with_publisher( - source, - home, - stage_for_macos_dev, - "service-tools", - |temporary_path, final_path| { - std::fs::rename(temporary_path, final_path).with_context(|| { - format!( - "failed to publish development Service tool {} over {}", - temporary_path.display(), - final_path.display() - ) - }) - }, - ) -} - -#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))] -#[cfg_attr(not(unix), allow(unreachable_code, unused_assignments, unused_variables))] -fn service_core_path_for_with_publisher( - source: &Path, - home: Option<&Path>, - stage_for_macos_dev: bool, - staging_directory_name: &str, - publisher: F, -) -> Result -where - F: FnOnce(&Path, &Path) -> Result<()>, -{ - if !stage_for_macos_dev { - return Ok(source.to_path_buf()); - } - - let home = home - .filter(|path| !path.as_os_str().is_empty()) - .context("HOME is unavailable for development Service core staging")?; - let core_name = source - .file_name() - .filter(|name| !name.is_empty()) - .with_context(|| format!("development Service core source has no file name: {}", source.display()))?; - let source_metadata = std::fs::symlink_metadata(source) - .with_context(|| format!("failed to inspect development Service core source {}", source.display()))?; - if !source_metadata.file_type().is_file() { - bail!( - "development Service core source is not an ordinary file: {}", - source.display() - ); - } - let mut source_file = std::fs::File::open(source) - .with_context(|| format!("failed to open development Service core source {}", source.display()))?; - - let staging_directory = home - .join("Applications/.clash-verge-rev-dev") - .join(staging_directory_name); - std::fs::create_dir_all(&staging_directory).with_context(|| { - format!( - "failed to create development Service core staging directory {}", - staging_directory.display() - ) - })?; - let final_path = staging_directory.join(core_name); - let (temporary_path, mut temporary_file) = create_service_core_staging_file(&staging_directory, core_name)?; - - let publish_result = (|| -> Result<()> { - std::io::copy(&mut source_file, &mut temporary_file).with_context(|| { - format!( - "failed to copy development Service core from {} to {}", - source.display(), - temporary_path.display() - ) - })?; - - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - - let mut permissions = temporary_file - .metadata() - .with_context(|| format!("failed to inspect temporary Service core {}", temporary_path.display()))? - .permissions(); - permissions.set_mode(0o755); - temporary_file.set_permissions(permissions).with_context(|| { - format!( - "failed to set executable permissions on temporary Service core {}", - temporary_path.display() - ) - })?; - } - #[cfg(not(unix))] - bail!("development Service core staging requires Unix executable permissions"); - - temporary_file - .sync_all() - .with_context(|| format!("failed to sync temporary Service core {}", temporary_path.display()))?; - drop(temporary_file); - publisher(&temporary_path, &final_path)?; - Ok(()) - })(); - - if let Err(error) = publish_result { - match std::fs::remove_file(&temporary_path) { - Ok(()) => return Err(error), - Err(cleanup_error) if cleanup_error.kind() == std::io::ErrorKind::NotFound => return Err(error), - Err(cleanup_error) => { - return Err(error).with_context(|| { - format!( - "failed to clean temporary development Service core {}: {cleanup_error}", - temporary_path.display() - ) - }); - } - } - } - - Ok(final_path) -} - -#[cfg(target_os = "macos")] -#[cfg_attr(not(feature = "verge-dev"), allow(clippy::unnecessary_wraps))] -fn macos_service_tool_path(source: &Path) -> Result { - #[cfg(feature = "verge-dev")] - { - let home = std::env::var_os("HOME") - .filter(|value| !value.is_empty()) - .map(PathBuf::from); - service_tool_path_for(source, home.as_deref(), true) - } - - #[cfg(not(feature = "verge-dev"))] - Ok(source.to_path_buf()) -} - fn service_core_path(clash_core: &str, bin_ext: &str) -> Result { let sibling = current_exe() .map_err(|error| { @@ -577,18 +378,8 @@ fn service_core_path(clash_core: &str, bin_ext: &str) -> Result { })? .with_file_name(format!("{clash_core}{bin_ext}")); - #[cfg(all(target_os = "macos", feature = "verge-dev"))] - { - let home = std::env::var_os("HOME") - .filter(|value| !value.is_empty()) - .map(PathBuf::from); - service_core_path_for(&sibling, home.as_deref(), true) - } - - #[cfg(not(all(target_os = "macos", feature = "verge-dev")))] Ok(sibling) } - #[cfg(target_os = "macos")] fn escape_osascript_double_quoted_string(value: &str) -> String { value.replace('\\', "\\\\").replace('"', "\\\"") @@ -599,24 +390,12 @@ fn shell_single_quote(value: &str) -> String { format!("'{}'", value.replace('\'', r"'\''")) } -fn packaged_service_tool_path(file_name: &str, packaged_path: impl FnOnce() -> Result) -> Result { - #[cfg(feature = "verge-dev")] - { - drop(packaged_path); - let directory = std::env::var_os("CLASH_VERGE_DEV_SERVICE_DIR") - .context("CLASH_VERGE_DEV_SERVICE_DIR is missing from the development session")?; - let directory = PathBuf::from(directory); - if !directory.is_absolute() { - bail!("CLASH_VERGE_DEV_SERVICE_DIR must be an absolute path"); - } - Ok(directory.join(file_name)) - } - - #[cfg(not(feature = "verge-dev"))] - { - let _ = file_name; - packaged_path() +fn uninstaller_tool_path(packaged_path: impl FnOnce() -> Result) -> Result { + let uninstall_path = packaged_path()?; + if !uninstall_path.exists() { + bail!(format!("uninstaller not found: {uninstall_path:?}")); } + Ok(uninstall_path) } #[cfg(target_os = "windows")] @@ -647,14 +426,6 @@ pub(super) fn run_maybe_elevated(program: &Path, hide_window: bool) -> Result Result) -> Result { - let uninstall_path = packaged_service_tool_path(file_name, packaged_path)?; - if !uninstall_path.exists() { - bail!(format!("uninstaller not found: {uninstall_path:?}")); - } - Ok(uninstall_path) -} - fn ensure_uninstall_success(status: &std::process::ExitStatus) -> Result<()> { if !status.success() { bail!( @@ -669,9 +440,8 @@ fn ensure_uninstall_success(status: &std::process::ExitStatus) -> Result<()> { fn uninstall_service() -> Result<()> { logging!(info, Type::Service, "uninstall service"); - let uninstall_path = uninstaller_tool_path("clash-verge-service-uninstall.exe", || { - Ok(dirs::service_path()?.with_file_name("clash-verge-service-uninstall.exe")) - })?; + let uninstall_path = + uninstaller_tool_path(|| Ok(dirs::service_path()?.with_file_name("clash-verge-service-uninstall.exe")))?; let status = run_maybe_elevated(&uninstall_path, true)?; ensure_uninstall_success(&status) @@ -681,7 +451,7 @@ fn uninstall_service() -> Result<()> { fn uninstall_service() -> Result<()> { logging!(info, Type::Service, "uninstall service"); - let uninstall_path = uninstaller_tool_path("clash-verge-service-uninstall", || { + let uninstall_path = uninstaller_tool_path(|| { Ok(tauri::utils::platform::current_exe()?.with_file_name("clash-verge-service-uninstall")) })?; @@ -729,11 +499,9 @@ fn linux_running_as_root() -> bool { fn uninstall_service() -> Result<()> { logging!(info, Type::Service, "uninstall service"); - let uninstall_path = uninstaller_tool_path("clash-verge-service-uninstall", || { - Ok(dirs::service_path()?.with_file_name("clash-verge-service-uninstall")) - })?; + let uninstall_path = + uninstaller_tool_path(|| Ok(dirs::service_path()?.with_file_name("clash-verge-service-uninstall")))?; - let uninstall_path = macos_service_tool_path(&uninstall_path)?; let uninstall_shell: String = uninstall_path.to_string_lossy().into_owned(); // clash_verge_i18n::sync_locale(Config::verge().await.latest_arc().language.as_deref()); @@ -768,13 +536,10 @@ fn install_service() -> Result<()> { fn invoke_service_install(cores: &[clash_verge_service_ipc::management::CoreSource], core_only: bool) -> Result<()> { let name = format!("clash-verge-service-install{}", std::env::consts::EXE_SUFFIX); - let installer = packaged_service_tool_path(&name, || { - #[cfg(target_os = "linux")] - let executable = tauri::utils::platform::current_exe()?; - #[cfg(not(target_os = "linux"))] - let executable = dirs::service_path()?; - Ok(executable.with_file_name(&name)) - })?; + #[cfg(target_os = "linux")] + let installer = tauri::utils::platform::current_exe()?.with_file_name(&name); + #[cfg(not(target_os = "linux"))] + let installer = dirs::service_path()?.with_file_name(&name); #[cfg(unix)] let gid = Some(tauri_plugin_clash_verge_sysinfo::current_gid()); #[cfg(windows)] @@ -1977,10 +1742,6 @@ impl ServiceManager { } pub async fn detect_startup_status(&self) { - if cfg!(feature = "dev-sidecar") { - RUN_STATE.accept_sidecar(); - return; - } RUN_STATE.observe_current_health().await; } @@ -2148,19 +1909,12 @@ mod tests { use super::{ ServiceHealth, ServiceStatus, capture_generation_before, claim_owner_recovery_generation, generate_service_session_token, mark_service_unavailable_after_owner_loss, owner_recovery_policy, - service_core_path_for, session_matches_status, + session_matches_status, }; - #[cfg(unix)] - use super::{service_core_path_for_with_publisher, service_tool_path_for}; use crate::core::runstate::{FakeEnv, OwnerRecoveryReason, PendingAction, RunStateStore}; use anyhow::bail; use clash_verge_service_ipc::OwnerSessionProof; - #[cfg(unix)] - use std::cell::Cell; - use std::{ - path::{Path, PathBuf}, - sync::atomic::{AtomicU64, Ordering}, - }; + use std::sync::atomic::{AtomicU64, Ordering}; /// A Run State backed by a scripted environment, so these tests never touch the global. fn fake_store() -> RunStateStore { @@ -2176,197 +1930,6 @@ mod tests { ServiceStatus::from_run_state(&store.settled().await) } - static TEST_DIRECTORY_GENERATION: AtomicU64 = AtomicU64::new(0); - - struct TestDirectory(PathBuf); - - impl TestDirectory { - fn new(label: &str) -> anyhow::Result { - let generation = TEST_DIRECTORY_GENERATION.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!( - "clash-verge-rev-service-{label}-{}-{generation}", - std::process::id() - )); - std::fs::create_dir(&path)?; - Ok(Self(path)) - } - - fn path(&self) -> &Path { - &self.0 - } - } - - impl Drop for TestDirectory { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - fn staging_directory(home: &Path) -> PathBuf { - home.join("Applications/.clash-verge-rev-dev/service-core") - } - - #[cfg(unix)] - fn service_tools_staging_directory(home: &Path) -> PathBuf { - home.join("Applications/.clash-verge-rev-dev/service-tools") - } - - #[cfg(unix)] - fn staging_temporary_entries(home: &Path, core_name: &str) -> anyhow::Result> { - let directory = staging_directory(home); - if !directory.exists() { - return Ok(Vec::new()); - } - Ok(std::fs::read_dir(directory)? - .filter_map(Result::ok) - .map(|entry| entry.path()) - .filter(|path| { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with(&format!(".{core_name}.")) && name.ends_with(".tmp")) - }) - .collect()) - } - - #[test] - fn nondevelopment_service_core_selection_preserves_sibling_without_staging() -> anyhow::Result<()> { - let root = TestDirectory::new("release-path")?; - let home = root.path().join("home"); - let source = root.path().join("target/debug/verge-mihomo"); - - let selected = service_core_path_for(&source, Some(&home), false)?; - - assert_eq!(selected, source); - assert!(!staging_directory(&home).exists()); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn development_service_core_uses_exact_layout_and_executable_bytes() -> anyhow::Result<()> { - use std::os::unix::fs::PermissionsExt as _; - - let root = TestDirectory::new("development-path")?; - let home = root.path().join("home"); - let source = root.path().join("verge-mihomo"); - std::fs::write(&source, b"development core")?; - - let selected = service_core_path_for(&source, Some(&home), true)?; - - assert_eq!( - selected, - home.join("Applications/.clash-verge-rev-dev/service-core/verge-mihomo") - ); - assert_eq!(std::fs::read(&selected)?, b"development core"); - let metadata = std::fs::symlink_metadata(&selected)?; - assert!(metadata.file_type().is_file()); - assert_ne!(metadata.permissions().mode() & 0o111, 0); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn development_service_tool_uses_safe_layout_and_executable_bytes() -> anyhow::Result<()> { - use std::os::unix::fs::PermissionsExt as _; - - let root = TestDirectory::new("development-service-tool")?; - let home = root.path().join("home"); - let source = root.path().join("clash-verge-service-install"); - std::fs::write(&source, b"development installer")?; - - let selected = service_tool_path_for(&source, Some(&home), true)?; - - assert_eq!( - selected, - service_tools_staging_directory(&home).join("clash-verge-service-install") - ); - assert_eq!(std::fs::read(&selected)?, b"development installer"); - assert_ne!(std::fs::metadata(&selected)?.permissions().mode() & 0o111, 0); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn development_service_core_refresh_atomically_replaces_bytes() -> anyhow::Result<()> { - let root = TestDirectory::new("refresh")?; - let home = root.path().join("home"); - let source = root.path().join("verge-mihomo"); - std::fs::write(&source, b"first core")?; - let selected = service_core_path_for(&source, Some(&home), true)?; - assert_eq!( - selected, - home.join("Applications/.clash-verge-rev-dev/service-core/verge-mihomo") - ); - - std::fs::write(&source, b"second core")?; - let refreshed = service_core_path_for(&source, Some(&home), true)?; - - assert_eq!(refreshed, selected); - assert_eq!(std::fs::read(&refreshed)?, b"second core"); - assert!(staging_temporary_entries(&home, "verge-mihomo")?.is_empty()); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn failed_development_refresh_preserves_good_core_and_cleans_temporary_entry() -> anyhow::Result<()> { - let root = TestDirectory::new("failed-refresh")?; - let home = root.path().join("home"); - let source = root.path().join("verge-mihomo"); - std::fs::write(&source, b"known good core")?; - let selected = service_core_path_for(&source, Some(&home), true)?; - - std::fs::write(&source, b"replacement core")?; - let publish_attempted = Cell::new(false); - let result = service_core_path_for_with_publisher( - &source, - Some(&home), - true, - "service-core", - |temporary, final_path| { - publish_attempted.set(true); - assert_ne!(temporary, final_path, "publisher must receive the temporary path"); - assert!(std::fs::symlink_metadata(temporary)?.file_type().is_file()); - assert_eq!(std::fs::read(temporary)?, b"replacement core"); - anyhow::bail!("injected post-creation publish failure") - }, - ); - let error = match result { - Ok(path) => anyhow::bail!("failed publication selected {}", path.display()), - Err(error) => error.to_string(), - }; - - assert!(publish_attempted.get()); - assert!(error.contains("injected post-creation publish failure")); - assert_eq!(std::fs::read(&selected)?, b"known good core"); - assert!(staging_temporary_entries(&home, "verge-mihomo")?.is_empty()); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn development_service_core_replaces_final_symlink_without_following_it() -> anyhow::Result<()> { - use std::os::unix::fs::symlink; - - let root = TestDirectory::new("symlink")?; - let home = root.path().join("home"); - let source = root.path().join("verge-mihomo"); - std::fs::write(&source, b"selected core")?; - let final_path = home.join("Applications/.clash-verge-rev-dev/service-core/verge-mihomo"); - std::fs::create_dir_all(final_path.parent().unwrap_or_else(|| Path::new(".")))?; - let symlink_target = root.path().join("must-not-change"); - std::fs::write(&symlink_target, b"target bytes")?; - symlink(&symlink_target, &final_path)?; - - let selected = service_core_path_for(&source, Some(&home), true)?; - - assert_eq!(selected, final_path); - assert!(std::fs::symlink_metadata(&selected)?.file_type().is_file()); - assert_eq!(std::fs::read(&selected)?, b"selected core"); - assert_eq!(std::fs::read(&symlink_target)?, b"target bytes"); - Ok(()) - } - #[test] fn mismatched_active_generation_displaces_local_session() { let proof = OwnerSessionProof { @@ -2460,7 +2023,7 @@ mod tests { &store, super::ServiceStartRefusal { code: code as u16, - core_path: "/development/service-core/verge-mihomo".into(), + core_path: "/fixture/service-core/verge-mihomo".into(), message: "no administrator-approved copy is installed".into(), }, ); @@ -2486,7 +2049,7 @@ mod tests { &store, super::ServiceStartRefusal { code: clash_verge_service_ipc::ServiceErrorCode::ProxyClearFailed as u16, - core_path: "/development/service-core/verge-mihomo".into(), + core_path: "/fixture/service-core/verge-mihomo".into(), message: "SystemConfiguration operation failed: lock preferences (status 3002)".into(), }, ); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 03eeb288d..61382454d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -153,7 +153,7 @@ fn handle_singleton_startup( } pub fn run() -> std::process::ExitCode { - #[cfg(all(target_os = "macos", not(debug_assertions), not(test), not(feature = "verge-dev")))] + #[cfg(all(target_os = "macos", not(debug_assertions), not(test)))] if utils::macos_launch_guard::enforce_before_initialization() == utils::macos_launch_guard::LaunchDisposition::Exit { return std::process::ExitCode::SUCCESS; diff --git a/src-tauri/src/utils/dirs.rs b/src-tauri/src/utils/dirs.rs index 236b3f189..72050001c 100644 --- a/src-tauri/src/utils/dirs.rs +++ b/src-tauri/src/utils/dirs.rs @@ -8,14 +8,14 @@ use std::{ }; use tauri::Manager as _; -#[cfg(not(feature = "verge-dev"))] +#[cfg(not(debug_assertions))] pub static APP_ID: &str = "io.github.clash-verge-rev.clash-verge-rev"; -#[cfg(not(feature = "verge-dev"))] +#[cfg(not(debug_assertions))] pub static BACKUP_DIR: &str = "clash-verge-rev-backup"; -#[cfg(feature = "verge-dev")] +#[cfg(debug_assertions)] pub static APP_ID: &str = "io.github.clash-verge-rev.clash-verge-rev.dev"; -#[cfg(feature = "verge-dev")] +#[cfg(debug_assertions)] pub static BACKUP_DIR: &str = "clash-verge-rev-backup-dev"; pub static CLASH_CONFIG: &str = "config.yaml"; @@ -219,9 +219,9 @@ fn sidecar_ipc_path_for( let root = std::ffi::CStr::from_bytes_until_nul(&buffer) .map_err(|_| anyhow::anyhow!("macOS per-user temporary directory is not NUL-terminated"))?; - #[cfg(feature = "verge-dev")] + #[cfg(debug_assertions)] let filename = "verge-mihomo-dev.sock"; - #[cfg(not(feature = "verge-dev"))] + #[cfg(not(debug_assertions))] let filename = "verge-mihomo.sock"; let path = PathBuf::from(OsStr::from_bytes(root.to_bytes())).join(filename); @@ -238,7 +238,7 @@ fn sidecar_ipc_path_for( #[cfg(windows)] fn sidecar_ipc_path_for(_app_root: &std::path::Path, identity: &clash_verge_service_ipc::OwnerIdentity) -> PathBuf { - PathBuf::from(sidecar_pipe_name(identity, cfg!(feature = "verge-dev"))) + PathBuf::from(sidecar_pipe_name(identity, cfg!(debug_assertions))) } #[cfg(any(windows, test))] @@ -285,9 +285,9 @@ mod ipc_tests { assert!(!path.starts_with(app_root)); assert!(path.as_os_str().as_bytes().len() < 104); - #[cfg(feature = "verge-dev")] + #[cfg(debug_assertions)] assert_eq!(path.file_name(), Some(OsStr::new("verge-mihomo-dev.sock"))); - #[cfg(not(feature = "verge-dev"))] + #[cfg(not(debug_assertions))] assert_eq!(path.file_name(), Some(OsStr::new("verge-mihomo.sock"))); assert_eq!(path, sidecar_ipc_path_for(Path::new("/different/root"), &identity)?); assert!(path.parent().is_some_and(Path::is_dir)); @@ -312,7 +312,7 @@ mod ipc_tests { path, Path::new(&format!( r"\\.\pipe\verge-mihomo-sidecar-{}-{}", - if cfg!(feature = "verge-dev") { "dev" } else { "release" }, + if cfg!(debug_assertions) { "dev" } else { "release" }, clash_verge_service_ipc::owner_key(&identity) )) ); diff --git a/src-tauri/src/utils/server.rs b/src-tauri/src/utils/server.rs index 42d097a86..bb3577947 100644 --- a/src-tauri/src/utils/server.rs +++ b/src-tauri/src/utils/server.rs @@ -166,9 +166,6 @@ fn start_embedded_server(listener: tokio::net::TcpListener, token: String) { let (shutdown_tx, shutdown_rx) = oneshot::channel(); let _ = SHUTDOWN_SENDER.set(Mutex::new(Some(shutdown_tx))); - #[cfg(feature = "verge-dev")] - let auth = instance_auth(token); - #[cfg(not(feature = "verge-dev"))] let auth = instance_auth(token); let visible = warp::path!("commands" / "visible").and_then(|| async { diff --git a/src/components/layout/traffic-graph.tsx b/src/components/layout/traffic-graph.tsx index f6893003b..89b23f2f2 100644 --- a/src/components/layout/traffic-graph.tsx +++ b/src/components/layout/traffic-graph.tsx @@ -13,7 +13,8 @@ const upLineWidth = 4 const downLineAlpha = 1 const downLineWidth = 4 const sampleIntervalMs = 1000 -const animationDurationMs = sampleIntervalMs +const animationDurationMs = 150 +const scrollTransform = `translateX(${-100 / (maxPoint + 1)}%)` const zeroTraffic: Traffic = { up: 0, down: 0, upTotal: 0, downTotal: 0 } const createDefaultList = () => @@ -203,12 +204,8 @@ export function TrafficGraph({ ref }: { ref?: Ref }) { performance.now() - animationStartRef.current, animationDurationMs, ) - const step = canvas.getBoundingClientRect().width / (maxPoint + 1) animation = canvas.animate( - [ - { transform: 'translateX(0)' }, - { transform: `translateX(${-step}px)` }, - ], + [{ transform: 'translateX(0)' }, { transform: scrollTransform }], { duration: animationDurationMs, easing: 'linear', fill: 'forwards' }, ) animation.currentTime = elapsed