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

refactor: give the four stdin spawn sites one delivery helper (#5655)

Adam Eivy93bc9f23d891
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 83d2aa89aa..a0f36591e9 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -17,7 +17,7 @@ import { existsSync } from 'fs';
import http from 'http';
import { Server as SocketServer } from 'socket.io';
import { ensureDir, PATHS, sleep, watchForFile } from '../lib/fileUtils.js';
-import { prepareCliSpawn, killProcessTree, guardChildStdin } from '../lib/bufferedSpawn.js';
+import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { commandExists } from '../lib/commandExists.js';
@@ -513,16 +513,7 @@ app.post('/spawn', async (req, res) => {
// Send prompt via stdin (skipped when the prompt was delivered via argv —
// antigravity's --print value, or grok's Windows temp file).
- try {
- if (useStdin) claudeProcess.stdin.write(prompt);
- claudeProcess.stdin.end();
- } catch {
- // Synchronous write failure (an already-destroyed pipe, or a prompt that is
- // not a string). Close the pipe anyway so a child that IS still reading
- // stdin sees EOF instead of hanging, and let the 'error'/'close' handler settle
- // the run with the real cause.
- claudeProcess.stdin?.destroy();
- }
+ deliverChildStdin(claudeProcess, useStdin ? prompt : null, `agent ${agentId}`);
// Handle stdout
claudeProcess.stdout.on('data', (data) => {
diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.js
index af668f404f..040a68ec50 100644
--- a/server/cos-runner/index.test.js
+++ b/server/cos-runner/index.test.js
@@ -66,8 +66,10 @@ describe('cos-runner spawn — per-provider prompt delivery (antigravity --print
it('gates the stdin write on useStdin so an argv-delivered prompt is not also piped', () => {
// For antigravity (--print value) / grok-on-Windows (temp file) useStdin is
- // false — writing the prompt to stdin too would be redundant/incorrect.
- expect(RUNNER_SRC).toMatch(/if\s*\(\s*useStdin\s*\)\s*claudeProcess\.stdin\.write\(prompt\)/);
+ // false — writing the prompt to stdin too would be redundant/incorrect. The
+ // delivery helper writes its payload only when it is non-null, so passing
+ // null there is what "don't pipe it" looks like now (#5655).
+ expect(RUNNER_SRC).toMatch(/deliverChildStdin\(claudeProcess,\s*useStdin \? prompt : null,/);
});
});
@@ -95,9 +97,9 @@ describe('cos-runner termination', () => {
// (#5655). Source-text because the route spawns a real child; the helper's
// behavior is covered in lib/bufferedSpawn.test.js.
const guardAt = RUNNER_SRC.indexOf('guardChildStdin(claudeProcess);');
- const writeAt = RUNNER_SRC.indexOf('claudeProcess.stdin.write(prompt);');
+ const deliverAt = RUNNER_SRC.indexOf('deliverChildStdin(claudeProcess,');
expect(guardAt).toBeGreaterThan(-1);
- expect(writeAt).toBeGreaterThan(guardAt);
+ expect(deliverAt).toBeGreaterThan(guardAt);
});
it('escalates through the shared armForceKill on every terminate path', () => {
diff --git a/server/lib/README.md b/server/lib/README.md
index bec0648254..66bbbc9e0a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -265,7 +265,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `interactiveShellResolver.js` | `resolveInteractiveShell()` — picks the shell binary a PTY session runs (Shell page, agent TUI shells). On Windows the old `COMSPEC` default meant `cmd.exe`, where no command a user would type reaches another drive: `cd I:` silently PRINTS that drive's cwd and stays put, a bare `I:\` is "not recognized as a command", and `cd 'I:\path'` is a syntax error (no single-quote quoting) — so a Windows install with its repos on a second drive was stuck on `C:`. Resolves PORTOS_SHELL → newest `pwsh.exe` under `%ProgramFiles%\PowerShell\<major>` (majors enumerated and sorted numerically, so a future 8 needs no code change) → any `pwsh.exe` on PATH via `findCommandOnPath` (scoop/choco/Store shim) → `powershell.exe` 5.1 (ships with Windows) → `cmd.exe` last. PowerShell crosses drives with every form. Unchanged on POSIX (`SHELL` → zsh). `resolveInteractiveShellWith({platform, env, exists, readdir, findOnPath})` is the un-memoized injectable form for tests. |
| `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. |
| `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), `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`. |
+| `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`. |
| `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.
diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.js
index 8b40086596..66bbcaeeff 100644
--- a/server/lib/bufferedSpawn.js
+++ b/server/lib/bufferedSpawn.js
@@ -456,3 +456,42 @@ export function guardChildStdin(child) {
}
return child;
}
+
+/**
+ * Deliver a prompt on a guarded child's `stdin` and close the pipe.
+ *
+ * Pair with `guardChildStdin`, which must already have run — this covers the
+ * OTHER half of the same hazard, a `write()` that throws *synchronously* (an
+ * already-destroyed pipe, or a payload that isn't a string/Buffer). That throw
+ * escapes the spawn site the same way an unlistened `'error'` does, so it is
+ * caught here.
+ *
+ * Two things then have to happen, and both were missed by the naive
+ * swallow-and-continue: the pipe is destroyed, so a child that IS still reading
+ * stdin sees EOF instead of waiting forever on a write that never lands; and
+ * the failure is logged, because a provider that gets an empty prompt and exits
+ * 0 would otherwise be filed as a clean run with nothing to explain the empty
+ * output. The child's own `'error'`/`'close'` handler stays the authoritative
+ * settle point, so this deliberately does not rethrow or settle anything.
+ *
+ * @param {import('child_process').ChildProcess} child
+ * @param {string|Buffer|null} payload - written when non-null; pass null when the
+ * prompt was already delivered by argv or a temp file and stdin only needs closing
+ * @param {string} label - names the run/agent in the failure log
+ * @returns {boolean} true when the prompt was handed off cleanly
+ */
+export function deliverChildStdin(child, payload, label) {
+ if (!child?.stdin) {
+ console.error(`❌ ${label} has no stdin pipe — the prompt was not delivered`);
+ return false;
+ }
+ try {
+ if (payload != null) child.stdin.write(payload);
+ child.stdin.end();
+ return true;
+ } catch (err) {
+ console.error(`❌ ${label} stdin write failed, closing the pipe: ${err?.code || err?.message || err}`);
+ child.stdin?.destroy();
+ return false;
+ }
+}
diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.js
index bea8e2c77e..8541a2bfa5 100644
--- a/server/lib/bufferedSpawn.test.js
+++ b/server/lib/bufferedSpawn.test.js
@@ -30,6 +30,7 @@ const {
MAX_OUTPUT_BYTES,
spawnFailureDetail,
guardChildStdin,
+ deliverChildStdin,
} = await import('./bufferedSpawn.js');
/**
@@ -630,3 +631,43 @@ describe('guardChildStdin', () => {
expect(guardChildStdin(child)).toBe(child);
});
});
+
+describe('deliverChildStdin', () => {
+ const streamStdin = (overrides = {}) => Object.assign(new EventEmitter(), {
+ write: vi.fn(), end: vi.fn(), destroy: vi.fn(), ...overrides,
+ });
+
+ it('writes the payload and closes the pipe', () => {
+ const child = { stdin: streamStdin() };
+ expect(deliverChildStdin(child, 'prompt', 'run r1')).toBe(true);
+ expect(child.stdin.write).toHaveBeenCalledWith('prompt');
+ expect(child.stdin.end).toHaveBeenCalled();
+ });
+
+ it('closes the pipe without writing when the prompt already went out by argv', () => {
+ const child = { stdin: streamStdin() };
+ expect(deliverChildStdin(child, null, 'run r1')).toBe(true);
+ expect(child.stdin.write).not.toHaveBeenCalled();
+ expect(child.stdin.end).toHaveBeenCalled();
+ });
+
+ it('destroys the pipe and logs when write throws, instead of letting it escape', () => {
+ // A bare swallow would leave a child that IS reading stdin waiting on a
+ // write that never lands, and file the resulting empty run as clean (#5655).
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const child = { stdin: streamStdin({ write: vi.fn(() => { throw Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }); }) }) };
+
+ expect(deliverChildStdin(child, 'prompt', 'run r1')).toBe(false);
+
+ expect(child.stdin.destroy).toHaveBeenCalled();
+ expect(consoleSpy.mock.calls[0][0]).toContain('❌ run r1 stdin write failed');
+ expect(consoleSpy.mock.calls[0][0]).toContain('EPIPE');
+ consoleSpy.mockRestore();
+ });
+
+ it('survives a spawn that failed command lookup and has no stdio at all', () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(deliverChildStdin({}, 'prompt', 'run r1')).toBe(false);
+ consoleSpy.mockRestore();
+ });
+});
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 3d6afc1cf3..5fe0670639 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -36,7 +36,7 @@ import { buildVendorSpawnConfig } from '../lib/providerVendors.js';
import { resolveCliModel, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';
import { resolveForgeTokenEnv } from './git.js';
import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
-import { prepareCliSpawn, killProcessTree, guardChildStdin } from '../lib/bufferedSpawn.js';
+import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { prClaimWasVerified, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';
import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';
@@ -450,16 +450,7 @@ export async function spawnDirectly({
prompt: (task.description || '').substring(0, 500)
});
- try {
- if (writePromptToStdin && claudeProcess.stdin) claudeProcess.stdin.write(prompt);
- claudeProcess.stdin?.end();
- } catch {
- // Synchronous write failure (an already-destroyed pipe, or a prompt that
- // is not a string). Close the pipe anyway so a child that IS still reading
- // stdin sees EOF instead of hanging, and let the 'error'/'exit' handler
- // settle the agent run with the real cause.
- claudeProcess.stdin?.destroy();
- }
+ deliverChildStdin(claudeProcess, writePromptToStdin ? prompt : null, `agent ${agentId}`);
activeAgents.set(agentId, {
process: claudeProcess,
diff --git a/server/services/runner.js b/server/services/runner.js
index 0e42dfa12a..4353d15792 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -11,7 +11,7 @@ import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { createImmediateFallbackSignalDetector, ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';
-import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin } from '../lib/bufferedSpawn.js';
+import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { isHostShuttingDown } from '../lib/hostShutdown.js';
import { ensureOllamaAgentContext } from './ollamaAgentContext.js';
import { isOllamaBackedProvider } from './providers.js';
@@ -416,16 +416,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc
// Pass prompt via stdin to avoid OS argv limits. When grok is delivered via a
// Windows temp file (useStdin === false) the prompt is already on disk, so
// just close stdin.
- try {
- if (useStdin) childProcess.stdin.write(promptInput);
- childProcess.stdin.end();
- } catch {
- // Synchronous write failure (an already-destroyed pipe, or a prompt that is
- // not a string). Close the pipe anyway so a child that IS still reading
- // stdin sees EOF instead of hanging, and let the 'error'/'close' handler settle
- // the run with the real cause.
- childProcess.stdin?.destroy();
- }
+ deliverChildStdin(childProcess, useStdin ? promptInput : null, `run ${runId}`);
// Track active run via the toolkit's declared external-run registry so its
// stopRun/isRunActive/deleteRun account for this host-spawned child process.
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index 2dae8a465f..61d1c5e818 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -626,6 +626,49 @@ describe('executeCliRun — Windows .cmd/.bat shim spawning (#1865)', () => {
});
});
+describe('executeCliRun — stdin pipe containment (#5655)', () => {
+ const provider = {
+ id: 'codex', command: 'codex', args: [],
+ defaultModel: 'codex-configured-default', timeout: 5000,
+ };
+
+ it('guards the pipe before writing, so a dead child\'s EPIPE cannot crash the server', async () => {
+ // executeCliRun runs outside the Express request lifecycle: an unlistened
+ // 'error' on the stdin stream is re-thrown by Node and takes the whole
+ // server process down with every live run on it.
+ const child = makeChild();
+ let listenersAtWriteTime = null;
+ child.stdin.write = vi.fn(() => { listenersAtWriteTime = child.stdin.listenerCount('error'); });
+ spawn.mockReturnValue(child);
+
+ await executeCliRun({ runId: 'run-stdin-guard', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE });
+
+ expect(listenersAtWriteTime).toBe(1);
+ expect(() => child.stdin.emit('error', Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }))).not.toThrow();
+ child.emit('close', 0);
+ });
+
+ it('closes the pipe and logs when the write throws, rather than stranding the run', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const child = makeChild();
+ child.stdin.write = vi.fn(() => { throw Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }); });
+ spawn.mockReturnValue(child);
+
+ const onComplete = vi.fn();
+ // The synchronous throw is contained — executeCliRun still returns normally.
+ await executeCliRun({ runId: 'run-stdin-throw', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE, onComplete });
+
+ // A child still reading stdin must see EOF instead of waiting on a write that never lands.
+ expect(child.stdin.destroy).toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('run run-stdin-throw stdin write failed'));
+
+ child.emit('close', 0);
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ errorSpy.mockRestore();
+ });
+});
+
describe('executeCliRun — close handler crash guard', () => {
// Drive a codex run whose first write (output) succeeds and second write
// (metadata) rejects, so the close handler's recovery path runs. Returns the
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
index f2f1771ba9..7d38093608 100644
--- a/server/services/visionCli.js
+++ b/server/services/visionCli.js
@@ -31,7 +31,7 @@ import { extname, join } from 'path';
import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { resolveCliModel, isCodexProvider, buildCodexStartupArgs, buildEffortArgs } from '../lib/providerModels.js';
import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
-import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin } from '../lib/bufferedSpawn.js';
+import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
const CLI_VISION_TIMEOUT_MS = 120000;
@@ -293,14 +293,7 @@ async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnIm
// When grok is delivered via a Windows temp file the prompt is already on
// disk (writePromptToStdin=false) — just close stdin.
- try {
- if (writePromptToStdin && stdin != null) child.stdin?.write(stdin);
- child.stdin?.end();
- } catch {
- // Synchronous write failure — close the pipe so a reading child sees EOF,
- // and let the 'error'/'close' handler above reject with the real cause.
- child.stdin?.destroy();
- }
+ deliverChildStdin(child, writePromptToStdin ? stdin : null, `${command} vision call`);
});
return text;
diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.js
index 1c153ba4ed..29be3c32e2 100644
--- a/server/services/visionCli.test.js
+++ b/server/services/visionCli.test.js
@@ -149,7 +149,9 @@ function makeFakeChild() {
Object.setPrototypeOf(child, ChildProcess.prototype);
child.killed = false;
child.kill = vi.fn(() => { child.killed = true; });
- child.stdin = { write: vi.fn(), end: vi.fn() };
+ // A real ChildProcess stdin is a stream — the fake is one too, or the
+ // production guardChildStdin listener has nothing to attach to (#5655).
+ child.stdin = Object.assign(new EventEmitter(), { write: vi.fn(), end: vi.fn(), destroy: vi.fn() });
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
return child;
@@ -319,6 +321,37 @@ describe('describeImageViaCli', () => {
expect(child.kill).toHaveBeenCalledWith('SIGTERM');
});
+ it('contains an EPIPE on stdin from a vision CLI that died before reading the prompt (#5655)', async () => {
+ // describeImageViaCli runs outside the Express request lifecycle, so an
+ // unlistened 'error' on the stdin stream would kill the server process
+ // instead of rejecting this promise.
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const child = makeFakeChild();
+ let listenersAtWriteTime = null;
+ child.stdin.write = vi.fn(() => {
+ listenersAtWriteTime = child.stdin.listenerCount('error');
+ throw Object.assign(new Error('write EPIPE'), { code: 'EPIPE' });
+ });
+ const spawnImpl = spawnEmitting(child, (c) => {
+ expect(() => c.stdin.emit('error', Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }))).not.toThrow();
+ c.emit('close', 1);
+ });
+
+ // claude-code is the stdin-delivering vision provider (codex puts the
+ // prompt in argv and never writes the pipe).
+ await expect(describeImageViaCli({
+ provider: { id: 'claude-code', command: 'claude', args: [] },
+ dataUrl: PNG_DATA_URL,
+ prompt: 'caption this',
+ spawnImpl,
+ })).rejects.toThrow(/exited 1/);
+
+ expect(listenersAtWriteTime).toBe(1);
+ // The pipe is closed anyway, so a child still reading stdin sees EOF.
+ expect(child.stdin.destroy).toHaveBeenCalled();
+ errorSpy.mockRestore();
+ });
+
it('throws on a malformed data URL before spawning', async () => {
const spawnImpl = vi.fn();
await expect(describeImageViaCli({