Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): detach interactive test shells from the session terminal (#4553)

Nick Gomez3d7a8daf7e42
diff --git a/.changeset/probes-spawn-detached-from-the-session.md b/.changeset/probes-spawn-detached-from-the-session.md
new file mode 100644
index 000000000..e021e7c81
--- /dev/null
+++ b/.changeset/probes-spawn-detached-from-the-session.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-desktop": patch
+---
+
+CLI presence checks no longer let an interactive shell probe freeze the app or take over the terminal. Windows probe placement is unchanged.
diff --git a/lint-plugins/no-comments/README.md b/lint-plugins/no-comments/README.md
index 732d4b599..64a284440 100644
--- a/lint-plugins/no-comments/README.md
+++ b/lint-plugins/no-comments/README.md
@@ -66,8 +66,19 @@ a path no unit claims exits 0 with an `out-of-scope:` line rather than a silent
config alone decides membership and the glob cannot drift from it. That block is this repository's;
the public tree's own root block carries no such route. Every staged path reaches the
sweep; one no unit claims prints `out-of-scope: <path> (no unit claims it; nothing was read)` and
-exits 0. That is how shell gets judged at commit, since the oxc language server hosts no shell
-grammar — and it puts a suppression-blind second read on the JS families too.
+exits 0. An in-scope operand the tree no longer has prints
+`not-on-disk: <path> (absent from the tree; nothing to scan)` and exits 0 the same way. A deleted path
+reaching the sweep as an operand is what first crashed it, and both in-repo producers now filter
+their own lists — the round gate builds its operands from `existsSync` and lint-staged passes an
+`ACMR`-filtered list — so the tolerance stands as the CLI's own contract for any caller, in this
+repository or outside it, that names a path between its own listing and this read. The
+tolerance keys on stat's `ENOENT` alone, and only on the paths the invocation named: an existence
+probe cannot tell a missing file from an unreadable one, so any other stat failure refuses the run
+as a 2 rather than reporting a corpus it did not read. Discovery-sourced paths get no tolerance at
+all — `discoverInScopeFiles` already refuses a tree whose in-scope entries it could not read, and
+a path the config declares that the tree lacks is reported on its own `declared-absent:` line.
+That is how shell gets judged at commit, since the oxc language server hosts no shell grammar —
+and it puts a suppression-blind second read on the JS families too.
`--help` prints the accepted grammar and exits 0; any other token the parser does not claim is
refused rather than dropped. The three exit codes are the same contract the codemod's are, so one
@@ -75,9 +86,9 @@ caller can branch on both:
| code | meaning |
| --- | --- |
-| 0 | the sweep ran and found no violation. In `--file` mode a path no unit claims lands here too, named on an `out-of-scope:` line |
+| 0 | the sweep ran and found no violation. In `--file` mode a path no unit claims lands here too, named on an `out-of-scope:` line; an in-scope path the invocation names that the tree lacks lands here on a `not-on-disk:` line |
| 1 | the corpus is dirty: a violation was reported, or a declared unit that the config requires to be non-empty discovered no file. `--all` lists every violation rather than the first 25 |
-| 2 | the invocation was refused before any work: an unrecognized or repeated argument, a value-taking flag with no path, a `--file` outside `--root`, a scope config that does not load, or a precedent registry that does not load, printed as `precedent-registry: UNREADABLE` with the manifest key or the PRECEDENTS.md numbering problem behind it. Same meaning as the codemod's 2 |
+| 2 | the invocation was refused before any work, or the run could not complete: an unrecognized or repeated argument, a value-taking flag with no path, a `--file` outside `--root`, a scope config that does not load, or a precedent registry that does not load, printed as `precedent-registry: UNREADABLE` with the manifest key or the PRECEDENTS.md numbering problem behind it. A failure while reading the corpus lands here too, printed as `::error::no-comments-sweep aborted<at>: <detail>` with the stack after it — nothing was judged, so the run is not evidence of a clean corpus. A failure that carries a path names it, repo-relative like every other path this tool prints (`aborted at <path>: <errno message>`) — that is every stat or read the scan loop propagates, `ENOENT` included, since the only `ENOENT` tolerance is the `--file` stat, whose misses leave by the `not-on-disk:` line under 0. A whole-tree run discovery refuses has no one path to blame and carries discovery's own aggregate instead: `aborted: discovery could not read <n> in-scope entry: <path> (<reason>). <remedy>`, where the noun tracks `<n>` (`entries` past one), the skip list previews the first five and marks the rest with a trailing `, …`, and `<remedy>` is a fixed sentence naming `discoverInScopeFilesWithSkips` that always follows the list. Same meaning as the codemod's 2 |
`scripts/no-comments-sweep.mjs` is upstream-only: `scripts/` is enumerated in the mirror manifest
rather than globbed, and the sweep is not one of the entries, so it does not ship to the public
diff --git a/lint-plugins/no-comments/scope.mjs b/lint-plugins/no-comments/scope.mjs
index daefde4be..36ec0c503 100644
--- a/lint-plugins/no-comments/scope.mjs
+++ b/lint-plugins/no-comments/scope.mjs
@@ -359,8 +359,8 @@ function requireWalker({ readdirSync, statSync, lstatSync }) {
export function discoverInScopeFilesWithSkips(repoRoot, options) {
requireWalker(options);
- const { readdirSync, statSync, lstatSync } = options;
- const scope = scopeForRoot(repoRoot);
+ const { readdirSync, statSync, lstatSync, scope: providedScope } = options;
+ const scope = providedScope ?? scopeForRoot(repoRoot);
const { isInScope: inScope, pruneDirectories } = scope;
const found = new Set();
const skips = [];
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index 4a545c808..d827cd27a 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -1,8 +1,17 @@
+import type { SpawnSyncOptionsWithStringEncoding } from 'node:child_process';
import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:child_process')>();
+ return { ...actual, spawnSync: vi.fn(actual.spawnSync) };
+});
+
+const spawnSyncMock = vi.mocked(spawnSync);
+
import { MCP_SERVER_NAME } from '../constants/mcp.ts';
import {
buildClaudeLaunchCommand,
@@ -296,6 +305,43 @@ function findNulMapfileBash(): string {
const NUL_MAPFILE_BASH = findNulMapfileBash();
+type DetachedSpawnSyncOptions = SpawnSyncOptionsWithStringEncoding & { detached: true };
+
+const REAL_BASH_PROBE_SPAWN_OPTIONS: DetachedSpawnSyncOptions = {
+ detached: true,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 20_000,
+ killSignal: 'SIGKILL',
+ encoding: 'utf8',
+};
+
+describe('real-bash probe spawn isolation', () => {
+ it('spawns the interactive bash detached from the session controlling terminal (undetached, an interactive bash under a tty acquires the ctty from a background process group and stops the whole vitest task group)', () => {
+ expect(
+ REAL_BASH_PROBE_SPAWN_OPTIONS.detached,
+ 'the real-bash probe must spawn with detached: true; without it an interactive bash (--login -i) acquires the session controlling terminal from a background process group and stops the entire vitest task group',
+ ).toBe(true);
+ });
+
+ it('keeps stdin off the terminal so the spawned shell never reads the session tty', () => {
+ expect(REAL_BASH_PROBE_SPAWN_OPTIONS.stdio?.[0]).toBe('ignore');
+ });
+
+ it('bounds the probe spawn at 20s (vitest testTimeout cannot preempt a worker blocked inside spawnSync, so the bound must live on the spawn options)', () => {
+ expect(
+ REAL_BASH_PROBE_SPAWN_OPTIONS.timeout,
+ 'the real-bash probe must carry a spawn-level timeout; a probe that wedges would otherwise block the worker inside spawnSync with no bound, because vitest testTimeout runs on the blocked worker and cannot preempt the synchronous call',
+ ).toBe(20_000);
+ });
+
+ it('kills the wedged probe rather than signaling it (interactive bash ignores SIGTERM and spawnSync escalates nothing)', () => {
+ expect(
+ REAL_BASH_PROBE_SPAWN_OPTIONS.killSignal,
+ 'the timeout bound must terminate the shell: spawnSync sends exactly one killSignal with no escalation and interactive bash ignores SIGTERM, so the default signal lets a wedged interactive bash --login -i outlive the bound and block the worker unbounded',
+ ).toBe('SIGKILL');
+ });
+});
+
describe('Git Bash structured launch, run by a real Bash', () => {
it.skipIf(NUL_MAPFILE_BASH === '')(
'reconstructs every launch token byte-for-byte, empty argument and trailing newline included',
@@ -303,11 +349,14 @@ describe('Git Bash structured launch, run by a real Bash', () => {
const dir = mkdtempSync(join(tmpdir(), 'ok-git-bash-launch-'));
try {
const capturedArgvPath = join(dir, 'argv');
+ const capturedShellStatPath = join(dir, 'shell-stat');
const capturePath = join(dir, 'capture.cjs');
writeFileSync(
capturePath,
- "const { writeFileSync } = require('node:fs');\n" +
- "writeFileSync(process.env.OK_CAPTURED_ARGV, [process.argv0, ...process.argv.slice(1)].join('\\0') + '\\0');\n",
+ "const { execFileSync } = require('node:child_process');\n" +
+ "const { writeFileSync } = require('node:fs');\n" +
+ "writeFileSync(process.env.OK_CAPTURED_ARGV, [process.argv0, ...process.argv.slice(1)].join('\\0') + '\\0');\n" +
+ "if (process.platform !== 'win32') writeFileSync(process.env.OK_CAPTURED_SHELL_STAT, execFileSync('ps', ['-o', 'stat=', '-p', String(process.ppid)], { encoding: 'utf8' }));\n",
);
const launchTokens = [
@@ -326,11 +375,29 @@ describe('Git Bash structured launch, run by a real Bash', () => {
if (!Array.isArray(composed)) throw new Error('expected Git Bash argv');
const run = spawnSync(NUL_MAPFILE_BASH, composed, {
- env: { ...process.env, HOME: dir, OK_CAPTURED_ARGV: capturedArgvPath },
- stdio: ['ignore', 'pipe', 'pipe'],
- timeout: 20_000,
- encoding: 'utf8',
+ ...REAL_BASH_PROBE_SPAWN_OPTIONS,
+ env: {
+ ...process.env,
+ HOME: dir,
+ OK_CAPTURED_ARGV: capturedArgvPath,
+ OK_CAPTURED_SHELL_STAT: capturedShellStatPath,
+ },
});
+ const recordedOptions = spawnSyncMock.mock.calls.find(
+ ([, recordedArgs]) => recordedArgs?.[0] === '--login',
+ )?.[2] as Partial<typeof REAL_BASH_PROBE_SPAWN_OPTIONS> | undefined;
+ expect(
+ recordedOptions,
+ 'the behavioral probe must route through the spawnSync recorder; its options are asserted from the recorded call so an inline-args edit at this call site cannot bypass the pins',
+ ).toBeDefined();
+ expect(
+ recordedOptions?.detached,
+ 'the recorded behavioral call must spawn detached: true; without it an interactive bash acquires the session controlling terminal from a background process group and stops the whole vitest task group',
+ ).toBe(true);
+ expect(recordedOptions?.stdio?.[0]).toBe('ignore');
+ expect(recordedOptions?.timeout).toBe(20_000);
+ expect(recordedOptions?.killSignal).toBe('SIGKILL');
+ expect(recordedOptions?.encoding).toBe('utf8');
expect(run.error).toBeUndefined();
expect(existsSync(capturedArgvPath), `bash stderr: ${run.stderr}`).toBe(true);
@@ -338,6 +405,13 @@ describe('Git Bash structured launch, run by a real Bash', () => {
...launchTokens,
'',
]);
+
+ if (process.platform !== 'win32') {
+ expect(
+ readFileSync(capturedShellStatPath, 'utf8'),
+ 'the spawned shell must be a session leader (detached: true makes libuv setsid the child into a new session); a forked child carries the s stat flag only when detached, so an undetached spawn reacquires the session controlling terminal from a background process group and stops the whole vitest task group',
+ ).toContain('s');
+ }
} finally {
rmSync(dir, { recursive: true, force: true });
}
diff --git a/packages/desktop/src/main/probe-spawn.test.ts b/packages/desktop/src/main/probe-spawn.test.ts
index 806b41d3d..6d89ce130 100644
--- a/packages/desktop/src/main/probe-spawn.test.ts
+++ b/packages/desktop/src/main/probe-spawn.test.ts
@@ -1,3 +1,5 @@
+import type { ChildProcess, SpawnOptions } from 'node:child_process';
+import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { rmSync } from 'node:fs';
import { homedir } from 'node:os';
@@ -15,10 +17,22 @@ import {
okProbeSpawnEnv,
probeEnvVerdict,
probeSpawnArgs,
+ probeSpawnDetached,
realProbeSpawn,
realProbeTimers,
} from './probe-spawn.ts';
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:child_process')>();
+ return { ...actual, spawn: vi.fn(actual.spawn) };
+});
+
+const spawnMock = vi.mocked(spawn);
+
+function spawnCallOptions(call = 0): SpawnOptions | undefined {
+ return spawnMock.mock.calls[call]?.[2] as SpawnOptions | undefined;
+}
+
vi.mock('node:os', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:os')>();
return { ...actual, homedir: vi.fn(actual.homedir) };
@@ -130,6 +144,206 @@ describe('probeSpawnArgs', () => {
);
});
+describe('probeSpawnDetached', () => {
+ test('detaches the probe child on POSIX and leaves win32 spawn placement unchanged', () => {
+ expect(
+ probeSpawnDetached('linux'),
+ 'the production probe adapter must spawn detached on POSIX: the release note guarantees an interactive shell probe can no longer stop the app from a background process group of a controlling terminal, and an undetached interactive shell acquires that session terminal',
+ ).toBe(true);
+ expect(
+ probeSpawnDetached('darwin'),
+ 'the production probe adapter must spawn detached on every POSIX platform, not only Linux',
+ ).toBe(true);
+ expect(
+ probeSpawnDetached('win32'),
+ 'Windows has no POSIX session or controlling-terminal job control to detach from, so the spawn placement stays unchanged there',
+ ).toBe(false);
+ });
+});
+
+describe.skipIf(process.platform === 'win32')('realProbeSpawn site pin', () => {
+ test('passes the pinned placement options to spawn at the spawn site (the runtime pins above cover the guard behavior; this pin covers the spawn site itself)', () => {
+ spawnMock.mockClear();
+ const child = realProbeSpawn('/bin/sh', ['--version']);
+ try {
+ expect(
+ spawnMock.mock.calls.length,
+ 'the site pin must observe the adapter real spawn call; zero calls means the passthrough record broke',
+ ).toBe(1);
+ const options = spawnCallOptions();
+ expect(
+ options?.detached,
+ 'the probe adapter spawn site must pass detached from the pinned guard: the release note guarantees CLI-presence probes can no longer stop the app or seize the controlling terminal on POSIX, and only the options this site actually passes reach that guarantee, so deleting or falsifying the option here ships every other pin green',
+ ).toBe(true);
+ expect(
+ options?.stdio,
+ 'the probe child reads nothing, so its stdio stays off every pipe and terminal',
+ ).toBe('ignore');
+ expect(
+ options?.shell,
+ 'the probe argv is composed upstream, so the site must not layer a shell over it',
+ ).toBe(false);
+ expect(
+ options?.windowsHide,
+ 'a console-less parent must not flash a terminal window for the probe child',
+ ).toBe(true);
+ } finally {
+ child.kill();
+ }
+ });
+});
+
+function onlySpawnedProbe(): { spawned: ChildProcess; pid: number } {
+ const results = spawnMock.mock.results;
+ if (results.length !== 1) {
+ throw new Error(
+ 'the probe kill pins bind to the single spawn the caller just made, so the caller must clear ' +
+ `the spawn mock immediately before it; saw ${results.length} recorded spawns`,
+ );
+ }
+ const spawned: ChildProcess | undefined = results.at(-1)?.value;
+ const pid = spawned?.pid;
+ if (!spawned || pid === undefined) throw new Error('probe child did not spawn with a pid');
+ return { spawned, pid };
+}
+
+describe.skipIf(process.platform === 'win32')('realProbeSpawn detached group kill', () => {
+ test('signals the detached probe process group with SIGKILL while the probe is still alive', async () => {
+ const groupKill = vi.spyOn(process, 'kill');
+ spawnMock.mockClear();
+ probeLog.warn.mockClear();
+ const child = realProbeSpawn('/bin/sh', ['-c', 'sleep 5']);
+ try {
+ const { pid } = onlySpawnedProbe();
+ const exited = new Promise<void>((resolve) => child.onExit(() => resolve()));
+ child.kill();
+ await exited;
+ expect(groupKill).toHaveBeenCalledTimes(1);
+ expect(
+ groupKill,
+ 'the detached probe must be terminated through its process group: the leader alone can exec past the pid that spawned it, so a bare-pid kill strands the group the app promised not to leak',
+ ).toHaveBeenCalledWith(-pid, 'SIGKILL');
+ expect(probeLog.warn).not.toHaveBeenCalled();
+ } finally {
+ groupKill.mockRestore();
+ child.kill();
+ }
+ });
+
+ test('treats an already-exited probe group as a benign ESRCH no-op without a failure record or a bare-pid retry', async () => {
+ spawnMock.mockClear();
+ probeLog.warn.mockClear();
+ const child = realProbeSpawn('/bin/sh', ['-c', 'exit 0']);
+ try {
+ const { spawned, pid } = onlySpawnedProbe();
+ const childKill = vi.spyOn(spawned, 'kill');
+ await new Promise<void>((resolve) => child.onExit(() => resolve()));
+ let groupGone = false;
+ try {
+ process.kill(-pid, 'SIGKILL');
+ } catch (err) {
+ groupGone = (err as NodeJS.ErrnoException).code === 'ESRCH';
+ }
+ expect(groupGone, 'precondition: the probe group is really gone before the pin runs').toBe(
+ true,
+ );
+ child.kill();
+ expect(probeLog.warn).not.toHaveBeenCalled();
+ expect(childKill).not.toHaveBeenCalled();
+ } finally {
+ child.kill();
+ }
+ });
+
+ test('records a non-ESRCH group-kill failure without retrying the bare pid', () => {
+ const eperm = new Error('kill EPERM') as NodeJS.ErrnoException;
+ eperm.code = 'EPERM';
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw eperm;
+ });
+ spawnMock.mockClear();
+ probeLog.warn.mockClear();
+ const child = realProbeSpawn('/bin/sh', ['-c', 'exit 0']);
+ try {
+ const { spawned, pid } = onlySpawnedProbe();
+ const childKill = vi.spyOn(spawned, 'kill');
+ child.kill();
+ expect(groupKill).toHaveBeenCalledWith(-pid, 'SIGKILL');
+ expect(childKill).not.toHaveBeenCalled();
+ expect(probeLog.warn).toHaveBeenCalledTimes(1);
+ expect(probeLog.warn.mock.calls[0]?.[0]).toMatchObject({
+ event: 'probe-group-kill-failed',
+ err: eperm,
+ code: 'EPERM',
+ probePid: pid,
+ signal: 'SIGKILL',
+ });
+ expect(probeLog.warn.mock.calls[0]?.[0]).not.toHaveProperty('pid');
+ } finally {
+ groupKill.mockRestore();
+ child.kill();
+ }
+ });
+});
+
+describe('realProbeSpawn win32 spawn-site placement', () => {
+ function withPlatform<T>(platform: NodeJS.Platform, run: () => T): T {
+ const original = process.platform;
+ Object.defineProperty(process, 'platform', { configurable: true, value: platform });
+ try {
+ return run();
+ } finally {
+ Object.defineProperty(process, 'platform', { configurable: true, value: original });
+ }
+ }
+
+ test('keeps the spawn site itself un-detached when the stubbed platform is win32', () => {
+ withPlatform('win32', () => {
+ spawnMock.mockClear();
+ const child = realProbeSpawn('/bin/sh', ['--version']);
+ child.onError(() => {});
+ try {
+ expect(
+ spawnMock.mock.calls.length,
+ 'the win32 site pin must observe the adapter real spawn call; zero calls means the passthrough record broke',
+ ).toBe(1);
+ const options = spawnCallOptions();
+ expect(
+ options?.detached,
+ 'the win32 half of the release note is pinned at the spawn site, not only on the predicate: replacing the site with a literal detached: true would keep the predicate pins green while detaching every Windows probe child',
+ ).toBe(false);
+ expect(
+ options?.windowsHide,
+ 'the win32 spawn placement stays unchanged apart from detach, so the site still passes the console-less no-terminal-flash option',
+ ).toBe(true);
+ } finally {
+ child.kill();
+ }
+ });
+ });
+
+ test('keeps the kill on the child itself and off any process group when the stubbed platform is win32', () => {
+ withPlatform('win32', () => {
+ const groupKill = vi.spyOn(process, 'kill');
+ spawnMock.mockClear();
+ const child = realProbeSpawn('/bin/sh', ['-c', 'sleep 5']);
+ try {
+ const { spawned } = onlySpawnedProbe();
+ const childKill = vi.spyOn(spawned, 'kill');
+ child.kill();
+ expect(
+ childKill,
+ 'the win32 probe has no POSIX job control to detach from, so its termination stays on the child handle the spawn returned',
+ ).toHaveBeenCalledWith('SIGKILL');
+ expect(groupKill).not.toHaveBeenCalled();
+ } finally {
+ groupKill.mockRestore();
+ child.kill();
+ }
+ });
+ });
+});
+
describe.skipIf(process.platform === 'win32')('the production CLI-presence probe adapter', () => {
let scratchHome: string;
let shell: string;
@@ -191,6 +405,25 @@ describe.skipIf(process.platform === 'win32')('the production CLI-presence probe
test('resolves a ~/.ok/bin CLI that the bare app environment cannot reach', async () => {
expect(await probeThroughProductionAdapter(FIXTURE_ONLY_BIN)).toBe(0);
});
+
+ test('terminates a hung probe through the production kill when the probe timer fires', async () => {
+ spawnMock.mockClear();
+ const groupKill = vi.spyOn(process, 'kill');
+ try {
+ const outcome = await runLoginShellProbe(realProbeSpawn, shell, realProbeTimers, 100, [
+ '-c',
+ 'sleep 5',
+ ]);
+ expect(outcome).toBe(null);
+ const { pid } = onlySpawnedProbe();
+ expect(
+ groupKill,
+ 'the probe timeout is the only production caller that kills a live probe, so its termination must reach the process group, not just the leader pid',
+ ).toHaveBeenCalledWith(-pid, 'SIGKILL');
+ } finally {
+ groupKill.mockRestore();
+ }
+ });
});
const WIN_CLI_BIN = 'C:\\Program Files\\Open Knowledge\\resources\\cli\\bin';
diff --git a/packages/desktop/src/main/probe-spawn.ts b/packages/desktop/src/main/probe-spawn.ts
index be17ab4c3..07ec570ad 100644
--- a/packages/desktop/src/main/probe-spawn.ts
+++ b/packages/desktop/src/main/probe-spawn.ts
@@ -1,3 +1,4 @@
+import type { ChildProcess } from 'node:child_process';
import { spawn } from 'node:child_process';
import {
composeOkChildEnv,
@@ -113,6 +114,25 @@ export function probeSpawnArgs(
};
}
+export function probeSpawnDetached(platform: NodeJS.Platform): boolean {
+ return platform !== 'win32';
+}
+
+export function killProbeGroup(child: ChildProcess): void {
+ const probePid = child.pid;
+ if (probePid === undefined) return;
+ try {
+ process.kill(-probePid, 'SIGKILL');
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code === 'ESRCH') return;
+ getLogger('probe-spawn').warn(
+ { event: 'probe-group-kill-failed', err, code, probePid, signal: 'SIGKILL' },
+ 'probe process group kill failed',
+ );
+ }
+}
+
export function realProbeSpawn(file: string, spawnArgs: readonly string[]): ProbeChild {
const options = okChildEnvOptionsFromProcess();
const argv = probeSpawnArgs(file, spawnArgs, options);
@@ -131,6 +151,7 @@ export function realProbeSpawn(file: string, spawnArgs: readonly string[]): Prob
const child = spawn(file, [...argv.args], {
stdio: 'ignore',
shell: false,
+ detached: probeSpawnDetached(options.platform),
windowsHide: true,
env: okProbeSpawnEnv(options, argv),
});
@@ -142,7 +163,12 @@ export function realProbeSpawn(file: string, spawnArgs: readonly string[]): Prob
child.on('error', (err) => cb(err));
},
kill: () => {
- child.kill('SIGKILL');
+ if (child.pid === undefined) return;
+ if (!probeSpawnDetached(options.platform)) {
+ child.kill('SIGKILL');
+ return;
+ }
+ killProbeGroup(child);
},
};
}
diff --git a/packages/desktop/src/shared/terminal-shell.test.ts b/packages/desktop/src/shared/terminal-shell.test.ts
index f9f6c5161..0253bf056 100644
--- a/packages/desktop/src/shared/terminal-shell.test.ts
+++ b/packages/desktop/src/shared/terminal-shell.test.ts
@@ -1,13 +1,148 @@
-import { spawnSync } from 'node:child_process';
+import { type SpawnOptions, spawn, spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { describe, expect, test, vi } from 'vitest';
+import {
+ DETACHED_SPAWN_OPTIONS,
+ INTERACTIVE_SHELL_SPAWN_OPTIONS,
+ spawnDetachedInteractiveChild,
+ spawnInteractiveShellSync,
+} from '../../tests/support/detached-interactive-spawn.test-helper.ts';
import { commandWithManagedPath } from './terminal-shell.ts';
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:child_process')>();
+ return { ...actual, spawn: vi.fn(actual.spawn), spawnSync: vi.fn(actual.spawnSync) };
+});
+
+const spawnMock = vi.mocked(spawn);
+const spawnSyncMock = vi.mocked(spawnSync);
+
+function asyncSpawnCallOptions(call = 0): SpawnOptions | undefined {
+ return spawnMock.mock.calls[call]?.[2] as SpawnOptions | undefined;
+}
+
+function syncSpawnCallOptions(call = 0):
+ | {
+ detached?: boolean;
+ timeout?: number;
+ killSignal?: NodeJS.Signals | number;
+ encoding?: BufferEncoding;
+ }
+ | undefined {
+ return spawnSyncMock.mock.calls[call]?.[2] as
+ | {
+ detached?: boolean;
+ timeout?: number;
+ killSignal?: NodeJS.Signals | number;
+ encoding?: BufferEncoding;
+ }
+ | undefined;
+}
+
const zsh = ['/bin/zsh', '/usr/bin/zsh'].find(existsSync);
const bash = ['/bin/bash', '/usr/bin/bash'].find(existsSync);
+describe('managed-path probe spawn isolation', () => {
+ test('spawns the interactive probes detached from the session controlling terminal (undetached, an interactive shell under a tty acquires the ctty from a background process group and stops the whole vitest task group)', () => {
+ expect(
+ INTERACTIVE_SHELL_SPAWN_OPTIONS.detached,
+ 'the managed-path probes must spawn with detached: true; without it an interactive shell (zsh or bash -i) acquires the session controlling terminal from a background process group and stops the entire vitest task group',
+ ).toBe(true);
+ });
+
+ test('bounds the synchronous probe spawn at 20s (vitest testTimeout cannot preempt a worker blocked inside spawnSync, so the bound must live on the spawn options)', () => {
+ expect(
+ INTERACTIVE_SHELL_SPAWN_OPTIONS.timeout,
+ 'the managed-path probes must carry a spawn-level timeout; a probe that wedges would otherwise block the worker inside spawnSync with no bound, because vitest testTimeout runs on the blocked worker and cannot preempt the synchronous call',
+ ).toBe(20_000);
+ });
+
+ test('kills the wedged probe rather than signaling it (interactive bash ignores SIGTERM and spawnSync escalates nothing)', () => {
+ expect(
+ INTERACTIVE_SHELL_SPAWN_OPTIONS.killSignal,
+ 'the timeout bound must terminate the shell: spawnSync sends exactly one killSignal with no escalation and interactive bash ignores SIGTERM, so the default signal lets a wedged interactive shell outlive the bound and block the worker unbounded',
+ ).toBe('SIGKILL');
+ });
+});
+
+describe('detached async interactive-shell spawn isolation', () => {
+ test('spawns the async interactive-shell children detached from the session controlling terminal (undetached, an interactive shell under a tty acquires the ctty from a background process group and stops the whole vitest task group)', () => {
+ expect(
+ DETACHED_SPAWN_OPTIONS.detached,
+ 'the async interactive-shell spawn helper must place its children in a new session: the bare-env probe adapter and the process-group containment spawns run real interactive shells, and an undetached one acquires the session controlling terminal from a background process group and stops the entire vitest task group',
+ ).toBe(true);
+ });
+});
+
+describe.skipIf(process.platform === 'win32')('detached interactive-shell wrapper site pin', () => {
+ test('spawnDetachedInteractiveChild passes the pinned detachment to spawn at the wrapper body (the tripwires above cover the const values; this pin covers the wrapper body itself)', () => {
+ spawnMock.mockClear();
+ const child = spawnDetachedInteractiveChild(process.execPath, ['-e', 'process.exit(0)']);
+ try {
+ expect(
+ spawnMock.mock.calls.length,
+ 'the site pin must observe the wrapper real spawn call; zero calls means the passthrough record broke',
+ ).toBe(1);
+ const options = asyncSpawnCallOptions();
+ expect(
+ options?.detached,
+ 'the wrapper body must spread the pinned detachment through to spawn: only the options the wrapper actually passes reach the children, so deleting or falsifying the spread here ships the const tripwires green while the probes run undetached and reacquire the session controlling terminal',
+ ).toBe(true);
+ expect(
+ options?.stdio,
+ 'the interactive-shell children read nothing, so their stdio stays off every pipe and terminal',
+ ).toBe('ignore');
+ expect(
+ options?.shell,
+ 'the argv is composed by the callers, so the wrapper must not layer a shell over it',
+ ).toBe(false);
+ expect(
+ options?.windowsHide,
+ 'a console-less parent must not flash a terminal window for the spawned children',
+ ).toBe(true);
+ } finally {
+ child.kill();
+ }
+ });
+
+ test('spawnInteractiveShellSync passes the pinned isolation options to spawnSync at the wrapper body (the tripwires above cover the const values; this pin covers the wrapper body itself)', () => {
+ spawnSyncMock.mockClear();
+ spawnInteractiveShellSync(process.execPath, ['-e', 'process.exit(0)']);
+ expect(
+ spawnSyncMock.mock.calls.length,
+ 'the site pin must observe the wrapper real spawnSync call; zero calls means the passthrough record broke',
+ ).toBe(1);
+ const options = syncSpawnCallOptions();
+ expect(
+ options?.detached,
+ 'the wrapper body must spread the pinned detachment through to spawnSync: only the options the wrapper actually passes reach the probes, so deleting or falsifying the spread here ships the const tripwires green while the probes run undetached and reacquire the session controlling terminal',
+ ).toBe(true);
+ expect(
+ options?.timeout,
+ 'the wrapper must carry the spawn-level timeout through; vitest testTimeout cannot preempt a worker blocked inside spawnSync',
+ ).toBe(20_000);
+ expect(
+ options?.killSignal,
+ 'the bound must terminate the shell: spawnSync escalates nothing and interactive bash ignores SIGTERM, so the pinned signal has to reach spawnSync',
+ ).toBe('SIGKILL');
+ expect(
+ options?.encoding,
+ 'the callers assert on stderr as a string, so utf8 decoding has to be part of the pinned options',
+ ).toBe('utf8');
+ });
+
+ test('spawnInteractiveShellSync forwards a per-call timeoutMs over the pinned default', () => {
+ spawnSyncMock.mockClear();
+ spawnInteractiveShellSync(process.execPath, ['-e', 'process.exit(0)'], undefined, 5_000);
+ expect(
+ syncSpawnCallOptions()?.timeout,
+ 'the ok-bin caller passes 5s to keep its pre-change bound, and nothing else observes that argument reaching spawnSync: dropping or reordering the parameter would otherwise leave every suite green while that caller silently ran on the 20s default',
+ ).toBe(5_000);
+ });
+});
+
describe.skipIf(zsh === undefined)('commandWithManagedPath', () => {
test('keeps startup-defined functions available in the initialized shell', () => {
const zdotdir = mkdtempSync(join(tmpdir(), 'ok-managed-path-zsh-'));
@@ -16,10 +151,11 @@ describe.skipIf(zsh === undefined)('commandWithManagedPath', () => {
const command = commandWithManagedPath(zsh ?? '/bin/zsh', 'slidev deck.md --port 4300', [
'/managed/bin',
]);
- const child = spawnSync(zsh ?? '/bin/zsh', ['-i', '-c', command], {
- env: { ...process.env, ZDOTDIR: zdotdir },
- encoding: 'utf8',
+ const child = spawnInteractiveShellSync(zsh ?? '/bin/zsh', ['-i', '-c', command], {
+ ...process.env,
+ ZDOTDIR: zdotdir,
});
+ expect(child.error).toBeUndefined();
expect(child.status, child.stderr).toBe(42);
} finally {
rmSync(zdotdir, { recursive: true, force: true });
@@ -34,10 +170,11 @@ describe.skipIf(bash === undefined)('commandWithManagedPath in Bash', () => {
writeFileSync(join(home, '.bashrc'), 'slidev() { exit 43; }\n');
const shell = bash ?? '/bin/bash';
const command = commandWithManagedPath(shell, 'slidev deck.md --port 4300', ['/managed/bin']);
- const child = spawnSync(shell, ['-i', '-c', command], {
- env: { ...process.env, HOME: home },
- encoding: 'utf8',
+ const child = spawnInteractiveShellSync(shell, ['-i', '-c', command], {
+ ...process.env,
+ HOME: home,
});
+ expect(child.error).toBeUndefined();
expect(child.status, child.stderr).toBe(43);
} finally {
rmSync(home, { recursive: true, force: true });
diff --git a/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts b/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts
index afd0a0c2a..42600740a 100644
--- a/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts
+++ b/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts
@@ -1,4 +1,4 @@
-import { spawn, spawnSync } from 'node:child_process';
+import { spawnSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import {
chmodSync,
@@ -31,7 +31,7 @@ import {
runLoginShellProbe,
} from '../../src/main/claude-readiness.ts';
import { handleSlidesStatus } from '../../src/main/ipc/slides.ts';
-import { realProbeSpawn, realProbeTimers } from '../../src/main/probe-spawn.ts';
+import { killProbeGroup, realProbeSpawn, realProbeTimers } from '../../src/main/probe-spawn.ts';
import {
buildSlidevInvocation,
composeSlidevSpawnEnv,
@@ -40,6 +40,10 @@ import {
type SlidevProcess,
} from '../../src/main/slidev-server.ts';
import { buildShellEnv } from '../../src/utility/pty-host.ts';
+import {
+ spawnDetachedInteractiveChild,
+ spawnInteractiveShellSync,
+} from '../support/detached-interactive-spawn.test-helper.ts';
import {
createRecordDir,
createScratchHomeWithOkBin,
@@ -70,7 +74,7 @@ const probeTimers: ProbeTimers = {
function bareEnvProbeSpawn(): ProbeSpawn {
return (file, args) => {
- const child = spawn(file, [...args], { stdio: 'ignore', shell: false, windowsHide: true });
+ const child = spawnDetachedInteractiveChild(file, args);
return {
onExit: (cb) => {
child.on('exit', (code) => cb(code));
@@ -79,7 +83,7 @@ function bareEnvProbeSpawn(): ProbeSpawn {
child.on('error', (err) => cb(err));
},
kill: () => {
- child.kill('SIGKILL');
+ killProbeGroup(child);
},
};
};
@@ -294,11 +298,7 @@ function spawnDeck(
args: readonly string[],
env?: NodeJS.ProcessEnv,
) {
- const child = spawn(shell, [...args.slice(0, -1), command], {
- stdio: 'ignore',
- detached: true,
- ...(env ? { env } : {}),
- });
+ const child = spawnDetachedInteractiveChild(shell, [...args.slice(0, -1), command], env);
const shellPid = child.pid ?? 0;
const descendants = () =>
spawnSync('/bin/ps', ['-eo', 'pid,ppid,pgid'], { encoding: 'utf8' })
@@ -522,11 +522,16 @@ describe.skipIf(!existsSync('/bin/bash'))('Slidev bashrc function detect-and-lau
'linux',
[],
);
- const child = spawnSync(invocation.file, [...invocation.args], {
- env: { ...process.env, HOME: home, PATH: MINIMAL_PARENT_PATH },
- encoding: 'utf8',
- timeout: 5_000,
- });
+ const child = spawnInteractiveShellSync(
+ invocation.file,
+ [...invocation.args],
+ {
+ ...process.env,
+ HOME: home,
+ PATH: MINIMAL_PARENT_PATH,
+ },
+ 5_000,
+ );
expect(child.error).toBeUndefined();
expect(child.status, child.stderr).toBe(SENTINEL_EXIT_CODE);
} finally {
diff --git a/packages/desktop/tests/support/detached-interactive-spawn.test-helper.ts b/packages/desktop/tests/support/detached-interactive-spawn.test-helper.ts
new file mode 100644
index 000000000..afdb37b60
--- /dev/null
+++ b/packages/desktop/tests/support/detached-interactive-spawn.test-helper.ts
@@ -0,0 +1,50 @@
+import type {
+ ChildProcess,
+ SpawnOptions,
+ SpawnSyncOptionsWithStringEncoding,
+ SpawnSyncReturns,
+} from 'node:child_process';
+import { spawn, spawnSync } from 'node:child_process';
+
+type DetachedSpawnSyncOptions = SpawnSyncOptionsWithStringEncoding & {
+ detached: true;
+ timeout: number;
+};
+
+export const INTERACTIVE_SHELL_SPAWN_OPTIONS: DetachedSpawnSyncOptions = {
+ detached: true,
+ encoding: 'utf8',
+ timeout: 20_000,
+ killSignal: 'SIGKILL',
+};
+
+type DetachedSpawnOptions = SpawnOptions & { detached: true };
+
+export const DETACHED_SPAWN_OPTIONS: DetachedSpawnOptions = { detached: true };
+
+export function spawnDetachedInteractiveChild(
+ file: string,
+ args: readonly string[],
+ env?: NodeJS.ProcessEnv,
+): ChildProcess {
+ return spawn(file, [...args], {
+ ...DETACHED_SPAWN_OPTIONS,
+ stdio: 'ignore',
+ shell: false,
+ windowsHide: true,
+ env,
+ });
+}
+
+export function spawnInteractiveShellSync(
+ file: string,
+ args: readonly string[],
+ env?: NodeJS.ProcessEnv,
+ timeoutMs: number = INTERACTIVE_SHELL_SPAWN_OPTIONS.timeout,
+): SpawnSyncReturns<string> {
+ return spawnSync(file, [...args], {
+ ...INTERACTIVE_SHELL_SPAWN_OPTIONS,
+ env,
+ timeout: timeoutMs,
+ });
+}