Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 退出挂死三层修复——外部硬杀 watchdog + post-async 预算 + 退出期不误启 browser 服务 (#712)
Dash404fcb71cd4b
diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.tsindex bcbb3d42ee..04413738a4 100644--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts@@ -29,6 +29,14 @@ const mocks = vi.hoisted(() => ({error: vi.fn(),},disableDevTerminalMirror: vi.fn(),+ // 默认 spawn stub —— beginShutdown 会布防真实 watchdog, 不 mock 的话+ // render-process-gone 等用例会真的 spawn `sleep 20; kill -9 <vitest pid>`,+ // 慢跑/watch 模式下会把测试进程杀掉。+ spawn: vi.fn(() => ({ unref: vi.fn() })),+}));++vi.mock('node:child_process', () => ({+ spawn: mocks.spawn,}));vi.mock('../logger', async () => {@@ -145,6 +153,26 @@ describe('runQuitDisposers', () => {expect(elapsed).toBeLessThan(200);});+ it('post-async disposer that never resolves is bounded by timeout — later post-async still runs', async () => {+ const { onQuit, runQuitDisposers } = await freshLifecycle();+ let laterRan = false;++ // 永不 resolve 的 post-async disposer (生产事故形态: 无界 await 卡死退出)+ onQuit('hang-post', () => new Promise(() => { /* never */ }), 'post-async');+ onQuit('later-post', () => { laterRan = true; }, 'post-async');++ const start = Date.now();+ await runQuitDisposers(50);+ const elapsed = Date.now() - start;++ expect(laterRan).toBe(true);+ // 单个 post-async 预算 50ms, 实际不应远超 (无其它阻塞)+ expect(elapsed).toBeLessThan(500);+ expect(mocks.logger.warn).toHaveBeenCalledWith(+ expect.stringContaining('post-async disposer "hang-post" timed out after 50ms'),+ );+ });+it('rejected async disposer does not break the chain', async () => {const { onQuit, runQuitDisposers } = await freshLifecycle();let postRan = false;@@ -159,6 +187,208 @@ describe('runQuitDisposers', () => {});});+describe('armShutdownHardKillWatchdog', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ function fakeSpawn() {+ const child = { once: vi.fn(), unref: vi.fn() };+ const spawn = vi.fn(() => child);+ return { spawn, child };+ }++ it('POSIX (darwin): /bin/sh 捕获 lstart → sleep → lstart+command 双校验后 kill -9 — detached + ignore + unref', async () => {+ const { armShutdownHardKillWatchdog, SHUTDOWN_HARD_KILL_GRACE_SECONDS } =+ await freshLifecycle();+ const { spawn, child } = fakeSpawn();++ armShutdownHardKillWatchdog({+ spawn,+ pid: 12345,+ platform: 'darwin',+ execPath: '/Apps/Cindy Test/Electron',+ });++ expect(spawn).toHaveBeenCalledTimes(1);+ const [cmd, args, opts] = spawn.mock.calls[0] as unknown as [+ string,+ string[],+ Record<string, unknown>,+ ];+ expect(cmd).toBe('/bin/sh');+ // 杀前身份校验(review P1 两轮):命令行匹配区分不了同一 App 的两次运行+ // (更新器重启的新实例复用 PID 会被误杀), 所以布防时先捕获进程创建时间+ // (lstart), 补刀前重取比对;不一致 = PID 已易主, 放弃。execPath grep 保留+ // 作第二道校验。+ expect(args).toEqual([+ '-c',+ 'started="$(ps -p 12345 -o lstart= 2>/dev/null)"; '+ + '[ -n "$started" ] || exit 0; '+ + `sleep ${SHUTDOWN_HARD_KILL_GRACE_SECONDS}; `+ + '[ "$(ps -p 12345 -o lstart= 2>/dev/null)" = "$started" ] && '+ + "ps -p 12345 -o command= 2>/dev/null | grep -qF '/Apps/Cindy Test/Electron' && "+ + 'kill -9 12345 2>/dev/null',+ ]);+ expect(opts).toEqual({ detached: true, stdio: 'ignore' });+ expect(child.unref).toHaveBeenCalledTimes(1);+ expect(mocks.logger.info).toHaveBeenCalledWith(+ expect.stringContaining(`grace=${SHUTDOWN_HARD_KILL_GRACE_SECONDS}s`),+ );+ });++ it('win32: PowerShell 捕获 StartTime → Start-Sleep → StartTime+Path 双校验后 Stop-Process — windowsHide + unref', async () => {+ const { armShutdownHardKillWatchdog, SHUTDOWN_HARD_KILL_GRACE_SECONDS } =+ await freshLifecycle();+ const { spawn, child } = fakeSpawn();++ armShutdownHardKillWatchdog({+ spawn,+ pid: 67890,+ platform: 'win32',+ execPath: 'C:\\Cindy\\Cindy.exe',+ });++ expect(spawn).toHaveBeenCalledTimes(1);+ const [cmd, args, opts] = spawn.mock.calls[0] as unknown as [+ string,+ string[],+ Record<string, unknown>,+ ];+ // cmd/tasklist 只能比映像名, 区分不了两次运行;换 Windows PowerShell 5.1+ // (SystemRoot 绝对路径, 不依赖 PATH) 以进程创建时间为身份锚点。+ expect(cmd).toBe(+ `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,+ );+ expect(args.slice(0, 5)).toEqual([+ '-NoProfile',+ '-NonInteractive',+ '-WindowStyle',+ 'Hidden',+ '-Command',+ ]);+ const script = args[5];+ // 布防时捕获创建时间;取不到 (进程已死) 则直接退出, 失败方向永远是"少杀"。+ expect(script).toContain(+ '$started = Get-Process -Id 67890 | Select-Object -ExpandProperty StartTime; if (-not $started) { exit }; ',+ );+ expect(script).toContain(`Start-Sleep -Seconds ${SHUTDOWN_HARD_KILL_GRACE_SECONDS}; `);+ // 补刀前 StartTime + Path 双校验;属性读取走 Select-Object -ExpandProperty+ // 兼容 Constrained Language Mode。+ expect(script).toContain(+ '$p = Get-Process -Id 67890; '+ + 'if ($p -and ($p | Select-Object -ExpandProperty StartTime) -eq $started '+ + "-and ($p | Select-Object -ExpandProperty Path) -eq 'C:\\Cindy\\Cindy.exe') "+ + '{ Stop-Process -Id 67890 -Force }',+ );+ expect(opts).toEqual({ detached: true, windowsHide: true, stdio: 'ignore' });+ expect(child.unref).toHaveBeenCalledTimes(1);+ });++ it('is idempotent — a second arm does not spawn again', async () => {+ const { armShutdownHardKillWatchdog } = await freshLifecycle();+ const { spawn } = fakeSpawn();++ armShutdownHardKillWatchdog({ spawn, pid: 1, platform: 'darwin' });+ armShutdownHardKillWatchdog({ spawn, pid: 1, platform: 'darwin' });++ expect(spawn).toHaveBeenCalledTimes(1);+ });++ it('async spawn "error" event is warn-logged, not an uncaughtException (review P1)', async () => {+ // spawn 可能在返回后经 'error' 事件异步报失败 (ENOENT/EACCES); 必须挂+ // listener 留痕, 否则 watchdog 静默未布防且错误落入 uncaughtException。+ const { armShutdownHardKillWatchdog } = await freshLifecycle();+ const { spawn, child } = fakeSpawn();++ armShutdownHardKillWatchdog({ spawn, pid: 1, platform: 'darwin' });++ expect(child.once).toHaveBeenCalledWith('error', expect.any(Function));+ const errorListener = child.once.mock.calls[0][1] as (err: Error) => void;+ expect(() => errorListener(new Error('ENOENT'))).not.toThrow();+ expect(mocks.logger.warn).toHaveBeenCalledWith(+ expect.stringContaining('watchdog process failed to start'),+ expect.any(Error),+ );+ });++ it('tolerates fake spawn children without once() (listener attach is optional)', async () => {+ const { armShutdownHardKillWatchdog } = await freshLifecycle();+ const child = { unref: vi.fn() };+ const spawn = vi.fn(() => child);++ expect(() =>+ armShutdownHardKillWatchdog({ spawn, pid: 1, platform: 'darwin' }),+ ).not.toThrow();+ expect(child.unref).toHaveBeenCalledTimes(1);+ });++ it('spawn throwing does not propagate (watchdog failure must not block shutdown)', async () => {+ const { armShutdownHardKillWatchdog } = await freshLifecycle();+ const spawn = vi.fn(() => {+ throw new Error('spawn-boom');+ });++ expect(() =>+ armShutdownHardKillWatchdog({ spawn, pid: 1, platform: 'darwin' }),+ ).not.toThrow();+ expect(mocks.logger.warn).toHaveBeenCalledWith(+ expect.stringContaining('watchdog process failed to start'),+ expect.any(Error),+ );+ });++ it('async spawn "error" retries within the 3-attempt budget, then marks the backstop ABSENT (review ×2)', async () => {+ // 异步启动失败(ENOENT/EACCES)时 watchdog 实际不在位:预算内立即重试+ // (吸收 EAGAIN 类瞬时抖动);全部失败 = 环境级问题,进程内不可能布防任何+ // 外部补刀——打明确的缺席标记(error 级)供退出尸检定位,不再无限重试。+ const { armShutdownHardKillWatchdog } = await freshLifecycle();+ const children: Array<{ once: ReturnType<typeof vi.fn>; unref: ReturnType<typeof vi.fn> }> = [];+ const spawn = vi.fn(() => {+ const child = { once: vi.fn(), unref: vi.fn() };+ children.push(child);+ return child;+ });++ armShutdownHardKillWatchdog({ spawn, pid: 1, platform: 'darwin' });+ expect(spawn).toHaveBeenCalledTimes(1);+ // 第 1、2 个 child 异步报错 → 各自立即重试+ (children[0].once.mock.calls[0][1] as (err: Error) => void)(new Error('EACCES'));+ expect(spawn).toHaveBeenCalledTimes(2);+ (children[1].once.mock.calls[0][1] as (err: Error) => void)(new Error('EACCES'));+ expect(spawn).toHaveBeenCalledTimes(3);+ // 第 3 个也报错:预算耗尽 → 缺席标记,不再重试+ (children[2].once.mock.calls[0][1] as (err: Error) => void)(new Error('EACCES'));+ expect(spawn).toHaveBeenCalledTimes(3);+ expect(mocks.logger.error).toHaveBeenCalledWith(+ expect.stringContaining('external kill backstop ABSENT'),+ expect.any(Error),+ );+ // 预算耗尽后再布防:no-op(环境已证实无法 spawn)+ armShutdownHardKillWatchdog({ spawn, pid: 1, platform: 'darwin' });+ expect(spawn).toHaveBeenCalledTimes(3);+ });++ it('sync spawn failure consumes the shared budget and marks ABSENT on exhaustion (review)', async () => {+ // 同步 throw 与异步 error 共享 3 次预算:同一环境级失败在一次布防里就地+ // 重试到耗尽并打缺席标记;之后其它入口的布防调用 no-op,不再空转。+ const { armShutdownHardKillWatchdog } = await freshLifecycle();+ const failingSpawn = vi.fn(() => {+ throw new Error('spawn-boom');+ });+ armShutdownHardKillWatchdog({ spawn: failingSpawn, pid: 1, platform: 'darwin' });+ expect(failingSpawn).toHaveBeenCalledTimes(3);+ expect(mocks.logger.error).toHaveBeenCalledWith(+ expect.stringContaining('external kill backstop ABSENT'),+ expect.any(Error),+ );++ const { spawn } = fakeSpawn();+ armShutdownHardKillWatchdog({ spawn, pid: 1, platform: 'darwin' });+ expect(spawn).not.toHaveBeenCalled();+ });+});+describe('installQuitHandler render-process-gone', () => {beforeEach(() => {vi.clearAllMocks();@@ -226,6 +456,8 @@ describe('installQuitHandler render-process-gone', () => {await vi.waitFor(() => {expect(app.exit).toHaveBeenCalledWith(1);});+ // beginShutdown 应布防外部硬杀 watchdog (走默认 spawn, 被顶部 mock 接住)+ expect(mocks.spawn).toHaveBeenCalledTimes(1);} finally {restore();}diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.tsindex d82d18a9cb..6f5a9aa522 100644--- a/apps/desktop/src/main/lifecycle.ts+++ b/apps/desktop/src/main/lifecycle.ts@@ -18,6 +18,10 @@* 然后 `app.exit(<code>)` 强制退出。`will-quit` / `quit` 事件不会触发——任何* 真正必须执行的清理都必须注册到这里, 而不是挂 `will-quit`。*+ * shutdown 开始时同步布防外部硬杀 watchdog (armShutdownHardKillWatchdog):+ * disposer 挂死、事件循环被 sync 代码阻塞、甚至 app.exit 在 native teardown+ * 挂死 (JS 已死) 时, 由 detached 外部进程在宽限期后 kill -9 补刀, 保证退出有界。+ ** installQuitHandler() 同时把以下入口都收到这条 disposer chain:** - app.on('before-quit') —— 用户/代码主动退出 (Cmd+Q / 关窗 / app.quit)@@ -29,6 +33,8 @@* 真硬崩 (segfault / kill -9) JS 层无能为力, 这里覆盖不到; 子进程靠 stdin EOF 自死。*/+import { spawn } from 'node:child_process';+import { app, BrowserWindow, session } from 'electron';import {@@ -141,13 +147,31 @@ export async function runQuitDisposers(timeoutMs = 2000): Promise<void> {}// ── Phase 3: post-async ──────────────────────────────────────────────────+ // 返回 Promise 的 disposer 同样纳入 timeoutMs 预算 (逐个 race, 串行语义不变)。+ // 此前这里是无界 await —— 生产实证: 单个挂死的 post-async disposer 就能让+ // "runQuitDisposers completed" 永远打不出来, 进程卡在退出路径上不死。for (const d of registry.filter((x) => x.phase === 'post-async')) {try {const ret = d.fn();if (ret && typeof (ret as Promise<unknown>).then === 'function') {- await (ret as Promise<unknown>).catch((err) =>+ const settled = (ret as Promise<unknown>).catch((err) =>log.error(`post-async disposer "${d.name}" threw`, err),);+ let timer: NodeJS.Timeout | undefined;+ let timedOut = false;+ await Promise.race([+ settled,+ new Promise<void>((resolve) => {+ timer = setTimeout(() => {+ timedOut = true;+ resolve();+ }, timeoutMs);+ }),+ ]);+ clearTimeout(timer);+ if (timedOut) {+ log.warn(`post-async disposer "${d.name}" timed out after ${timeoutMs}ms — continuing`);+ }}} catch (err) {log.error(`post-async disposer "${d.name}" threw`, err);@@ -155,6 +179,152 @@ export async function runQuitDisposers(timeoutMs = 2000): Promise<void> {}}+/**+ * 外部硬杀 watchdog 的宽限期 (秒)。disposer 预算 6s 的 3 倍余量; 比更新脚本的+ * 120s (updateScriptMacOS) 激进得多 —— 这是常规退出路径, 用户在旁边等。+ */+export const SHUTDOWN_HARD_KILL_GRACE_SECONDS = 20;++/** 最小 spawn 形状 —— 单测注入 fake 用, 真实实现是 node:child_process 的 spawn。 */+type WatchdogSpawn = (+ command: string,+ args: string[],+ options: { detached: boolean; stdio: 'ignore'; windowsHide?: boolean },+) => {+ unref(): void;+ /** ChildProcess 的 'error' 事件订阅; fake 可省略 (可选调用)。 */+ once?(event: 'error', listener: (err: Error) => void): unknown;+};++let _watchdogArmed = false;+/**+ * watchdog spawn 总尝试预算(同步/异步失败共享计数,防 error→重试死循环):+ * 3 次足以吸收 EAGAIN(fork 上限)这类瞬时抖动;仍然全失败 = 环境级问题+ * (ENOENT/EACCES),本进程从内部**不可能**布防任何外部补刀,重试再多也无意义+ * (review:此为可接受的终态)。耗尽时打一条明确的缺席标记(error 级),让+ * 退出尸检一眼看出"这次 shutdown 没有外部兜底"。+ */+const WATCHDOG_MAX_SPAWN_ATTEMPTS = 3;+let _watchdogSpawnAttempts = 0;++function noteWatchdogSpawnFailure(err: unknown, options: Parameters<typeof armShutdownHardKillWatchdog>[0]): void {+ _watchdogArmed = false;+ if (_watchdogSpawnAttempts < WATCHDOG_MAX_SPAWN_ATTEMPTS) {+ log.warn('shutdown hard-kill watchdog process failed to start (retrying)', err);+ armShutdownHardKillWatchdog(options);+ return;+ }+ log.error(+ `shutdown hard-kill watchdog UNAVAILABLE after ${_watchdogSpawnAttempts} spawn attempts — ` ++ 'external kill backstop ABSENT for this shutdown (continuing without it)',+ err,+ );+}++/**+ * 布防外部硬杀 watchdog: spawn 一个 detached 的外部杀手进程, 宽限期后对本进程+ * PID 补 kill。这是唯一能同时覆盖三类退出挂死的手段:+ * - sync disposer 阻塞事件循环 (JS 层 setTimeout 根本不会触发)+ * - post-async 无界 await (Phase 3 已加预算, 这里是第二道保险)+ * - app.exit() 在 native teardown 挂死 —— 实证见 updateScriptMacOS.ts:+ * 2026-07-06 观测到 exit 已打日志但 PID 存活 32h, 彼时 JS 事件循环已死,+ * 进程无法自救, 只有外部进程能补刀。+ *+ * 正常退出时本进程早已死透, 补刀落空无害 (kill 静默失败)。PID 复用防护 (review+ * P1 两轮): 映像名/命令行校验区分不了同一 App 的两次运行 (正常退出后更新器立即+ * 重启、新实例在宽限期内拿到复用 PID 会被误杀), 所以 watchdog 在布防时刻 (本进程+ * 必然存活) 先捕获目标 PID 的**进程创建时间**, 补刀前重取一次, 不一致 = PID 已易主,+ * 放弃。残余窗口只剩 "本进程在 watchdog 子进程完成首次捕获前 (毫秒级) 就退出且+ * PID 立即复用给另一个同路径进程", 视为可接受。+ *+ * 幂等: 进程生命周期内只布防一次。spawn/pid/platform 可注入, 便于单测;+ * 布防失败只 warn, 绝不阻断正常退出。+ */+export function armShutdownHardKillWatchdog(+ options: {+ spawn?: WatchdogSpawn;+ pid?: number;+ platform?: NodeJS.Platform;+ graceSeconds?: number;+ /** 进程身份锚点 (杀前校验用), 默认 process.execPath;测试注入。 */+ execPath?: string;+ } = {},+): void {+ if (_watchdogArmed) return;+ if (_watchdogSpawnAttempts >= WATCHDOG_MAX_SPAWN_ATTEMPTS) return; // 预算耗尽,缺席标记已打+ _watchdogArmed = true;+ _watchdogSpawnAttempts += 1;+ const spawnFn = options.spawn ?? spawn;+ const pid = options.pid ?? process.pid;+ const platform = options.platform ?? process.platform;+ const graceSeconds = options.graceSeconds ?? SHUTDOWN_HARD_KILL_GRACE_SECONDS;+ const execPath = options.execPath ?? process.execPath;+ try {+ // 杀前校验进程身份 (review P1 两轮): 宽限期内 OS 复用了该 PID 时, 盲杀会误伤。+ // 映像名/命令行校验区分不了同一 App 的两次运行 (更新器重启的新实例), 所以以+ // **进程创建时间**为身份锚点: 布防时刻本进程必然存活, watchdog 子进程先捕获+ // 目标 PID 的创建时间, 补刀前重取比对, 不一致 = PID 已易主, 放弃补刀。+ const child =+ platform === 'win32'+ ? (() => {+ // cmd 拿不到进程创建时间 (wmic 已从新版 Windows 移除), 改用 Windows+ // PowerShell 5.1 —— 所有受支持 Windows 内置, 用 SystemRoot 绝对路径,+ // 不假设它在 PATH。属性读取走 Select-Object -ExpandProperty 而非语言级+ // .StartTime, 兼容企业锁死环境的 Constrained Language Mode (其下语言级+ // 属性访问被禁, cmdlet 内部反射不受限);取不到创建时间时直接退出不杀,+ // 失败方向是"少杀"而非"误杀"。字符串 -eq 大小写不敏感, 路径比对安全。+ const psExe =+ `${process.env.SystemRoot ?? 'C:\\Windows'}` ++ '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';+ const script =+ `$ErrorActionPreference='SilentlyContinue'; ` ++ `$started = Get-Process -Id ${pid} | Select-Object -ExpandProperty StartTime; ` ++ `if (-not $started) { exit }; ` ++ `Start-Sleep -Seconds ${graceSeconds}; ` ++ `$p = Get-Process -Id ${pid}; ` ++ `if ($p -and ($p | Select-Object -ExpandProperty StartTime) -eq $started ` ++ `-and ($p | Select-Object -ExpandProperty Path) -eq '${execPath.replace(/'/g, "''")}') ` ++ `{ Stop-Process -Id ${pid} -Force }`;+ return spawnFn(+ psExe,+ ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', script],+ { detached: true, windowsHide: true, stdio: 'ignore' },+ );+ })()+ : spawnFn(+ '/bin/sh',+ [+ '-c',+ // lstart 是完整启动时间字符串 (秒级), 同 PID + 同启动秒 + 同 execPath+ // 的碰撞视为不可能。捕获时进程已死则直接退出 (不需要补刀)。+ `started="$(ps -p ${pid} -o lstart= 2>/dev/null)"; ` ++ `[ -n "$started" ] || exit 0; ` ++ `sleep ${graceSeconds}; ` ++ `[ "$(ps -p ${pid} -o lstart= 2>/dev/null)" = "$started" ] && ` ++ `ps -p ${pid} -o command= 2>/dev/null | grep -qF '${execPath.replace(/'/g, `'\\''`)}' && ` ++ `kill -9 ${pid} 2>/dev/null`,+ ],+ { detached: true, stdio: 'ignore' },+ );+ // spawn 的失败可能在返回后经 'error' 事件异步上报 (ENOENT/EACCES 等);+ // 不挂 listener 会变成 uncaughtException, 且 watchdog 实际未布防却无任何+ // 日志痕迹 —— 这里 warn 留痕, 让退出尸检能看出"补刀兜底当时不在位"。+ child.once?.('error', (err) => {+ // 异步启动失败 = 实际未布防(review P1 两轮):回置标志,预算内立即重试,+ // 耗尽则打缺席标记(见 noteWatchdogSpawnFailure)。+ noteWatchdogSpawnFailure(err, options);+ });+ child.unref();+ // log 放在 spawn 之后 (review P1): 统一 logger 同步写日志文件, 坏盘/网络盘+ // 上可能阻塞 —— watchdog 必须在任何可能卡住的盘 IO 之前先布防好。+ log.info(`arming shutdown hard-kill watchdog: pid=${pid} grace=${graceSeconds}s`);+ } catch (err) {+ // 同步 spawn 失败 = 实际未布防:与异步 error 共享尝试预算,预算内重试,+ // 耗尽打缺席标记(日志由 noteWatchdogSpawnFailure 统一输出)。+ noteWatchdogSpawnFailure(err, options);+ }+}+let _installed = false;let _isDisposing = false;let _disposeStarted: Promise<void> | null = null;@@ -170,6 +340,11 @@ let _disposeStarted: Promise<void> | null = null;function beginShutdown(timeoutMs: number, reason: string): Promise<void> {if (_disposeStarted) return _disposeStarted;_isDisposing = true;+ // watchdog 必须是 shutdown 的第一个动作 (review P1): log 与 noteShutdownBegin+ // 都是同步盘 IO (日志文件 / run-marker 的 mkdirSync+writeFileSync), 落在坏盘+ // 或网络盘上可能无限阻塞 —— 那正是 watchdog 要兜的挂死形态, 不能让布防+ // 排在它们后面。spawn 本身不做盘写。+ armShutdownHardKillWatchdog();log.info(`beginShutdown timeoutMs=${timeoutMs} reason=${reason}`);noteShutdownBegin(reason);_disposeStarted = runQuitDisposers(timeoutMs)@@ -211,6 +386,10 @@ export function installQuitHandler(timeoutMs = 2000): void {// ── Layer 1: graceful quit (before-quit) ────────────────────────────────// preventDefault 阻断默认 quit, 等 disposer chain 跑完再 app.exit(0)。app.on('before-quit', (e) => {+ // arm-first(review P1):本 handler 必然走向退出,而下面第一行 log 就是+ // 同步盘 IO——日志落在坏盘/网络盘上时会在布防前就挂死,watchdog 形同虚设。+ // 幂等,与 beginShutdown 里的布防互为兜底。+ armShutdownHardKillWatchdog();log.info('before-quit received');if (_isDisposing) return;e.preventDefault();@@ -226,6 +405,8 @@ export function installQuitHandler(timeoutMs = 2000): void {if (process.platform === 'win32') shutdownSignals.push('SIGBREAK');for (const sig of shutdownSignals) {process.on(sig, () => {+ // arm-first(review P1):同 before-quit,先布防再碰日志盘 IO。+ armShutdownHardKillWatchdog();log.info(`received ${sig}, gracefully shutting down`);if (_isDisposing) return;if (app.isReady()) {@@ -266,6 +447,9 @@ export function installQuitHandler(timeoutMs = 2000): void {broadcastTransientNetworkErrorTip(err);return;}+ // arm-first(review P1):只在确定退出的分支布防——上面 broken-stdio /+ // 瞬时网络两个不退出的分支绝不能布防,否则 20s 后 watchdog 会误杀健康进程。+ armShutdownHardKillWatchdog();log.error('uncaughtException — shutting down', err);if (_isDisposing) return;void beginShutdown(timeoutMs, 'uncaughtException').finally(() => app.exit(1));@@ -300,6 +484,9 @@ export function installQuitHandler(timeoutMs = 2000): void {);return;}+ // arm-first(review P1):沙箱/webview 两个不退出的分支在上面已 return,+ // 走到这里必然退出。+ armShutdownHardKillWatchdog();log.error(`render-process-gone: reason=${details.reason} exitCode=${details.exitCode}`);if (_isDisposing) return;void beginShutdown(timeoutMs, `render-process-gone:${details.reason}`).finally(() =>diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/browser-dispose.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/browser-dispose.test.tsindex 22dea512b3..233d8fae71 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/browser-dispose.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/browser-dispose.test.ts@@ -1,10 +1,14 @@import { describe, expect, it, vi } from 'vitest';-import { stopRuntimeForQuit } from '../browser-dispose.js';+import {+ stopRuntimeForQuit,+ stopRuntimeForQuitIfUsed,+ trackBrowserRuntimeUsage,+} from '../browser-dispose.js';import type { BrowserControlRequest, BrowserControlResult } from '@cindy/browser-control-runtime';function fakeLogger() {- return { warn: vi.fn() };+ return { info: vi.fn(), warn: vi.fn() };}describe('stopRuntimeForQuit', () => {@@ -48,3 +52,343 @@ describe('stopRuntimeForQuit', () => {expect(logger.warn).toHaveBeenCalledTimes(1);});});++describe('stopRuntimeForQuitIfUsed', () => {+ it('skips the stop dispatch entirely when the runtime was never used', async () => {+ // The vendored dispatch bridge boots the browser control service before+ // routing ANY action — so "never used" must mean zero calls, not a no-op stop.+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(async () => ({+ ok: true,+ action: 'stop',+ status: 200,+ }));+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call).not.toHaveBeenCalled();+ expect(logger.info).toHaveBeenCalledWith(+ expect.stringContaining('never used this session'),+ );+ expect(logger.warn).not.toHaveBeenCalled();+ });++ it('stops normally when the runtime saw traffic this session', async () => {+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ async (req) => ({ ok: true, action: req.action, status: 200 }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await tracked.call({ action: 'status' });+ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call).toHaveBeenCalledTimes(2);+ expect(call.mock.calls[1][0]).toEqual({ action: 'stop' });+ expect(logger.warn).not.toHaveBeenCalled();+ });++ it('does not count a rejected call as usage — service liveness unproven', async () => {+ // Review P1: marking at dispatch time would treat a failed-boot call as+ // "service is up", and the quit-time stop would then re-run the boot.+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(async () => {+ throw new Error('dispatch exploded');+ });+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await expect(tracked.call({ action: 'status' })).rejects.toThrow('dispatch exploded');+ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call).toHaveBeenCalledTimes(1);+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('never used this session'));+ });++ it('counts an ok:false WITH http status as usage — the service answered, it is up (review)', async () => {+ // HTTP >=400 走的是 dispatcher 真实应答:服务已启动,只是 action 失败;+ // 跳过 stop 会把已启动的服务/Chrome 留成孤儿(锁住 profile)。+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ async (req) => ({ ok: false, action: req.action, status: 500 }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await tracked.call({ action: 'status' });+ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call).toHaveBeenCalledTimes(2);+ expect(call.mock.calls[1][0]).toEqual({ action: 'stop' });+ });++ it('does not count an ok:false WITHOUT status as usage — thrown boots have no http reply', async () => {+ // catch 路径(启动 throw / disabled)不带 status:服务存活未证实,不计使用。+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ async (req) => ({ ok: false, action: req.action, errorCode: 'BROWSER_RUNTIME_UNAVAILABLE', message: 'disabled' }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await tracked.call({ action: 'status' });+ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call).toHaveBeenCalledTimes(1);+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('never used this session'));+ });++ it('beginQuiescence blocks NEW non-stop calls with a RESOLVED ok:false result (review ×2)', async () => {+ // 底层 runtime 的契约是 call 永不 reject(总是 resolve BrowserControlResult,+ // 调用方只看 res.ok)——门禁必须 resolve ok:false 而不是 reject,否则会在+ // 只检查 res.ok 的调用方处变成 unhandledRejection。+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ async (req) => ({ ok: true, action: req.action, status: 200 }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });++ tracked.beginQuiescence();++ const res = await tracked.call({ action: 'status' });+ expect(res.ok).toBe(false);+ expect(res.errorCode).toBe('BROWSER_RUNTIME_UNAVAILABLE');+ // 无 status → 不计使用+ expect(tracked.everCalled()).toBe(false);+ expect(call).not.toHaveBeenCalled();+ // stop 仍放行(quit 路径自己要发 stop)+ await tracked.call({ action: 'stop' });+ expect(call).toHaveBeenCalledTimes(1);+ });++ it('does not count a stop dispatch as usage — teardown is not traffic', async () => {+ // Review P1: ExternalChromeBackend.dispose (backend switching) sends a+ // stop through the same wrapper; counting it would make the quit path+ // dispatch a second stop that re-boots the service.+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ async (req) => ({ ok: true, action: req.action, status: 200 }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await tracked.call({ action: 'stop' });+ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call).toHaveBeenCalledTimes(1);+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('never used this session'));+ });++ it('a successful stop RESETS usage — use → backend-switch stop → quit skips (review P1)', async () => {+ // 使用后切换后端(ExternalChromeBackend.dispose)已成功停掉服务;若使用态+ // 终身保留,退出时会再派一次 stop,vendored bridge 会先把已停的服务重新+ // 拉起——这正是本包装要避免的退出期启动。stopped:true = 真正 tear down。+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ async (req) => ({ ok: true, action: req.action, status: 200, data: req.action === 'stop' ? { stopped: true } : undefined }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await tracked.call({ action: 'status' });+ expect(tracked.everCalled()).toBe(true);+ await tracked.call({ action: 'stop' });+ expect(tracked.everCalled()).toBe(false);+ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call).toHaveBeenCalledTimes(2); // status + 后端切换的 stop,quit 未再派+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('never used this session'));+ });++ it('a failed stop does NOT reset usage — service may still be up, quit stop stays', async () => {+ let stopCount = 0;+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ async (req) => {+ if (req.action !== 'stop') return { ok: true, action: req.action, status: 200 };+ stopCount += 1;+ return stopCount === 1+ ? { ok: false, action: req.action, status: 500, errorCode: 'BROWSER_RUNTIME_ACTION_FAILED', message: 'busy' }+ : { ok: true, action: req.action, status: 200 };+ },+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await tracked.call({ action: 'status' });+ await tracked.call({ action: 'stop' }); // 失败的 stop:服务可能还活着+ expect(tracked.everCalled()).toBe(true);+ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call.mock.calls.map(([req]) => req.action)).toEqual(['status', 'stop', 'stop']);+ });++ it('a pre-stop call settling AFTER a successful stop does not re-mark usage (review ×2)', async () => {+ // BackendRouter.setBackend 处理旧后端 dispose 时不等其在途调用排空:在途+ // 调用可能在 stop 成功重置之后才 settle——它应答的是已被拆掉的服务实例,+ // 若翻回使用态,退出路径会再派 stop 把服务重新拉起。epoch 必须拦住它。+ let resolveSlow!: (r: BrowserControlResult) => void;+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>((req) =>+ req.action === 'stop'+ ? Promise.resolve({ ok: true, action: req.action, status: 200, data: { stopped: true } })+ : new Promise((resolve) => {+ resolveSlow = resolve;+ }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ const slow = tracked.call({ action: 'snapshot' }); // stop 前已在途+ await tracked.call({ action: 'stop' }); // 后端切换的成功 stop+ resolveSlow({ ok: true, action: 'snapshot', status: 200 }); // 晚到的旧应答+ await slow;+ expect(tracked.everCalled()).toBe(false);++ await stopRuntimeForQuitIfUsed(tracked, logger);+ expect(call.mock.calls.map(([req]) => req.action)).toEqual(['snapshot', 'stop']); // quit 未再派+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('never used this session'));+ });++ it('quit waits for an in-flight backend-switch stop, then skips its own stop (review)', async () => {+ // stop 若不进 inFlight,settleInFlight 之后它才落定重置使用态,quit 已经+ // 多派了一次 stop——vendored bridge 会为路由这次 stop 把刚停掉的服务再拉起。+ let resolveStop!: (r: BrowserControlResult) => void;+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>((req) =>+ req.action === 'stop'+ ? new Promise((resolve) => {+ resolveStop = resolve;+ })+ : Promise.resolve({ ok: true, action: req.action, status: 200 }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await tracked.call({ action: 'status' }); // usage = true+ const switchStop = tracked.call({ action: 'stop' }); // 后端切换的 stop,在途+ const quit = stopRuntimeForQuitIfUsed(tracked, logger);+ resolveStop({ ok: true, action: 'stop', status: 200, data: { stopped: true } });+ await switchStop;+ await quit;++ expect(call.mock.calls.map(([req]) => req.action)).toEqual(['status', 'stop']); // quit 未再派+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('never used this session'));+ });++ it('a call admitted AFTER a pending stop re-marks usage once it answers (review P1)', async () => {+ // 后端切换的 stop 在途期间,一条 start(比 stop 晚派发)赢得竞态并拉起了+ // 新 Chrome:它的应答必须重新计入使用,否则 quit 会跳过清理、泄漏进程与+ // profile 锁(epoch-per-stop 方案会误伤这类新调用,seq 屏障不会)。+ let resolveStop!: (r: BrowserControlResult) => void;+ let resolveStart!: (r: BrowserControlResult) => void;+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>((req) => {+ if (req.action === 'stop' && !resolveStop) {+ return new Promise((resolve) => {+ resolveStop = resolve;+ });+ }+ if (req.action === 'start') {+ return new Promise((resolve) => {+ resolveStart = resolve;+ });+ }+ return Promise.resolve({ ok: true, action: req.action, status: 200 });+ });+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ const pendingStop = tracked.call({ action: 'stop' }); // 先派发的 stop+ const lateStart = tracked.call({ action: 'start' }); // stop 之后新进的 start+ resolveStop({ ok: true, action: 'stop', status: 200, data: { stopped: true } }); // stop 真正 tear down:只作废更早的调用+ await pendingStop;+ resolveStart({ ok: true, action: 'start', status: 200 }); // start 应答:重新计使用+ await lateStart;+ expect(tracked.everCalled()).toBe(true);++ await stopRuntimeForQuitIfUsed(tracked, logger);+ expect(call.mock.calls.map(([req]) => req.action)).toEqual(['stop', 'start', 'stop']); // quit 照常清理+ });++ it('a NO-OP stop (stopped:false) does not invalidate a racing cold start (review P1)', async () => {+ // 后端切换的 stop 撞上冷启动:vendored /stop 见 running===null 返回+ // stopped:false(HTTP 200)——它没有 tear down 任何东西,更没覆盖到那次+ // 在途 launch。若照样清使用态+抬屏障,晚到的 start 应答会被忽略,quit+ // 跳过清理,新拉起的 Chrome 和 profile 锁被留下。+ let resolveStart!: (r: BrowserControlResult) => void;+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>((req) => {+ if (req.action === 'start') {+ return new Promise((resolve) => {+ resolveStart = resolve;+ });+ }+ return Promise.resolve(+ req.action === 'stop'+ ? { ok: true, action: req.action, status: 200, data: { stopped: false } }+ : { ok: true, action: req.action, status: 200 },+ );+ });+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ const coldStart = tracked.call({ action: 'start' }); // 冷启动在途(先派发)+ await tracked.call({ action: 'stop' }); // 后端切换的 no-op stop+ resolveStart({ ok: true, action: 'start', status: 200 }); // launch 完成+ await coldStart;+ expect(tracked.everCalled()).toBe(true);++ await stopRuntimeForQuitIfUsed(tracked, logger);+ expect(call.mock.calls.map(([req]) => req.action)).toEqual(['start', 'stop', 'stop']); // quit 照常清理+ });++ it('usage flips back on when non-stop traffic resumes after a successful stop', async () => {+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ async (req) => ({ ok: true, action: req.action, status: 200, data: req.action === 'stop' ? { stopped: true } : undefined }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ await tracked.call({ action: 'status' });+ await tracked.call({ action: 'stop' });+ await tracked.call({ action: 'start' }); // 服务被重新使用+ await stopRuntimeForQuitIfUsed(tracked, logger);++ expect(call.mock.calls.map(([r]) => r.action)).toEqual(['status', 'stop', 'start', 'stop']);+ });+});++describe('stopRuntimeForQuitIfUsed — quit racing an in-flight first call (review P1)', () => {+ it('waits for a still-booting call; success → stop dispatched', async () => {+ let resolveFirst!: (r: BrowserControlResult) => void;+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>((req) =>+ req.action === 'stop'+ ? Promise.resolve({ ok: true, action: req.action, status: 200 })+ : new Promise((resolve) => {+ resolveFirst = resolve;+ }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ void tracked.call({ action: 'start' });+ const quit = stopRuntimeForQuitIfUsed(tracked, logger);+ // 在途启动尚未落定,quit 必须等待而不是立即判"never used"+ resolveFirst({ ok: true, action: 'start', status: 200 });+ await quit;++ expect(call).toHaveBeenCalledTimes(2);+ expect(call.mock.calls[1][0]).toEqual({ action: 'stop' });+ });++ it('waits for a still-booting call; failure → skip (service liveness unproven)', async () => {+ let rejectFirst!: (err: Error) => void;+ const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(+ () =>+ new Promise((_resolve, reject) => {+ rejectFirst = reject;+ }),+ );+ const tracked = trackBrowserRuntimeUsage({ call });+ const logger = fakeLogger();++ void tracked.call({ action: 'start' }).catch(() => undefined);+ const quit = stopRuntimeForQuitIfUsed(tracked, logger);+ rejectFirst(new Error('boot exploded'));+ await quit;++ expect(call).toHaveBeenCalledTimes(1);+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('never used this session'));+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/browser-dispose.ts b/apps/desktop/src/main/mcp-integrations/browser-dispose.tsindex 0a688660a0..6964956f12 100644--- a/apps/desktop/src/main/mcp-integrations/browser-dispose.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-dispose.ts@@ -10,13 +10,207 @@ interface QuitLogger {warn(message: string, ...args: unknown[]): void;}+/** `stopRuntimeForQuitIfUsed` additionally logs the skip decision at info. */+interface QuitInfoLogger extends QuitLogger {+ info(message: string, ...args: unknown[]): void;+}++/**+ * Usage-tracking wrapper around the vendored runtime: records whether ANY+ * request was dispatched through it this session. The quit path uses this to+ * skip the stop dispatch entirely when the runtime was never touched — the+ * vendored dispatch bridge (`dispatchBrowserControlRequest`) unconditionally+ * boots the browser control service (dynamic playwright import included)+ * before routing ANY action, `stop` included, so an unguarded quit-time stop+ * on a browser-less session would START the very service it is shutting down.+ * That service boot is an exit-hang amplifier we must not run during quit.+ */+export interface UsageTrackedBrowserRuntime extends Pick<BrowserControlRuntime, 'call'> {+ /**+ * True iff a NON-stop `call` produced an HTTP response and no successful+ * `stop` has invalidated it since — i.e. the control service provably+ * booted and answered, and (as far as dispatch ordering can tell) has not+ * been torn down again afterwards.+ */+ everCalled(): boolean;+ /**+ * Resolves once every in-flight call — `stop` included — has settled+ * (results and rejections are swallowed). The quit path awaits this before+ * reading `everCalled()`:+ * - a still-booting first call must not be misread as "never used"+ * (review P1): it can finish launching Chrome right after we skipped+ * the stop, orphaning the process and its locked user-data-dir;+ * - an in-flight backend-switch `stop` must settle first too (review):+ * reading usage before its reset lands would make quit dispatch a+ * second stop against a service that is already going down.+ */+ settleInFlight(): Promise<void>;+ /**+ * Quit gate (review P1): after this, NEW non-stop calls are rejected instead+ * of dispatched. Without it a call admitted between "settleInFlight saw an+ * empty set" and "everCalled read" could boot the service mid-shutdown after+ * the skip decision was already made.+ */+ beginQuiescence(): void;+}++export function trackBrowserRuntimeUsage(+ inner: Pick<BrowserControlRuntime, 'call'>,+): UsageTrackedBrowserRuntime {+ let everCalled = false;+ let quiescing = false;+ // Dispatch-order barrier (review ×3, two rounds): every call gets a+ // monotonically increasing dispatch sequence; a SUCCESSFUL stop raises the+ // barrier to its own sequence. A non-stop response only marks usage when+ // its dispatch sequence is ABOVE the barrier:+ // - calls dispatched BEFORE the stop settle late against a torn-down+ // service → blocked (late settle must not re-enable the quit stop);+ // - calls admitted AFTER the stop was dispatched (e.g. a start racing+ // ExternalChromeBackend.dispose during a backend switch) are newer than+ // the barrier → their response re-marks usage, so quit still cleans up+ // the freshly launched Chrome (an epoch-per-stop scheme wrongly+ // invalidated these).+ let dispatchSeq = 0;+ let stopInvalidationBarrier = -1;+ const inFlight = new Set<Promise<unknown>>();+ return {+ call(request) {+ if (quiescing && request.action !== 'stop') {+ // Resolve (not reject): the underlying runtime's contract is that+ // `call` always resolves a BrowserControlResult — callers only check+ // `res.ok` and a rejection here would surface as an unhandled+ // rejection (review). No `status` field, so this never counts as+ // usage either.+ return Promise.resolve({+ ok: false,+ action: request.action,+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',+ message: 'browser runtime is shutting down — new calls are not dispatched',+ });+ }+ const result = inner.call(request);+ // Mark "used" only when the response carries an HTTP `status`, and only+ // for non-stop actions (review feedback, three P1s across two rounds):+ // - `status` present means the dispatcher really answered over the+ // control service — it booted. This includes ok:false HTTP >=400+ // responses (service is up, the action failed) which MUST count,+ // otherwise quit skips the stop and leaks the running service.+ // - `status` absent covers planDispatch rejections and thrown boots+ // (`BROWSER_RUNTIME_UNAVAILABLE` / catch-path failures): service+ // liveness unproven — counting those would make the quit-time stop+ // re-run the very boot we're avoiding.+ // - `stop` itself is teardown, not usage — ExternalChromeBackend.dispose+ // dispatches one during backend switching, and counting it would make+ // the quit path dispatch a second stop that re-boots the service.+ // A wrongly-skipped quit-stop is recovered by the vendored stale-lock+ // path on next launch (see stopRuntimeForQuit docs).+ const mySeq = dispatchSeq;+ dispatchSeq += 1;+ let settled: Promise<unknown>;+ if (request.action !== 'stop') {+ settled = result.then(+ (response) => {+ const status = (response as { status?: unknown } | null | undefined)?.status;+ // Barrier check: only calls dispatched after the latest+ // successful stop may (re-)mark usage — see barrier comment.+ if (typeof status === 'number' && mySeq > stopInvalidationBarrier) {+ everCalled = true;+ }+ },+ () => {+ // Rejected dispatch proves nothing about service liveness — ignore.+ },+ );+ } else {+ // A settled SUCCESSFUL stop proves the service is down again (review+ // P1: ExternalChromeBackend.dispose stops it mid-session on backend+ // switch). Keeping usage true past that point would make the+ // quit-time stop boot the already-stopped service — the exact+ // startup this wrapper exists to prevent. The barrier only+ // invalidates calls dispatched BEFORE this stop; anything admitted+ // after it can re-mark usage. ok:false / rejected stops leave state+ // unchanged: the service may still be up, and a possibly-redundant+ // quit stop is the safe direction there.+ settled = result.then(+ (response) => {+ const r = response as+ | { ok?: unknown; data?: { stopped?: unknown } | null }+ | null+ | undefined;+ // Only a stop that actually tore something down invalidates usage+ // (review P1): the vendored /stop reports `data.stopped`, and a+ // no-op stop (`stopped:false` — nothing running at that instant,+ // e.g. it raced a cold `start` whose launch it did NOT cover)+ // must leave usage and the barrier untouched, so the racing+ // start's later response re-marks usage and quit still cleans up+ // the Chrome it launched. Vendored state machine guarantees+ // `stopped:true` only after the launch finished (`running` is+ // assigned post-launch), so a mid-launch race always lands here+ // as `stopped:false`.+ if (r?.ok === true && r.data?.stopped === true) {+ everCalled = false;+ stopInvalidationBarrier = Math.max(stopInvalidationBarrier, mySeq);+ }+ },+ () => {},+ );+ }+ // Stops are tracked in inFlight too (review): settleInFlight must let a+ // racing backend-switch stop land its usage reset before the quit path+ // reads everCalled, or quit dispatches a second stop.+ inFlight.add(settled);+ void settled.finally(() => inFlight.delete(settled));+ return result;+ },+ everCalled: () => everCalled,+ settleInFlight: async () => {+ // Snapshot-loop until quiescent: an in-flight call may itself trigger+ // follow-up calls (e.g. login flow chaining start → focus).+ while (inFlight.size > 0) {+ await Promise.all([...inFlight]);+ }+ },+ beginQuiescence: () => {+ quiescing = true;+ },+ };+}++/**+ * Quit-path stop, short-circuited when the runtime saw zero traffic this+ * session (see `trackBrowserRuntimeUsage`). If any request DID go through,+ * the control service already exists, so dispatching `stop` cannot newly+ * boot anything — it only tears down whatever the session created.+ */+export async function stopRuntimeForQuitIfUsed(+ runtime: UsageTrackedBrowserRuntime,+ logger: QuitInfoLogger,+): Promise<void> {+ // Quit can race the very first call (e.g. openBrowserForLogin still awaiting+ // `start`): close the gate to NEW calls first, then wait for in-flight ones+ // to settle before deciding — otherwise a still-booting Chrome would be+ // misread as "never used" and outlive the app, or a call admitted right+ // after the settle-check could boot the service mid-shutdown (review P1).+ // Bounded externally: this runs inside the async disposer phase (timeoutMs+ // race) with the hard-kill watchdog behind it.+ runtime.beginQuiescence();+ await runtime.settleInFlight();+ if (!runtime.everCalled()) {+ logger.info('browser runtime never used this session — skipping quit-time stop');+ return;+ }+ await stopRuntimeForQuit(runtime, logger);+}+/*** Stop the managed browser on the app-quit path.** Swallows/logs all failures: this runs inside the lifecycle disposer chain* where throwing would only stall shutdown, and a failed stop is recovered by- * the vendored stale-lock path on next launch. `stop` is idempotent — a no-op if- * the browser was never started.+ * the vendored stale-lock path on next launch. `stop` won't kill anything that+ * isn't running — but note the dispatch itself boots the browser control+ * service if it isn't up yet, so quit-time callers should prefer+ * `stopRuntimeForQuitIfUsed` to avoid starting services during shutdown.** An unprofiled `stop` resolves the DEFAULT profile, which is sufficient because* the runtime is configured with exactly one managed profile (the sync.mjs patchdiff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.tsindex 9bdcb6f8bf..c53afbac77 100644--- a/apps/desktop/src/main/mcp-integrations/browser.ts+++ b/apps/desktop/src/main/mcp-integrations/browser.ts@@ -19,7 +19,7 @@ import { createLogger } from '../logger.js';import { extractBrowserAvailability, type BrowserAvailability } from './browser-availability.js';import { loadUserBrowserRecipes, type UserRecipesResult } from '../browser-recipes/loader.js';import { writeUserRecipe, type WriteUserRecipeResult } from '../browser-recipes/writer.js';-import { stopRuntimeForQuit } from './browser-dispose.js';+import { stopRuntimeForQuitIfUsed, trackBrowserRuntimeUsage } from './browser-dispose.js';import {BackendRouter,ExternalChromeBackend,@@ -159,21 +159,26 @@ healLegacyManagedProfileDir();// Single shared runtime for the desktop process. Boots with the managed profile// (electron-free, safe at module-eval); logs route into the unified logger.//-// `vendoredRuntime` is the raw upstream object. We never hand it out directly —-// it sits behind the `ExternalChromeBackend` wrapper, which itself sits behind-// the `BackendRouter`. The router is what callers (@cindy/mcps via-// `getBrowserMcpDeps`, host helpers below) receive, so swapping the active-// backend in Phase 5 is a single `router.setBackend()` call away.-const vendoredRuntime: BrowserControlRuntime = createBrowserControlRuntime({- config: buildManagedConfig(),- logSink: (level, scope, args) => {- // Bind to `logger`: the unified logger's methods rely on `this`, and calling- // a detached `logger[level]` reference would lose it (undefined in strict- // mode) and silently break the browser runtime's log channel.- const fn = (logger[level] ?? logger.info).bind(logger);- fn(`[${scope}]`, ...args);- },-});+// `vendoredRuntime` is the raw upstream object behind a thin usage-tracking+// wrapper (see `trackBrowserRuntimeUsage`): every consumer in this module —+// the `ExternalChromeBackend` (behind the `BackendRouter`, which is what+// @cindy/mcps via `getBrowserMcpDeps` and host helpers below receive), the+// availability probe and the login helper — calls through the wrapper, so+// `disposeBrowserRuntime` can tell whether the runtime saw ANY traffic this+// session. We never hand the raw object out; swapping the active backend in+// Phase 5 is a single `router.setBackend()` call away.+const vendoredRuntime = trackBrowserRuntimeUsage(+ createBrowserControlRuntime({+ config: buildManagedConfig(),+ logSink: (level, scope, args) => {+ // Bind to `logger`: the unified logger's methods rely on `this`, and calling+ // a detached `logger[level]` reference would lose it (undefined in strict+ // mode) and silently break the browser runtime's log channel.+ const fn = (logger[level] ?? logger.info).bind(logger);+ fn(`[${scope}]`, ...args);+ },+ }),+);const externalBackend = new ExternalChromeBackend(vendoredRuntime, logger);@@ -452,8 +457,7 @@ export async function openBrowserForLogin(): Promise<void> {* spawned process owned by the vendored runtime; nothing else sends `stop`, so* without this the headed Chrome + its locked user-data-dir survive app* quit / crash / dev-reload, and the next launch has to recover a stale- * SingletonLock. Delegates to the active backend's `dispose` via the router —- * for the external backend that is the electron-free `stopRuntimeForQuit`+ * SingletonLock. Goes through the electron-free `stopRuntimeForQuitIfUsed`* (which swallows errors — see browser-dispose.ts).** NOTE (Windows): the vendored stop sends SIGTERM→SIGKILL to the launched Chrome@@ -473,8 +477,11 @@ export function disposeBrowserRuntime(): Promise<void> {// doesn't know about the swap and Phase 5 swap-time dispose already ran;// a stale-lock recovery on next launch is the symptom).//- // `stopRuntimeForQuit` is idempotent — if Chrome never started this turn- // it's a no-op; if it's running it stops cleanly. Safe to call regardless- // of which backend is currently active.- return stopRuntimeForQuit(vendoredRuntime, logger);+ // Short-circuit via the usage tracker: the vendored dispatch bridge boots+ // the browser control service (dynamic playwright import included) before+ // routing ANY action, `stop` included — so on a session that never touched+ // the browser runtime, an unconditional stop would START services during+ // quit, which is an exit-hang amplifier. If the runtime WAS used, `stop` is+ // idempotent and safe regardless of which backend is currently active.+ return stopRuntimeForQuitIfUsed(vendoredRuntime, logger);}