Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): wait for real process close in desktop smoke cleanup (#4352)
Nick Gomez6a43563eabdb
diff --git a/packages/desktop/tests/smoke/_helpers/electron-cleanup.test-helper.ts b/packages/desktop/tests/smoke/_helpers/electron-cleanup.test-helper.tsnew file mode 100644index 000000000..9e834367d--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/electron-cleanup.test-helper.ts@@ -0,0 +1,15 @@+import type { TaskkillOutcome } from './electron-cleanup';++export function timedOutTaskkill(): TaskkillOutcome {+ return { status: null, signal: null, stdout: '', stderr: '', timedOut: true };+}++export function reapedTaskkill(pid: number): TaskkillOutcome {+ return {+ status: 0,+ signal: null,+ stdout: `SUCCESS: The process with PID ${pid} has been terminated.\r\n`,+ stderr: '',+ timedOut: false,+ };+}diff --git a/packages/desktop/tests/smoke/_helpers/electron-cleanup.test.ts b/packages/desktop/tests/smoke/_helpers/electron-cleanup.test.tsindex 570253f04..4182979c6 100644--- a/packages/desktop/tests/smoke/_helpers/electron-cleanup.test.ts+++ b/packages/desktop/tests/smoke/_helpers/electron-cleanup.test.ts@@ -1,6 +1,14 @@-import { type ChildProcess, spawn } from 'node:child_process';+import { type ChildProcess, spawn, spawnSync } from 'node:child_process';+import { once } from 'node:events';import { afterEach, describe, expect, test } from 'vitest';-import { closeAppBounded } from './electron-cleanup';+import {+ AppCleanupIncompleteError,+ closeAppBounded,+ type TaskkillOutcome,+} from './electron-cleanup';+import { reapedTaskkill, timedOutTaskkill } from './electron-cleanup.test-helper';++const REAP_MS = 50;const spawnedProcs: ChildProcess[] = [];@@ -55,9 +63,9 @@ describe('closeAppBounded — real subprocess contract', () => {expect(proc.exitCode === 0 || proc.signalCode !== null).toBe(true);});- test('(b) hung subprocess (traps + ignores SIGTERM) → returns within gracefulMs + slack, kill spy receives (-pid, SIGKILL)', async () => {+ test('(b) hung subprocess and a kill spy that reaps nothing → every attempt targets (-pid, SIGKILL) and the call reports incomplete closure', async () => {const hangBody = `- process.on('SIGTERM', () => { /* swallow */ });+ process.on('SIGTERM', () => {});setInterval(() => {}, 1000);`;const proc = spawnNode(hangBody);@@ -70,14 +78,19 @@ describe('closeAppBounded — real subprocess contract', () => {killCalls.push({ pid: killPid, signal });};- const start = Date.now();- await closeAppBounded(proc, { gracefulMs: 300, kill: spyKill, platform: 'linux' });- const elapsed = Date.now() - start;+ await expect(+ closeAppBounded(proc, {+ gracefulMs: 300,+ postKillReapMs: REAP_MS,+ kill: spyKill,+ platform: 'linux',+ }),+ ).rejects.toBeInstanceOf(AppCleanupIncompleteError);- expect(elapsed).toBeLessThan(3_000);-- expect(killCalls.length).toBe(1);- expect(killCalls[0]).toEqual({ pid: -pid, signal: 'SIGKILL' });+ expect(killCalls).toEqual([+ { pid: -pid, signal: 'SIGKILL' },+ { pid: -pid, signal: 'SIGKILL' },+ ]);});test('(c) already-exited subprocess → closeAppBounded returns ~immediately, no kill fired', async () => {@@ -105,3 +118,245 @@ describe('closeAppBounded — real subprocess contract', () => {expect(killCalls).toEqual([]);});});++const HOLDER_SCRIPT = 'setInterval(() => {}, 1000);';+const HANG_FOREVER = "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000);";++function exitAfter(ms: number): string {+ return `setTimeout(() => process.exit(0), ${ms});`;+}++function rootScript(afterHolderSpawn: string): string {+ return [+ "const { spawn } = require('node:child_process');",+ `const holder = spawn(process.execPath, ['-e', ${JSON.stringify(HOLDER_SCRIPT)}], { stdio: 'inherit' });`,+ afterHolderSpawn,+ "process.stdout.write('HOLDER_PID=' + holder.pid + '\\n');",+ ].join('\n');+}++function psStat(pid: number): string {+ const res = spawnSync('ps', ['-p', String(pid), '-o', 'stat='], { encoding: 'utf8' });+ if (res.error !== undefined) throw res.error;+ return (res.stdout ?? '').trim();+}++function isAlive(pid: number): boolean {+ const stat = psStat(pid);+ return stat.length > 0 && !stat.startsWith('Z');+}++interface StreamHeldTree {+ root: ChildProcess;+ rootPid: number;+ holderPid: number;+ closeObserved: () => boolean;+}++interface TrackedTree {+ rootPid: number;+ holderPid: number | undefined;+}++const liveTrees: TrackedTree[] = [];++afterEach(() => {+ for (const tracked of liveTrees) {+ try {+ process.kill(-tracked.rootPid, 'SIGKILL');+ } catch {}+ if (tracked.holderPid === undefined) continue;+ try {+ process.kill(tracked.holderPid, 'SIGKILL');+ } catch {}+ }+ liveTrees.length = 0;+});++async function spawnStreamHeldTree(afterHolderSpawn: string): Promise<StreamHeldTree> {+ const root = spawn(process.execPath, ['-e', rootScript(afterHolderSpawn)], {+ stdio: 'pipe',+ detached: true,+ });+ if (root.pid === undefined) await once(root, 'spawn');+ const rootPid = root.pid;+ if (rootPid === undefined) throw new Error('spawn did not assign a root pid');++ const tracked: TrackedTree = { rootPid, holderPid: undefined };+ liveTrees.push(tracked);++ let closeObserved = false;+ root.once('close', () => {+ closeObserved = true;+ });++ let stdout = '';+ root.stdout?.on('data', (chunk: Buffer) => {+ stdout += chunk.toString('utf8');+ });+ root.stderr?.on('data', () => {});++ const holderPid = await new Promise<number>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error('root process never reported its stdio-holding descendant')),+ 10_000,+ );+ const check = () => {+ const match = /HOLDER_PID=(\d+)/.exec(stdout);+ if (match?.[1] === undefined) return;+ clearTimeout(timer);+ root.stdout?.off('data', check);+ resolve(Number(match[1]));+ };+ root.stdout?.on('data', check);+ check();+ });++ tracked.holderPid = holderPid;+ return { root, rootPid, holderPid, closeObserved: () => closeObserved };+}++describe.skipIf(process.platform === 'win32')(+ 'closeAppBounded — close, not exit, is the postcondition',+ () => {+ test('(1) root exits on its own while a descendant still holds its stdio → returns only once the launched process closed', async () => {+ const tree = await spawnStreamHeldTree(exitAfter(150));++ await closeAppBounded(tree.root, { gracefulMs: 1_000, platform: 'linux' });++ expect({+ closeObserved: tree.closeObserved(),+ holderAlive: isAlive(tree.holderPid),+ }).toEqual({ closeObserved: true, holderAlive: false });+ });++ test('(2) hung root with a stdio-holding descendant → returns only once the group kill reached both and the launched process closed', async () => {+ const tree = await spawnStreamHeldTree(HANG_FOREVER);++ await closeAppBounded(tree.root, { gracefulMs: 500, platform: 'linux' });++ expect({+ closeObserved: tree.closeObserved(),+ rootAlive: isAlive(tree.rootPid),+ holderAlive: isAlive(tree.holderPid),+ }).toEqual({ closeObserved: true, rootAlive: false, holderAlive: false });+ });++ test('(3) win32 tree-kill reports ETIMEDOUT once and kills nothing, then succeeds → converges to real closure', async () => {+ const tree = await spawnStreamHeldTree(HANG_FOREVER);+ const attempts: TaskkillOutcome[] = [];++ const taskkill = async (pid: number): Promise<TaskkillOutcome> => {+ if (attempts.length === 0) {+ const timedOut = timedOutTaskkill();+ attempts.push(timedOut);+ return timedOut;+ }+ try {+ process.kill(-pid, 'SIGKILL');+ } catch {}+ const reaped = reapedTaskkill(pid);+ attempts.push(reaped);+ return reaped;+ };++ await closeAppBounded(tree.root, { gracefulMs: 500, taskkill, platform: 'win32' });++ expect({+ closeObserved: tree.closeObserved(),+ rootAlive: isAlive(tree.rootPid),+ holderAlive: isAlive(tree.holderPid),+ }).toEqual({ closeObserved: true, rootAlive: false, holderAlive: false });+ expect(attempts.length).toBe(2);+ });++ test('(4) win32 tree-kill always reports ETIMEDOUT and kills nothing → never returns normally while the tree is still alive', async () => {+ const tree = await spawnStreamHeldTree(HANG_FOREVER);+ const attempts: number[] = [];++ const taskkill = async (pid: number): Promise<TaskkillOutcome> => {+ attempts.push(pid);+ return timedOutTaskkill();+ };++ const outcome = await closeAppBounded(tree.root, {+ gracefulMs: 500,+ postKillReapMs: REAP_MS,+ taskkill,+ platform: 'win32',+ }).then(+ () => 'returned' as const,+ (error: unknown) =>+ error instanceof AppCleanupIncompleteError ? ('reported-failure' as const) : 'threw',+ );++ const rootAlive = isAlive(tree.rootPid);+ const holderAlive = isAlive(tree.holderPid);++ expect({+ outcome,+ attemptedPids: attempts,+ claimedCleanupComplete: outcome === 'returned' && (rootAlive || holderAlive),+ }).toEqual({+ outcome: 'reported-failure',+ attemptedPids: [tree.rootPid, tree.rootPid],+ claimedCleanupComplete: false,+ });+ });++ test('(5) root already exited before the call while a descendant still holds its stdio → escalation still establishes closure', async () => {+ const tree = await spawnStreamHeldTree(exitAfter(50));+ if (tree.root.exitCode === null && tree.root.signalCode === null) {+ await once(tree.root, 'exit');+ }++ await closeAppBounded(tree.root, { gracefulMs: 1_000, platform: 'linux' });++ expect({+ closeObserved: tree.closeObserved(),+ holderAlive: isAlive(tree.holderPid),+ }).toEqual({ closeObserved: true, holderAlive: false });+ });++ test('(7) a piped process that already closed before the call → the structural fallback returns without a kill', async () => {+ const proc = spawn(process.execPath, ['-e', 'process.exit(0);'], {+ stdio: 'pipe',+ detached: true,+ });+ spawnedProcs.push(proc);+ proc.stdout?.on('data', () => {});+ proc.stderr?.on('data', () => {});+ await once(proc, 'close');++ const killCalls: number[] = [];+ const start = Date.now();+ await closeAppBounded(proc, {+ gracefulMs: 5_000,+ kill: (pid) => {+ killCalls.push(pid);+ },+ platform: 'linux',+ });++ expect({ elapsedUnder250ms: Date.now() - start < 250, killCalls }).toEqual({+ elapsedUnder250ms: true,+ killCalls: [],+ });+ });++ test('(6) a signal was sent but the root ignored it → `killed === true` alone is not closure', async () => {+ const tree = await spawnStreamHeldTree(HANG_FOREVER);+ tree.root.kill('SIGTERM');+ expect(tree.root.killed).toBe(true);+ expect(isAlive(tree.rootPid)).toBe(true);++ await closeAppBounded(tree.root, { gracefulMs: 500, platform: 'linux' });++ expect({+ closeObserved: tree.closeObserved(),+ rootAlive: isAlive(tree.rootPid),+ holderAlive: isAlive(tree.holderPid),+ }).toEqual({ closeObserved: true, rootAlive: false, holderAlive: false });+ });+ },+);diff --git a/packages/desktop/tests/smoke/_helpers/electron-cleanup.ts b/packages/desktop/tests/smoke/_helpers/electron-cleanup.tsindex 4544901e5..6fdff20c2 100644--- a/packages/desktop/tests/smoke/_helpers/electron-cleanup.ts+++ b/packages/desktop/tests/smoke/_helpers/electron-cleanup.ts@@ -1,27 +1,92 @@import type { ChildProcess } from 'node:child_process';-import { spawnSync } from 'node:child_process';+import { spawn } from 'node:child_process';import { type Dirent, readdirSync, readFileSync } from 'node:fs';import { join } from 'node:path';import type { ElectronApplication } from '@playwright/test';+export interface TaskkillOutcome {+ status: number | null;+ signal: NodeJS.Signals | null;+ stdout: string;+ stderr: string;+ error?: Error;+ timedOut: boolean;+}+export interface CloseAppBoundedOpts {gracefulMs?: number;+ postKillReapMs?: number;kill?: (pid: number, signal: NodeJS.Signals | string) => void;- taskkill?: (pid: number) => void;+ taskkill?: (pid: number) => Promise<TaskkillOutcome>;platform?: NodeJS.Platform;}const POST_KILL_REAP_MS = 2_000;+const TASKKILL_TIMEOUT_MS = 5_000;+const KILL_ATTEMPTS = 2;-function taskkillTree(pid: number): void {- spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], {- stdio: 'ignore',- timeout: 5_000,+export function taskkillTree(pid: number): Promise<TaskkillOutcome> {+ return new Promise<TaskkillOutcome>((resolve) => {+ let child: ChildProcess;+ try {+ child = spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true });+ } catch (error) {+ resolve({+ status: null,+ signal: null,+ stdout: '',+ stderr: '',+ error: error instanceof Error ? error : new Error(String(error)),+ timedOut: false,+ });+ return;+ }+ let stdout = '';+ let stderr = '';+ child.stdout?.on('data', (chunk: Buffer) => {+ stdout += chunk.toString('utf8');+ });+ child.stderr?.on('data', (chunk: Buffer) => {+ stderr += chunk.toString('utf8');+ });+ let settled = false;+ const settle = (outcome: Omit<TaskkillOutcome, 'stdout' | 'stderr'>) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve({ ...outcome, stdout, stderr });+ };+ const timer = setTimeout(() => {+ child.kill('SIGKILL');+ settle({ status: null, signal: null, timedOut: true });+ }, TASKKILL_TIMEOUT_MS);+ timer.unref();+ child.once('error', (error: Error) =>+ settle({ status: null, signal: null, error, timedOut: false }),+ );+ child.once('close', (status: number | null, signal: NodeJS.Signals | null) =>+ settle({ status, signal, timedOut: false }),+ );+ });+}++const closed = new WeakSet<ChildProcess>();+const watched = new WeakSet<ChildProcess>();+const incomplete = new WeakMap<ChildProcess, AppCleanupIncompleteError>();++function watchForClose(proc: ChildProcess): void {+ if (watched.has(proc)) return;+ watched.add(proc);+ proc.once('close', () => {+ closed.add(proc);});+ if (closedBeforeFirstSight(proc)) closed.add(proc);}export function captureAppProcess(app: ElectronApplication): ChildProcess {- return app.process();+ const proc = app.process();+ watchForClose(proc);+ return proc;}const LOCK_SEARCH_DEPTH = 3;@@ -57,53 +122,160 @@ export function reapDetachedServers(dirs: readonly string[]): void {}}-export async function closeAppBounded(- proc: ChildProcess | null,- opts: CloseAppBoundedOpts = {},-): Promise<void> {- if (proc === null) return;-- if (isProcessGone(proc)) return;-- const gracefulMs = opts.gracefulMs ?? 5_000;+function openStdioCount(proc: ChildProcess): number {+ const slots = Array.isArray(proc.stdio) ? proc.stdio : [];+ let open = 0;+ for (const slot of slots) {+ if (slot === null || slot === undefined) continue;+ if (slot.destroyed) continue;+ open += 1;+ }+ return open;+}- await waitForExit(proc, gracefulMs);+function hasExited(proc: ChildProcess): boolean {+ return proc.exitCode !== null || proc.signalCode !== null;+}- if (isProcessGone(proc)) return;+function closedBeforeFirstSight(proc: ChildProcess): boolean {+ return hasExited(proc) && openStdioCount(proc) === 0;+}- const killFn = opts.kill ?? process.kill.bind(process);- if (typeof proc.pid === 'number' && Number.isInteger(proc.pid) && proc.pid > 0) {- if ((opts.platform ?? process.platform) === 'win32') {- (opts.taskkill ?? taskkillTree)(proc.pid);- await waitForExit(proc, Math.min(gracefulMs, POST_KILL_REAP_MS));- return;- }- try {- killFn(-proc.pid, 'SIGKILL');- } catch {}- }+function hasClosed(proc: ChildProcess): boolean {+ return closed.has(proc);}-function isProcessGone(proc: ChildProcess): boolean {- return proc.exitCode !== null || proc.signalCode !== null || proc.killed === true;+function usablePid(proc: ChildProcess): number | undefined {+ const pid = proc.pid;+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return undefined;+ return pid;}-function waitForExit(proc: ChildProcess, timeoutMs: number): Promise<void> {+function waitForClose(proc: ChildProcess, timeoutMs: number): Promise<void> {return new Promise<void>((resolve) => {- if (isProcessGone(proc)) {+ if (hasClosed(proc)) {resolve();return;}- let settled = false;- const settle = () => {- if (settled) return;- settled = true;- proc.off('exit', settle);+ let done = false;+ const finish = () => {+ if (done) return;+ done = true;+ proc.off('close', onClose);clearTimeout(timer);resolve();};- const timer = setTimeout(settle, timeoutMs);- (timer as unknown as { unref?: () => void }).unref?.();- proc.once('exit', settle);+ const onClose = () => finish();+ const timer = setTimeout(finish, timeoutMs);+ timer.unref();+ proc.on('close', onClose);});}++export type KillAttempt = { elapsedMs: number } & (+ | { lever: 'taskkill'; outcome: TaskkillOutcome }+ | { lever: 'group-kill'; thrown: unknown }+ | { lever: 'no-pid' }+);++async function escalate(proc: ChildProcess, opts: CloseAppBoundedOpts): Promise<KillAttempt> {+ const startedAt = Date.now();+ const pid = usablePid(proc);+ if (pid === undefined) return { lever: 'no-pid', elapsedMs: Date.now() - startedAt };+ if ((opts.platform ?? process.platform) === 'win32') {+ const outcome = await (opts.taskkill ?? taskkillTree)(pid);+ return { lever: 'taskkill', outcome, elapsedMs: Date.now() - startedAt };+ }+ const killFn = opts.kill ?? process.kill.bind(process);+ try {+ killFn(-pid, 'SIGKILL');+ return { lever: 'group-kill', thrown: undefined, elapsedMs: Date.now() - startedAt };+ } catch (thrown) {+ return { lever: 'group-kill', thrown, elapsedMs: Date.now() - startedAt };+ }+}++function quote(text: string): string {+ const trimmed = text.trim();+ return trimmed.length === 0 ? 'none' : JSON.stringify(trimmed);+}++function describeAttempt(attempt: KillAttempt, slot: number): string {+ const label = `attempt ${slot + 1} after ${attempt.elapsedMs}ms`;+ if (attempt.lever === 'no-pid') return `${label}: no usable pid, no kill lever available`;+ if (attempt.lever === 'group-kill') {+ const thrown = attempt.thrown;+ if (thrown === undefined) return `${label}: kill(-pid, SIGKILL) sent`;+ const detail = thrown instanceof Error ? thrown.message : String(thrown);+ return `${label}: kill(-pid, SIGKILL) threw ${detail}`;+ }+ const { status, signal, error, stdout, stderr, timedOut } = attempt.outcome;+ return `${label}: taskkill /T /F status=${String(status)} signal=${signal ?? 'none'} timedOut=${timedOut} error=${+ error === undefined ? 'none' : error.message+ } stdout=${quote(stdout)} stderr=${quote(stderr)}`;+}++export class AppCleanupIncompleteError extends Error {+ readonly pid: number | undefined;+ readonly exitCode: number | null;+ readonly signalCode: NodeJS.Signals | null;+ readonly openStdioStreams: number;+ readonly gracefulWaitMs: number;+ readonly attempts: readonly KillAttempt[];++ constructor(proc: ChildProcess, attempts: readonly KillAttempt[], gracefulWaitMs: number) {+ const openStdioStreams = openStdioCount(proc);+ const header = [+ `closeAppBounded could not establish close for pid ${proc.pid ?? 'unknown'}`,+ `exitCode=${String(proc.exitCode)}`,+ `signalCode=${proc.signalCode ?? 'none'}`,+ `openStdioStreams=${openStdioStreams}`,+ `gracefulWaitMs=${gracefulWaitMs}`,+ ].join(' ');+ super([header, ...attempts.map(describeAttempt)].join('\n '));+ this.name = 'AppCleanupIncompleteError';+ this.pid = proc.pid;+ this.exitCode = proc.exitCode;+ this.signalCode = proc.signalCode;+ this.openStdioStreams = openStdioStreams;+ this.gracefulWaitMs = gracefulWaitMs;+ this.attempts = attempts;+ }+}++export async function closeAppBounded(+ proc: ChildProcess | null,+ opts: CloseAppBoundedOpts = {},+): Promise<void> {+ if (proc === null) return;++ watchForClose(proc);+ if (hasClosed(proc)) return;+ const prior = incomplete.get(proc);+ if (prior !== undefined) throw prior;++ const gracefulMs = opts.gracefulMs ?? 5_000;+ const reapMs = opts.postKillReapMs ?? POST_KILL_REAP_MS;++ const gracefulStartedAt = Date.now();+ await waitForClose(proc, gracefulMs);+ const gracefulWaitMs = Date.now() - gracefulStartedAt;+ if (hasClosed(proc)) return;++ const escalationDeadline = Date.now() + KILL_ATTEMPTS * (TASKKILL_TIMEOUT_MS + reapMs);+ const attempts: KillAttempt[] = [];+ for (let round = 0; round < KILL_ATTEMPTS; round += 1) {+ const attempt = await escalate(proc, opts);+ attempts.push(attempt);+ if (hasClosed(proc)) return;+ if (attempt.lever === 'no-pid') break;+ const remainingMs = escalationDeadline - Date.now();+ if (remainingMs <= 0) break;+ await waitForClose(proc, Math.min(reapMs, remainingMs));+ if (hasClosed(proc)) return;+ }++ const failure = new AppCleanupIncompleteError(proc, attempts, gracefulWaitMs);+ incomplete.set(proc, failure);+ throw failure;+}diff --git a/packages/desktop/tests/smoke/_helpers/no-unbounded-app-close.test.ts b/packages/desktop/tests/smoke/_helpers/no-unbounded-app-close.test.tsindex cd67b96b1..2ab697246 100644--- a/packages/desktop/tests/smoke/_helpers/no-unbounded-app-close.test.ts+++ b/packages/desktop/tests/smoke/_helpers/no-unbounded-app-close.test.ts@@ -99,6 +99,10 @@ function formatViolations(violations: Violation[]): string {lines.push('Test bodies should NOT introduce an unbounded `await app.close()` ahead');lines.push("of the fixture teardown — Playwright runs the body's `finally` first,");lines.push('and an unbounded await there hangs through the 150 s outer timeout.');+ lines.push('`closeAppBounded` REJECTS with `AppCleanupIncompleteError` when it cannot');+ lines.push('establish `close`, so a test body that calls it directly must handle that');+ lines.push('rejection: an unhandled one inside a `finally` replaces the real failure the');+ lines.push('body was reporting. The fixture aggregates and reports every unclosed app.');lines.push('See `_helpers/electron-cleanup.ts` for the bounded primitive contract.');return lines.join('\n');}diff --git a/packages/desktop/tests/smoke/_helpers/settings-surface.ts b/packages/desktop/tests/smoke/_helpers/settings-surface.tsindex d8dfaff13..78393d4f6 100644--- a/packages/desktop/tests/smoke/_helpers/settings-surface.ts+++ b/packages/desktop/tests/smoke/_helpers/settings-surface.ts@@ -418,10 +418,13 @@ export async function awaitEngineSpellcheckEnabled(export async function closeAppForRelaunch(app: ElectronApplication): Promise<void> {const proc = captureAppProcess(app);- await Promise.race([- app.close().catch(() => undefined),- closeAppBounded(proc, { gracefulMs: 5_000 }),- ]);+ void app.close().catch(() => undefined);+ await closeAppBounded(proc, { gracefulMs: 5_000 }).catch((error: unknown) => {+ throw new Error(+ 'app did not close; the relaunch shares this userDataDir and would fail requestSingleInstanceLock',+ { cause: error },+ );+ });}export function editorBody(editor: Page) {diff --git a/packages/desktop/tests/smoke/_helpers/smoke-test.ts b/packages/desktop/tests/smoke/_helpers/smoke-test.tsindex c46cb582d..6dd38396c 100644--- a/packages/desktop/tests/smoke/_helpers/smoke-test.ts+++ b/packages/desktop/tests/smoke/_helpers/smoke-test.ts@@ -86,11 +86,24 @@ export const test = baseTest.extend<SmokeFixtures>({console.warn(`[smoke-test] boot-log attach failed: ${reason}`);}}- if (shouldAttachStderr(testInfo)) {- await attachCapturedStderr(testInfo, captures);- }+ const unclosed: Error[] = [];for (const proc of procs) {- await closeAppBounded(proc, { gracefulMs: 5_000 });+ try {+ await closeAppBounded(proc, { gracefulMs: 5_000 });+ } catch (error) {+ unclosed.push(error instanceof Error ? error : new Error(String(error)));+ }+ }+ if (unclosed.length > 0) {+ try {+ await testInfo.attach('app-cleanup-incomplete', {+ body: unclosed.map((error) => error.message).join('\n\n'),+ contentType: 'text/plain',+ });+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ console.warn(`[smoke-test] cleanup-diagnostic attach failed: ${reason}`);+ }}reapDetachedServers(cleanupDirs);for (const dir of cleanupDirs) {@@ -101,6 +114,18 @@ export const test = baseTest.extend<SmokeFixtures>({console.warn(`[smoke-test] tmp-dir cleanup failed for ${dir}: ${reason}`);}}+ if (shouldAttachStderr(testInfo) || unclosed.length > 0) {+ await attachCapturedStderr(testInfo, captures);+ }+ if (unclosed.length > 0) {+ for (const error of unclosed) {+ console.error(`[smoke-test] cleanup incomplete: ${error.message}`);+ }+ throw new AggregateError(+ unclosed,+ `[smoke-test] ${unclosed.length} app process(es) did not close`,+ );+ }},});diff --git a/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts b/packages/desktop/tests/smoke/qa-create-new-extended.e2e.tsindex 9fc9d57ba..148046a43 100644--- a/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts+++ b/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts@@ -293,7 +293,12 @@ test.describe('QA extended create-new-project', () => {expect(existsSync(join(firstProject, '.cursor'))).toBe(false);expect(existsSync(join(firstProject, '.mcp.json'))).toBe(false);- await closeAppBounded(app1Proc, { gracefulMs: 5_000 });+ await closeAppBounded(app1Proc, { gracefulMs: 5_000 }).catch((error: unknown) => {+ throw new Error(+ 'app1 did not close; app2 shares this userDataDir and would fail requestSingleInstanceLock',+ { cause: error },+ );+ });const stateAfterSubmit = JSON.parse(readFileSync(join(userDataDir, 'state.json'), 'utf8'));expect(stateAfterSubmit.lastUsedProjectParent).toBe(parent);diff --git a/packages/desktop/tests/smoke/slidev-render-readiness.e2e.ts b/packages/desktop/tests/smoke/slidev-render-readiness.e2e.tsindex 97d3edef0..2306cfdf1 100644--- a/packages/desktop/tests/smoke/slidev-render-readiness.e2e.ts+++ b/packages/desktop/tests/smoke/slidev-render-readiness.e2e.ts@@ -98,11 +98,14 @@ async function isReachable(url: string): Promise<boolean> {}async function closeElectronAppBounded(app: ElectronApplication): Promise<void> {- const process = captureAppProcess(app);- await Promise.race([- app.close().catch(() => undefined),- closeAppBounded(process, { gracefulMs: 5_000 }),- ]);+ const proc = captureAppProcess(app);+ void app.close().catch(() => undefined);+ await closeAppBounded(proc, { gracefulMs: 5_000 }).catch((error: unknown) => {+ const reason = error instanceof Error ? error.message : String(error);+ console.warn(+ `[slidev-render-readiness] cleanup incomplete, fixture teardown reports it: ${reason}`,+ );+ });}test.describe('Slidev renderer readiness smoke', () => {diff --git a/packages/desktop/tests/smoke/uninstall-result.e2e.ts b/packages/desktop/tests/smoke/uninstall-result.e2e.tsindex 9d0250ef5..b1f8273ae 100644--- a/packages/desktop/tests/smoke/uninstall-result.e2e.ts+++ b/packages/desktop/tests/smoke/uninstall-result.e2e.ts@@ -16,12 +16,16 @@ import { join } from 'node:path';import type { OkUninstallBridge } from '@inkeep/open-knowledge-core';import { type Browser, chromium, _electron as electron, expect, test } from '@playwright/test';import { buildDesktopUninstallHandoffScript } from '../../src/main/desktop-uninstall-handoff';-import { closeAppBounded } from './_helpers/electron-cleanup';+import { captureAppProcess, closeAppBounded } from './_helpers/electron-cleanup';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';const TARGET = resolveDesktopTarget();const DARWIN = process.platform === 'darwin';const owned: string[] = [];+const cleanupFailures: string[] = [];+test.afterEach(() => {+ expect(cleanupFailures.splice(0)).toEqual([]);+});test.afterEach(() => {for (const dir of owned.splice(0)) {rmSync(dir, { recursive: true, force: true });@@ -29,6 +33,12 @@ test.afterEach(() => {}});+function closeOrRecord(proc: Parameters<typeof closeAppBounded>[0]): Promise<void> {+ return closeAppBounded(proc).catch((error: unknown) => {+ cleanupFailures.push(error instanceof Error ? error.message : String(error));+ });+}+test.describe('isolated uninstall completion', () => {test.skip(!DARWIN, 'macOS uninstall handoff');test.skip(!TARGET.exists, TARGET.missingReason);@@ -50,7 +60,7 @@ test.describe('isolated uninstall completion', () => {env: { ...process.env, HOME: home },}),);- const child = app.process();+ const child = captureAppProcess(app);try {const page = await app.firstWindow();await expect(@@ -68,7 +78,7 @@ test.describe('isolated uninstall completion', () => {expect(await exited).toEqual([0, null]);expect(existsSync(join(home, '.ok'))).toBe(false);} finally {- await closeAppBounded(child);+ await closeOrRecord(child);}});}@@ -83,7 +93,7 @@ test.describe('isolated uninstall completion', () => {env: { ...process.env, HOME: home, OK_UNINSTALL_UI_PREVIEW: 'notice' },}),);- const child = app.process();+ const child = captureAppProcess(app);try {await expect(async () => {const headings = await Promise.all(@@ -92,7 +102,7 @@ test.describe('isolated uninstall completion', () => {expect(headings.flat()).toContain('Uninstall OpenKnowledge?');}).toPass({ timeout: 20_000 });} finally {- await closeAppBounded(child);+ await closeOrRecord(child);}});for (const [success, action, exitCode] of [@@ -123,7 +133,7 @@ test.describe('isolated uninstall completion', () => {env: { ...process.env, HOME: home },}),);- const child = app.process();+ const child = captureAppProcess(app);try {const page = await app.firstWindow();await expect(page.getByRole('alertdialog')).toBeVisible();@@ -157,7 +167,7 @@ test.describe('isolated uninstall completion', () => {);expect(readFileSync(note, 'utf8')).toBe('# Keep my notes');} finally {- await closeAppBounded(child);+ await closeOrRecord(child);}});}@@ -307,8 +317,8 @@ ${success ? `rm '${state}'` : 'exit 31'}helper.kill('SIGTERM');await closed;}- await closeAppBounded(parent);- await closeAppBounded(helper);+ await closeOrRecord(parent);+ await closeOrRecord(helper);await browser?.close().catch(() => {});}});diff --git a/packages/desktop/tests/unit/electron-cleanup-bounded.test.ts b/packages/desktop/tests/unit/electron-cleanup-bounded.test.tsindex 528ee8f6f..17c206358 100644--- a/packages/desktop/tests/unit/electron-cleanup-bounded.test.ts+++ b/packages/desktop/tests/unit/electron-cleanup-bounded.test.ts@@ -1,8 +1,27 @@-import type { ChildProcess } from 'node:child_process';+import { type ChildProcess, spawn } from 'node:child_process';import { EventEmitter } from 'node:events';import type { ElectronApplication } from '@playwright/test';-import { describe, expect, test } from 'vitest';-import { captureAppProcess, closeAppBounded } from '../smoke/_helpers/electron-cleanup';+import { beforeEach, describe, expect, test, vi } from 'vitest';+import {+ AppCleanupIncompleteError,+ captureAppProcess,+ closeAppBounded,+ taskkillTree,+} from '../smoke/_helpers/electron-cleanup';+import { reapedTaskkill } from '../smoke/_helpers/electron-cleanup.test-helper';++vi.mock('node:child_process', async (importOriginal) => ({+ ...(await importOriginal<typeof import('node:child_process')>()),+ spawn: vi.fn(),+}));++const spawnMock = vi.mocked(spawn);++beforeEach(() => {+ spawnMock.mockReset();+});++const REAP_MS = 20;interface MockProc extends EventEmitter {pid: number | undefined;@@ -10,7 +29,10 @@ interface MockProc extends EventEmitter {exitCode: number | null;signalCode: NodeJS.Signals | null;killCalls: { pid: number; signal: NodeJS.Signals | string }[];+ stdio: ({ destroyed: boolean } | null | undefined)[];fireExit: (code?: number) => void;+ fireExitWithoutClose: (code?: number) => void;+ fireClose: () => void;}function makeProc(pid: number | undefined = 12345): MockProc {@@ -20,11 +42,26 @@ function makeProc(pid: number | undefined = 12345): MockProc {ee.exitCode = null;ee.signalCode = null;ee.killCalls = [];- ee.fireExit = (code = 0) => {+ ee.stdio = [];+ ee.fireExitWithoutClose = (code = 0) => {if (ee.exitCode !== null || ee.signalCode !== null) return;ee.exitCode = code;ee.emit('exit', code, null);};+ ee.fireClose = () => {+ if (ee.exitCode === null && ee.signalCode === null) {+ throw new Error('fireClose before exit: a ChildProcess never emits close ahead of exit');+ }+ if (ee.stdio.some((slot) => slot !== null && slot !== undefined && !slot.destroyed)) {+ throw new Error('fireClose with stdio still open: close follows every stdio slot closing');+ }+ ee.emit('close', ee.exitCode, ee.signalCode);+ };+ ee.fireExit = (code = 0) => {+ if (ee.exitCode !== null || ee.signalCode !== null) return;+ ee.fireExitWithoutClose(code);+ ee.fireClose();+ };return ee;}@@ -34,6 +71,7 @@ function mockKill(proc: MockProc) {proc.killed = true;proc.signalCode = signal as NodeJS.Signals;proc.emit('exit', null, signal);+ proc.emit('close', null, signal);};}@@ -105,14 +143,20 @@ describe('closeAppBounded — bounded-time process-group reap', () => {const kill = mockKill(proc);const taskkillPids: number[] = [];- await closeAppBounded(proc as unknown as ChildProcess, {- gracefulMs: 200,- kill,- taskkill: (pid) => taskkillPids.push(pid),- platform: 'win32',- });-- expect(taskkillPids).toEqual([23456]);+ await expect(+ closeAppBounded(proc as unknown as ChildProcess, {+ gracefulMs: 200,+ postKillReapMs: REAP_MS,+ kill,+ taskkill: async (pid) => {+ taskkillPids.push(pid);+ return reapedTaskkill(pid);+ },+ platform: 'win32',+ }),+ ).rejects.toBeInstanceOf(AppCleanupIncompleteError);++ expect(taskkillPids).toEqual([23456, 23456]);expect(proc.killCalls).toEqual([]);});@@ -122,8 +166,9 @@ describe('closeAppBounded — bounded-time process-group reap', () => {const pending = closeAppBounded(proc as unknown as ChildProcess, {gracefulMs: 1_000,- taskkill: () => {+ taskkill: async (pid) => {setTimeout(() => proc.fireExit(0), 150);+ return reapedTaskkill(pid);},platform: 'win32',}).then(() => {@@ -146,7 +191,10 @@ describe('closeAppBounded — bounded-time process-group reap', () => {await closeAppBounded(proc as unknown as ChildProcess, {gracefulMs: 5_000,kill: mockKill(proc),- taskkill: (pid) => taskkillPids.push(pid),+ taskkill: async (pid) => {+ taskkillPids.push(pid);+ return reapedTaskkill(pid);+ },platform: 'win32',});@@ -168,18 +216,27 @@ describe('closeAppBounded — bounded-time process-group reap', () => {expect(proc.killCalls).toEqual([]);});- test('already-killed process → no kill (idempotent on killed)', async () => {+ test('a signal was sent but nothing exited → `killed` is not closure, so the group kill still fires', async () => {const proc = makeProc(22222);proc.killed = true;- const kill = mockKill(proc);-- await closeAppBounded(proc as unknown as ChildProcess, {- gracefulMs: 5_000,- kill,- platform: 'linux',- });+ const killCalls: MockProc['killCalls'] = [];+ const noopKill = (pid: number, signal: NodeJS.Signals | string) => {+ killCalls.push({ pid, signal });+ };- expect(proc.killCalls).toEqual([]);+ await expect(+ closeAppBounded(proc as unknown as ChildProcess, {+ gracefulMs: 100,+ postKillReapMs: REAP_MS,+ kill: noopKill,+ platform: 'linux',+ }),+ ).rejects.toBeInstanceOf(AppCleanupIncompleteError);++ expect(killCalls).toEqual([+ { pid: -22222, signal: 'SIGKILL' },+ { pid: -22222, signal: 'SIGKILL' },+ ]);});test('process killed by external signal → no kill (idempotent on signalCode-set)', async () => {@@ -196,24 +253,26 @@ describe('closeAppBounded — bounded-time process-group reap', () => {expect(proc.killCalls).toEqual([]);});- test('missing pid → graceful wait only, no kill attempted (defensive)', async () => {+ test('missing pid → no kill lever exists, so closure is reported as unestablished', async () => {const proc = makeProc();proc.pid = undefined;const kill = mockKill(proc);- const start = Date.now();- await closeAppBounded(proc as unknown as ChildProcess, {+ const rejection = await closeAppBounded(proc as unknown as ChildProcess, {gracefulMs: 100,+ postKillReapMs: REAP_MS,kill,platform: 'linux',- });- const elapsed = Date.now() - start;+ }).catch((error: unknown) => error);- expect(elapsed).toBeLessThan(2_000);+ expect(rejection).toBeInstanceOf(AppCleanupIncompleteError);+ expect((rejection as AppCleanupIncompleteError).attempts.map((a) => a.lever)).toEqual([+ 'no-pid',+ ]);expect(proc.killCalls).toEqual([]);});- test('kill-fn throws ESRCH (kill→already-dead race) → catch swallows, resolves cleanly', async () => {+ test('kill-fn throws ESRCH → the throw is recorded in the report, never propagated raw', async () => {const proc = makeProc(99999);let killAttempts = 0;const throwingKill = (_pid: number, _signal: NodeJS.Signals | string) => {@@ -221,13 +280,45 @@ describe('closeAppBounded — bounded-time process-group reap', () => {throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' });};- await closeAppBounded(proc as unknown as ChildProcess, {+ const rejection = await closeAppBounded(proc as unknown as ChildProcess, {gracefulMs: 100,+ postKillReapMs: REAP_MS,kill: throwingKill,platform: 'linux',- });+ }).catch((error: unknown) => error);++ expect(rejection).toBeInstanceOf(AppCleanupIncompleteError);+ const thrown = (rejection as AppCleanupIncompleteError).attempts.map((attempt) =>+ attempt.lever === 'group-kill' && attempt.thrown instanceof Error+ ? attempt.thrown.message+ : attempt.lever,+ );+ expect(thrown).toEqual(['kill ESRCH', 'kill ESRCH']);+ expect(killAttempts).toBe(2);+ });- expect(killAttempts).toBeGreaterThanOrEqual(1);+ test('a repeat call after failed close rethrows cached failure, then real close wins', async () => {+ const proc = makeProc(66666);+ const killCalls: MockProc['killCalls'] = [];+ const kill = (pid: number, signal: NodeJS.Signals | string) => {+ killCalls.push({ pid, signal });+ };+ const opts = { gracefulMs: 50, postKillReapMs: REAP_MS, kill, platform: 'linux' as const };++ const first = await closeAppBounded(proc as unknown as ChildProcess, opts).catch(+ (error: unknown) => error,+ );+ expect(first).toBeInstanceOf(AppCleanupIncompleteError);+ const killsAfterFirst = killCalls.length;++ const second = await closeAppBounded(proc as unknown as ChildProcess, opts).catch(+ (error: unknown) => error,+ );+ expect(second).toBe(first);+ expect(killCalls.length).toBe(killsAfterFirst);++ proc.fireExit(0);+ await expect(closeAppBounded(proc as unknown as ChildProcess, opts)).resolves.toBeUndefined();});test('idempotency — second call after kill is a no-op', async () => {@@ -251,6 +342,60 @@ describe('closeAppBounded — bounded-time process-group reap', () => {expect(proc.killCalls.length).toBe(killCountAfterFirst);});+ test('exited at first sight with stdio a descendant still holds is not closure', async () => {+ const proc = makeProc(55555);+ proc.exitCode = 0;+ proc.stdio = [{ destroyed: false }, { destroyed: false }, { destroyed: false }];+ const kill = mockKill(proc);+ let resolved = false;++ const pending = closeAppBounded(proc as unknown as ChildProcess, {+ gracefulMs: 5_000,+ kill,+ platform: 'linux',+ }).then(() => {+ resolved = true;+ });++ await new Promise((r) => setTimeout(r, 50));++ expect(resolved).toBe(false);+ expect(proc.killCalls).toEqual([]);++ for (const slot of proc.stdio) {+ if (slot !== null && slot !== undefined) slot.destroyed = true;+ }+ proc.fireClose();+ await pending;++ expect(resolved).toBe(true);+ });++ test("'exit' without 'close' leaves the call pending — an exited process whose stdio flags already read shut is not closure", async () => {+ const proc = makeProc(77777);+ const kill = mockKill(proc);+ let resolved = false;++ const pending = closeAppBounded(proc as unknown as ChildProcess, {+ gracefulMs: 5_000,+ kill,+ platform: 'linux',+ }).then(() => {+ resolved = true;+ });++ proc.fireExitWithoutClose(0);+ await new Promise((r) => setTimeout(r, 50));++ expect(resolved).toBe(false);+ expect(proc.killCalls).toEqual([]);++ proc.fireClose();+ await pending;++ expect(resolved).toBe(true);+ });+test('null proc → no-op (safe to call when capture failed before assignment)', async () => {await closeAppBounded(null, { gracefulMs: 5_000 });expect(true).toBe(true);@@ -271,3 +416,74 @@ describe('closeAppBounded — bounded-time process-group reap', () => {expect(proc.killCalls).toEqual([]);});});++interface FakeTaskkillChild extends EventEmitter {+ stdout: EventEmitter;+ stderr: EventEmitter;+ kill: (signal?: NodeJS.Signals) => boolean;+ killSignals: (NodeJS.Signals | undefined)[];+}++function fakeTaskkillChild(): FakeTaskkillChild {+ const child = new EventEmitter() as FakeTaskkillChild;+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.killSignals = [];+ child.kill = (signal) => {+ child.killSignals.push(signal);+ return true;+ };+ return child;+}++describe('taskkillTree — the shipped win32 lever', () => {+ test('spawns the tree-kill with the pinned argv and reports what Windows said', async () => {+ const child = fakeTaskkillChild();+ vi.mocked(spawn).mockReturnValue(child as unknown as ReturnType<typeof spawn>);++ const outcome = taskkillTree(23456);+ child.stdout.emit('data', Buffer.from('SUCCESS: terminated.\r\n', 'utf8'));+ child.stderr.emit('data', Buffer.from('', 'utf8'));+ child.emit('close', 0, null);++ await expect(outcome).resolves.toEqual({+ status: 0,+ signal: null,+ stdout: 'SUCCESS: terminated.\r\n',+ stderr: '',+ timedOut: false,+ });+ expect(vi.mocked(spawn)).toHaveBeenCalledWith('taskkill', ['/pid', '23456', '/T', '/F'], {+ windowsHide: true,+ });+ });++ test('a taskkill that never exits is abandoned on its own timeout rather than blocking cleanup', async () => {+ vi.useFakeTimers();+ try {+ const child = fakeTaskkillChild();+ vi.mocked(spawn).mockReturnValue(child as unknown as ReturnType<typeof spawn>);++ const outcome = taskkillTree(23456);+ await vi.advanceTimersByTimeAsync(5_000);++ await expect(outcome).resolves.toMatchObject({ timedOut: true, status: null });+ expect(child.killSignals).toEqual(['SIGKILL']);+ } finally {+ vi.useRealTimers();+ }+ });++ test('a taskkill that cannot be spawned reports the error instead of throwing', async () => {+ const child = fakeTaskkillChild();+ vi.mocked(spawn).mockReturnValue(child as unknown as ReturnType<typeof spawn>);++ const outcome = taskkillTree(23456);+ child.emit('error', new Error('spawn taskkill ENOENT'));++ await expect(outcome).resolves.toMatchObject({+ timedOut: false,+ error: expect.objectContaining({ message: 'spawn taskkill ENOENT' }),+ });+ });+});