Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: settle CLI capability probes at their deadline even when the child ignores SIGTERM (#10604)

[._.]/ Adam Eivya7c8512e7bf8
diff --git a/server/lib/README.md b/server/lib/README.md
index ea07703c77..3176276e03 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -422,7 +422,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `childProcess.js` | Drop-in `child_process` replacement that defaults every spawn to `windowsHide: true` — `spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` / `execFileSync`, plus a `ChildProcess` re-export. **Server runtime code must import from here, never from `child_process` directly** (enforced by `childProcess.guards.test.js`): a console-less PM2 fork spawning a console child without `CREATE_NO_WINDOW` makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. `exec`/`execFile` carry `util.promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit `windowsHide: false` is respected. Background: `docs/WINDOWS_CONSOLE.md`. |
| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES`, `guardChildStdin(child)` (attach the no-op `stdin` `'error'` listener BEFORE any `stdin.write`/`stdin.end` — a child that dies before reading stdin makes the pipe emit `EPIPE`, and an unlistened stream `'error'` outside the Express request lifecycle takes the whole server process down; call it at every spawn that writes to a child's stdin) + `deliverChildStdin(child, payload, label)` (its other half: write-then-`end()` with a synchronously-throwing `write` caught, the pipe destroyed so a reading child sees EOF rather than hanging, and the failure logged so an empty-prompt run that exits 0 isn't filed as clean), `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (`killGraceMs`, default 8s), Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). A killable that is NOT a `ChildProcess` — a node-pty `IPty` TUI session — is killed through its own `.kill()`, with **no signal on Windows**: node-pty throws `Signals not supported on windows.` for any signal argument, so a signalled kill there killed nothing and threw past the caller. Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. |
| `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. |
-| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. Sibling `commandOutput(cmd, args, opts)` runs the same probe but returns the trimmed stdout (or `null` when it could not run / exited non-zero), so a caller can read a `--version` banner or a `models` listing without spawning the same child twice. |
+| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (spawn-based, with a deadline that settles even when the child ignores termination), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. Sibling `commandOutput(cmd, args, opts)` runs the same probe but returns the trimmed stdout (or `null` when it could not run / exited non-zero), so a caller can read a `--version` banner or a `models` listing without spawning the same child twice. |
| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.
| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so `git reset --hard` / `git commit`, `find -delete` / `-exec`, and `gh`/`glab` writes (`api -X POST`, `pr merge`) are rejected while `git log`, `find -name` and `gh pr list` pass. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. |
| `detachedSpawn.js` | `spawnDatabaseMaintenanceWorker(id, token)` launches only the fixed, one-use fenced offline-transfer worker and retains its supervisor evidence; it grants no ordinary launch bypass. `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. `snapshotProcesses()` (POSIX pid/pgid/start/command table, fails closed on unreadable rows), `signalProcessGroup(pgid, signal)` and `isDetachedSupervisorCommand(command)` back database-maintenance descendant reconciliation; completed POSIX launches retire their registry record once two snapshots prove the launcher group empty. |
diff --git a/server/lib/commandExists.js b/server/lib/commandExists.js
index 671d04f6aa..f69ef7a0ca 100644
--- a/server/lib/commandExists.js
+++ b/server/lib/commandExists.js
@@ -1,17 +1,20 @@
-import { execFile } from './childProcess.js';
-import { promisify } from 'util';
+import { spawn } from './childProcess.js';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-const execFileAsync = promisify(execFile);
+// execFile's own default, kept so a probe that previously failed on a runaway
+// listing still fails the same way.
+const DEFAULT_MAX_BUFFER = 1024 * 1024;
+// POSIX grace between the deadline's SIGTERM and the SIGKILL escalation.
+const PROBE_KILL_GRACE_MS = 2_000;
/**
* Run a bounded capability probe and return its trimmed stdout, or `null` when
* the command could not run or exited non-zero.
*
* The command is routed through `prepareCliSpawn` first. On Windows an
- * npm-installed CLI is a `.cmd` shim, and `execFile`'s default `shell: false`
+ * npm-installed CLI is a `.cmd` shim, and a `shell: false` spawn
* neither applies a PATHEXT search to a bare name (`codex` → `spawn ENOENT`)
* nor will it launch a `.cmd` target at all post-CVE-2024-27980 (`spawn
* EINVAL`). Both failures land in the same `.catch(() => null)` as a genuinely
@@ -22,13 +25,23 @@ const execFileAsync = promisify(execFile);
* explicit-extension path and wraps a batch target as `cmd.exe /c <path>
* <args>`; every branch of it is a no-op off Windows.
*
- * The child's stdin is closed immediately. `agy models` blocks on an open stdin
- * and prints NOTHING until it closes — with execFile's default pipe that is a
- * full timeout's hang ending in SIGTERM and empty output. (execFile ignores an
- * `stdio` option, so ending the stream is the way to do it.) Not every vendor
- * needs it, but it costs one FD close and makes every probe immune. Same
- * reasoning, and the same incident, as `_execCliModelList` in
- * `lib/aiToolkit/providers.js`.
+ * The child's stdin is closed from the start (`'ignore'`). `agy models` blocks
+ * on an open stdin and prints NOTHING until it closes — with an inherited pipe
+ * that is a full timeout's hang ending in SIGTERM and empty output. Not every
+ * vendor needs it, but it makes every probe immune. Same reasoning, and the
+ * same incident, as `_execCliModelList` in `lib/aiToolkit/providers.js`.
+ *
+ * The deadline settles the result ITSELF rather than waiting for the child to
+ * close (#10604). `execFile`'s `timeout` only sends a signal and still resolves
+ * on `close`, so a child that ignored SIGTERM kept the caller — and the scratch
+ * cleanup below — pending indefinitely. On expiry the probe resolves `null`
+ * at once and terminates only the child it spawned: on Windows
+ * `killProcessTree` takes the whole `cmd.exe` shim tree with `taskkill /T`;
+ * on POSIX the child runs in its own process group (`detached`), which gets
+ * SIGTERM and, if the child is still alive after a short grace, SIGKILL.
+ * Output past `maxBuffer` fails the probe the same way. Every event after the
+ * result is fixed — a late `error`, `close` or chunk — is ignored, and a
+ * failure to signal or to clean up never replaces the result.
*
* `TMPDIR`/`TMP`/`TEMP` are pinned to a throwaway directory scoped to THIS one
* probe, mkdtemp'd before the spawn and removed once it settles. Several real
@@ -44,7 +57,7 @@ const execFileAsync = promisify(execFile);
* that already scoped its own `env` still gets its OTHER vars untouched; only
* the three temp-dir keys are overridden on top.
*/
-function probe(cmd, args, { timeoutMs, env, cwd, maxBuffer }) {
+function probe(cmd, args, { timeoutMs, env, cwd, maxBuffer = DEFAULT_MAX_BUFFER }) {
let scratchDir;
try {
scratchDir = mkdtempSync(join(tmpdir(), 'portos-cli-probe-'));
@@ -56,12 +69,6 @@ function probe(cmd, args, { timeoutMs, env, cwd, maxBuffer }) {
return Promise.resolve(null);
}
const probeEnv = { ...(env || process.env), TMPDIR: scratchDir, TMP: scratchDir, TEMP: scratchDir };
- const options = {
- timeout: timeoutMs,
- env: probeEnv,
- ...(cwd === undefined ? {} : { cwd }),
- ...(maxBuffer === undefined ? {} : { maxBuffer }),
- };
const cleanup = () => {
try {
rmSync(scratchDir, { recursive: true, force: true });
@@ -73,25 +80,84 @@ function probe(cmd, args, { timeoutMs, env, cwd, maxBuffer }) {
// `bufferedSpawn.js` is imported lazily, not at module load: this module is
// reached by a very large share of the server suite, and an eager edge into
// that subtree pushed the tree-wide instantiation budget over (see "Import
- // scoping" in server/AGENTS.md). The import also supplies the microtask
- // boundary the `Promise.resolve()` used to — some spawn failures (notably
- // ENOEXEC for a broken text shim on macOS) are thrown synchronously by the
- // child-process wrapper, and this keeps them on the same rejected-promise path
- // as an ordinary failure.
+ // scoping" in server/AGENTS.md). The import also supplies a microtask
+ // boundary — some spawn failures (notably ENOEXEC for a broken text shim on
+ // macOS) are thrown synchronously by the child-process wrapper, and this
+ // keeps them on the same rejected-promise path as an ordinary failure.
return import('./bufferedSpawn.js')
- .then(({ prepareCliSpawn }) => {
- // Resolution reads the env the CHILD will run under, so a caller that
- // overrides PATH probes its own binary, not one off the server's PATH.
- const launch = prepareCliSpawn(cmd, args, probeEnv);
- const pending = execFileAsync(launch.command, launch.args, options);
- pending.child?.stdin?.end();
- return pending;
- })
- .then(({ stdout }) => String(stdout ?? '').trim())
+ .then((lifecycle) => runProbe(lifecycle, cmd, args, probeEnv, { timeoutMs, cwd, maxBuffer }))
.catch(() => null)
.finally(cleanup);
}
+function runProbe({ prepareCliSpawn, killProcessTree, IS_WIN32 }, cmd, args, probeEnv, { timeoutMs, cwd, maxBuffer }) {
+ return new Promise((resolve) => {
+ // Resolution reads the env the CHILD will run under, so a caller that
+ // overrides PATH probes its own binary, not one off the server's PATH.
+ const launch = prepareCliSpawn(cmd, args, probeEnv);
+ const child = spawn(launch.command, launch.args, {
+ env: probeEnv,
+ ...(cwd === undefined ? {} : { cwd }),
+ stdio: ['ignore', 'pipe', 'ignore'],
+ // A POSIX process group is what lets the deadline reach the CLI's own
+ // children; on Windows `detached` would open a console, and taskkill /T
+ // already covers the tree.
+ detached: !IS_WIN32,
+ });
+ const chunks = [];
+ let bytes = 0;
+ let settled = false;
+ let deadline = null;
+
+ const settle = (value) => {
+ if (settled) return;
+ settled = true;
+ if (deadline) clearTimeout(deadline);
+ resolve(value);
+ };
+ const signal = (sig) => {
+ try {
+ killProcessTree(child, sig, { processGroup: !IS_WIN32 });
+ } catch (err) {
+ console.warn(`⚠️ ${cmd} probe could not send ${sig}: ${err?.code || err?.message}`);
+ }
+ };
+ const terminate = () => {
+ signal('SIGTERM');
+ if (IS_WIN32) return; // taskkill /T /F already force-killed the tree
+ const escalation = setTimeout(() => {
+ if (child.exitCode === null && child.signalCode === null) signal('SIGKILL');
+ }, PROBE_KILL_GRACE_MS);
+ escalation.unref?.();
+ };
+
+ child.stdout?.on('data', (chunk) => {
+ if (settled) return;
+ bytes += chunk.length;
+ if (bytes > maxBuffer) {
+ terminate();
+ settle(null);
+ return;
+ }
+ chunks.push(chunk);
+ });
+ // Both listeners stay attached after settling so a late `error` (e.g. a
+ // failed kill) never becomes an unhandled emitter error.
+ child.on('error', () => settle(null));
+ child.on('close', (code) => {
+ settle(code === 0 ? Buffer.concat(chunks).toString('utf8').trim() : null);
+ });
+
+ if (Number.isFinite(timeoutMs) && timeoutMs > 0) {
+ deadline = setTimeout(() => {
+ if (settled) return;
+ terminate();
+ settle(null);
+ }, timeoutMs);
+ }
+ });
+}
+
/**
* Does running `cmd args` succeed without error? A capability probe (not a
* PATH lookup like `whichFirst` in processEnv.js) — it actually invokes the
diff --git a/server/lib/commandExists.test.js b/server/lib/commandExists.test.js
index d501c5d5c1..1649cef08d 100644
--- a/server/lib/commandExists.test.js
+++ b/server/lib/commandExists.test.js
@@ -1,10 +1,51 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { EventEmitter } from 'node:events'
import { existsSync } from 'node:fs'
-const execFileMock = { impl: (_cmd, _args, _opts, cb) => cb(null, { stdout: '', stderr: '' }) }
-vi.mock('./childProcess.js', () => ({
- execFile: (cmd, args, opts, cb) => execFileMock.impl(cmd, args, opts, cb),
-}))
+// A scripted stand-in for a spawned child. It has no `pid`, so killProcessTree
+// takes its `.kill()` path and never signals a real process group.
+const fakeChild = (script) => {
+ const child = new EventEmitter()
+ child.stdout = new EventEmitter()
+ child.exitCode = null
+ child.signalCode = null
+ child.kill = vi.fn()
+ setImmediate(() => script(child))
+ return child
+}
+const exitWith = (stdout, code = 0) => (child) => {
+ if (stdout) child.stdout.emit('data', Buffer.from(stdout))
+ child.exitCode = code
+ child.emit('close', code)
+}
+
+// Scripted by default; `spawnMock.impl = null` reaches the real spawn for the
+// one real-process contract test below.
+const spawnMock = { impl: null, calls: [] }
+vi.mock('./childProcess.js', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ spawn: (cmd, args, opts) => {
+ const call = { cmd, args, opts }
+ spawnMock.calls.push(call)
+ call.child = spawnMock.impl ? spawnMock.impl(cmd, args, opts) : actual.spawn(cmd, args, opts)
+ return call.child
+ },
+ }
+})
+
+const rmMock = { fail: false }
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ rmSync: (...a) => {
+ if (rmMock.fail) throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' })
+ return actual.rmSync(...a)
+ },
+ }
+})
// Real by default (a no-op off Windows); overridden in the shim suite below to
// stand in for what it returns on a real Windows box.
@@ -19,12 +60,15 @@ vi.mock('./bufferedSpawn.js', async (importOriginal) => {
}
})
-const { commandExists } = await import('./commandExists.js')
+const { commandExists, commandOutput } = await import('./commandExists.js')
+const lastSpawn = () => spawnMock.calls.at(-1)
describe('commandExists', () => {
beforeEach(() => {
- execFileMock.impl = (_cmd, _args, _opts, cb) => cb(null, { stdout: '', stderr: '' })
+ spawnMock.impl = () => fakeChild(exitWith(''))
+ spawnMock.calls = []
prepareMock.impl = null
+ rmMock.fail = false
})
it('resolves true when the command exits cleanly', async () => {
@@ -32,72 +76,47 @@ describe('commandExists', () => {
})
it('resolves false when the command errors (e.g. ENOENT)', async () => {
- execFileMock.impl = (_cmd, _args, _opts, cb) => cb(new Error('ENOENT'))
+ spawnMock.impl = () => fakeChild((c) => c.emit('error', Object.assign(new Error('ENOENT'), { code: 'ENOENT' })))
await expect(commandExists('nope', ['--version'])).resolves.toBe(false)
})
it('resolves false when spawning throws synchronously (e.g. ENOEXEC)', async () => {
- execFileMock.impl = () => { throw Object.assign(new Error('ENOEXEC'), { code: 'ENOEXEC' }) }
+ spawnMock.impl = () => { throw Object.assign(new Error('ENOEXEC'), { code: 'ENOEXEC' }) }
await expect(commandExists('broken-shim', ['--version'])).resolves.toBe(false)
})
- it('defaults args to ["--version"] when omitted', async () => {
- let seenArgs = null
- execFileMock.impl = (_cmd, args, _opts, cb) => { seenArgs = args; cb(null, { stdout: '', stderr: '' }) }
- await commandExists('claude')
- expect(seenArgs).toEqual(['--version'])
- })
-
- it('defaults the timeout to 5s when no opts are passed', async () => {
- let seenOpts = null
- execFileMock.impl = (_cmd, _args, opts, cb) => { seenOpts = opts; cb(null, { stdout: '', stderr: '' }) }
+ it('defaults args to ["--version"] and closes the child stdin', async () => {
await commandExists('claude')
- expect(seenOpts.timeout).toBe(5_000)
- })
-
- it('honors a longer timeoutMs for a heavier CLI probe', async () => {
- let seenOpts = null
- execFileMock.impl = (_cmd, _args, opts, cb) => { seenOpts = opts; cb(null, { stdout: '', stderr: '' }) }
- await commandExists('codex', undefined, { timeoutMs: 15_000 })
- expect(seenOpts.timeout).toBe(15_000)
+ expect(lastSpawn().args).toEqual(['--version'])
+ expect(lastSpawn().opts.stdio[0]).toBe('ignore')
})
it('uses the supplied child environment and working directory', async () => {
- let seenOpts = null
- execFileMock.impl = (_cmd, _args, opts, cb) => { seenOpts = opts; cb(null, { stdout: '', stderr: '' }) }
const env = { PATH: '/example/bin' }
await commandExists('opencode', undefined, { env, cwd: '/example/workspace' })
- expect(seenOpts.timeout).toBe(5_000)
- expect(seenOpts.cwd).toBe('/example/workspace')
+ const { opts } = lastSpawn()
+ expect(opts.cwd).toBe('/example/workspace')
// The caller's own vars survive; TMPDIR/TMP/TEMP are pinned to a
// throwaway per-probe scratch dir so a real CLI (kilo, opencode) cannot
// write its own scratch/cache state into the caller's TMPDIR (#9039).
- expect(seenOpts.env.PATH).toBe('/example/bin')
- expect(seenOpts.env.TMPDIR).toBe(seenOpts.env.TMP)
- expect(seenOpts.env.TMPDIR).toBe(seenOpts.env.TEMP)
- expect(seenOpts.env.TMPDIR).toMatch(/portos-cli-probe-/)
+ expect(opts.env.PATH).toBe('/example/bin')
+ expect(opts.env.TMPDIR).toBe(opts.env.TMP)
+ expect(opts.env.TMPDIR).toBe(opts.env.TEMP)
+ expect(opts.env.TMPDIR).toMatch(/portos-cli-probe-/)
})
- it('removes its throwaway scratch dir once the probe settles', async () => {
- let scratchDir = null
- execFileMock.impl = (_cmd, _args, opts, cb) => { scratchDir = opts.env.TMPDIR; cb(null, { stdout: '', stderr: '' }) }
-
+ it('removes its throwaway scratch dir once the probe settles, success or failure', async () => {
await commandExists('claude')
-
- expect(scratchDir).toMatch(/portos-cli-probe-/)
- expect(existsSync(scratchDir)).toBe(false)
- })
-
- it('removes its scratch dir even when the probe fails', async () => {
- let scratchDir = null
- execFileMock.impl = (_cmd, _args, opts, cb) => { scratchDir = opts.env.TMPDIR; cb(new Error('ENOENT')) }
-
+ const okDir = lastSpawn().opts.env.TMPDIR
+ spawnMock.impl = () => fakeChild(exitWith('', 1))
await commandExists('nope')
+ const failDir = lastSpawn().opts.env.TMPDIR
- expect(scratchDir).toMatch(/portos-cli-probe-/)
- expect(existsSync(scratchDir)).toBe(false)
+ expect(okDir).toMatch(/portos-cli-probe-/)
+ expect(existsSync(okDir)).toBe(false)
+ expect(existsSync(failDir)).toBe(false)
})
// A bare `codex` is a `.cmd` shim on Windows. execFile's default shell:false
@@ -110,11 +129,10 @@ describe('commandExists', () => {
command: 'cmd.exe',
args: ['/c', 'C:\\ProgramData\\npm\\codex.cmd', '--version'],
})
- let seen = null
- execFileMock.impl = (cmd, args, _opts, cb) => { seen = { cmd, args }; cb(null, { stdout: 'codex-cli 0.1.0', stderr: '' }) }
+ spawnMock.impl = () => fakeChild(exitWith('codex-cli 0.1.0'))
await expect(commandExists('codex')).resolves.toBe(true)
- expect(seen).toEqual({
+ expect({ cmd: lastSpawn().cmd, args: lastSpawn().args }).toEqual({
cmd: 'cmd.exe',
args: ['/c', 'C:\\ProgramData\\npm\\codex.cmd', '--version'],
})
@@ -147,3 +165,64 @@ describe('commandExists', () => {
})
})
})
+
+describe('commandOutput lifecycle (#10604)', () => {
+ beforeEach(() => {
+ spawnMock.calls = []
+ prepareMock.impl = null
+ rmMock.fail = false
+ })
+
+ it('keeps empty output, non-empty output and failure distinct', async () => {
+ spawnMock.impl = () => fakeChild(exitWith(''))
+ await expect(commandOutput('tool')).resolves.toBe('')
+ spawnMock.impl = () => fakeChild(exitWith(' tool 1.2.3\n'))
+ await expect(commandOutput('tool')).resolves.toBe('tool 1.2.3')
+ spawnMock.impl = () => fakeChild(exitWith('partial', 2))
+ await expect(commandOutput('tool')).resolves.toBeNull()
+ })
+
+ it('fails a probe whose output exceeds maxBuffer and terminates the child', async () => {
+ let child
+ spawnMock.impl = () => (child = fakeChild((c) => c.stdout.emit('data', Buffer.alloc(32, 'x'))))
+ await expect(commandOutput('chatty', [], { maxBuffer: 16 })).resolves.toBeNull()
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM')
+ })
+
+ it('settles at the deadline when the child never closes, ignoring late events', async () => {
+ let child
+ spawnMock.impl = () => (child = fakeChild(() => {}))
+ await expect(commandOutput('stuck', [], { timeoutMs: 20 })).resolves.toBeNull()
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM')
+ expect(existsSync(lastSpawn().opts.env.TMPDIR)).toBe(false)
+ // A late error or close after the result is fixed must not throw.
+ expect(() => {
+ child.emit('error', new Error('late'))
+ child.stdout.emit('data', Buffer.from('late'))
+ child.emit('close', 0)
+ }).not.toThrow()
+ })
+
+ it('a failed scratch cleanup cannot replace the probe result', async () => {
+ rmMock.fail = true
+ spawnMock.impl = () => fakeChild(exitWith('v1'))
+ await expect(commandOutput('tool')).resolves.toBe('v1')
+ })
+
+ it.skipIf(process.platform === 'win32')('a real child that ignores SIGTERM cannot hold the probe past its deadline', async () => {
+ spawnMock.impl = null
+ const script = "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000); process.stdout.write('alive')"
+ const started = Date.now()
+
+ await expect(commandOutput(process.execPath, ['-e', script], { timeoutMs: 300 })).resolves.toBeNull()
+
+ expect(Date.now() - started).toBeLessThan(2_000)
+ expect(existsSync(lastSpawn().opts.env.TMPDIR)).toBe(false)
+ // The owned child is escalated to SIGKILL after the grace period.
+ const pid = lastSpawn().child?.pid
+ const alive = () => { try { process.kill(pid, 0); return true } catch { return false } }
+ const killDeadline = Date.now() + 5_000
+ while (alive() && Date.now() < killDeadline) await new Promise((r) => setTimeout(r, 50))
+ expect(alive()).toBe(false)
+ }, 10_000)
+})
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index df042bb069..fbff255a8c 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -178,9 +178,11 @@ vi.mock('./providers.js', async () => {
});
vi.mock('./settings.js', () => mocks.settings);
-// child_process is mocked so the install/upgrade paths (spawn-based streaming +
-// execFile-based presence checks) are drivable. Defaults are benign for the rest
-// of the suite: spawn closes clean, execFile rejects (→ commandExists() false).
+// child_process is mocked so the install/upgrade paths (spawn-based streaming)
+// are drivable, and commandExists is driven by the `cp.execFile` callback so the
+// brew/lms presence checks stay scriptable apart from those streamed spawns.
+// Defaults are benign for the rest of the suite: spawn closes clean, execFile
+// rejects (→ commandExists() false).
const cp = vi.hoisted(() => ({
defaults: {
spawn: () => {
@@ -200,6 +202,10 @@ vi.mock('../lib/childProcess.js', () => ({
spawn: (...a) => cp.spawn(...a),
execFile: (cmd, args, opts, cb) => cp.execFile(cmd, args, opts, cb),
}));
+vi.mock('../lib/commandExists.js', () => ({
+ commandExists: (cmd, args = ['--version']) =>
+ new Promise((resolve) => cp.execFile(cmd, args, {}, (err) => resolve(!err))),
+}));
// Build a fake `brew` child that streams `lines`, then closes with `code`.
const fakeChild = ({ code = 0, lines = [] } = {}) => {
diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.js
index 41e37cf56a..30eb130a6e 100644
--- a/server/services/ollamaManager.test.js
+++ b/server/services/ollamaManager.test.js
@@ -14,6 +14,12 @@ vi.mock('../lib/childProcess.js', () => ({
execFile: (cmd, args, opts, cb) => execMock.impl(cmd, args, opts, cb),
spawn: vi.fn()
}))
+// The brew/systemctl/ollama presence probes go through commandExists, which
+// spawns its own bounded child; drive them from the same exec script.
+vi.mock('../lib/commandExists.js', () => ({
+ commandExists: (cmd, args = ['--version']) =>
+ new Promise((resolve) => execMock.impl(cmd, args, {}, (err) => resolve(!err)))
+}))
// The HF pull recovery attaches the user's HF token (so a gated repo Ollama could
// pull is recoverable too). Stub the resolver rather than reading real settings.