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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: close the stdin pipe and surface the EPIPE the guard swallows (#5655)
Adam Eivy6b16f4cbdfb8
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex cf58a7a74c..83d2aa89aa 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -517,8 +517,11 @@ app.post('/spawn', async (req, res) => {if (useStdin) claudeProcess.stdin.write(prompt);claudeProcess.stdin.end();} catch {- // Synchronous write failure (already-destroyed stdin) — the 'error'/'close'- // handler settles the run with the real cause.+ // 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();}// Handle stdoutdiff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex d696d01cc4..af668f404f 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -89,6 +89,17 @@ describe('cos-runner termination', () => {expect(RUNNER_SRC).not.toContain(".process.kill('SIG");});+ it('guards the child stdin pipe BEFORE writing the prompt to it', () => {+ // A child that dies before reading stdin emits EPIPE, and an unlistened+ // stream 'error' in this non-request context kills the runner process+ // (#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);');+ expect(guardAt).toBeGreaterThan(-1);+ expect(writeAt).toBeGreaterThan(guardAt);+ });+it('escalates through the shared armForceKill on every terminate path', () => {expect(RUNNER_SRC).toContain("import { armForceKill as armForceKillShared } from './forceKill.js';");// /terminate and /terminate-all, plus the post-finalize tui:kill relay.diff --git a/server/lib/README.md b/server/lib/README.mdindex c5f9e2bf7f..bec0648254 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; used by every CLI-agent spawn site), `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), `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.jsindex 04021f3d4b..8b40086596 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -436,7 +436,9 @@ export function spawnFailureDetail(result, fallback) {* takes down the single server process that owns every live agent run, PTY* shell, media job and socket. Swallowing it is correct: the child's own* `'error'`/`'exit'`/`'close'` handler is the authoritative settle point and- * reports the real cause.+ * reports the real cause. It is logged rather than dropped, because a child+ * that exits 0 after refusing its prompt would otherwise be recorded as a clean+ * run with no trace of the prompt never having been delivered.** A crash guard must never be the crash: a `spawn()` that failed command lookup* hands back a handle with no stdio at all, and a child configured with a@@ -447,6 +449,10 @@ export function spawnFailureDetail(result, fallback) {* @returns {import('child_process').ChildProcess} the same child, for chaining*/export function guardChildStdin(child) {- if (typeof child?.stdin?.on === 'function') child.stdin.on('error', () => {});+ if (typeof child?.stdin?.on === 'function') {+ child.stdin.on('error', (err) => {+ console.warn(`⚠️ child stdin closed before the prompt was delivered: ${err?.code || err?.message || err}`);+ });+ }return child;}diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex 6f5034f0c7..bea8e2c77e 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -608,7 +608,7 @@ describe('guardChildStdin', () => {// An 'error' on a stream with no listener is re-thrown by Node. Every CLI-agent// spawn site runs outside the Express request lifecycle, so that throw takes the// whole server process down — with every live agent run, PTY shell and socket on- // it. This is the contract those three call sites rely on.+ // it. This is the contract every CLI spawn site that writes stdin relies on.it('swallows an EPIPE emitted on the child stdin pipe', () => {const child = { stdin: new EventEmitter() };guardChildStdin(child);diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex ca0cca69ec..3d6afc1cf3 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -454,8 +454,11 @@ export async function spawnDirectly({if (writePromptToStdin && claudeProcess.stdin) claudeProcess.stdin.write(prompt);claudeProcess.stdin?.end();} catch {- // Synchronous write failure (already-destroyed stdin) — the 'error'/'exit'- // handler settles the agent run with the real cause.+ // 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();}activeAgents.set(agentId, {diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 73017b09fd..e3332e19c8 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -649,16 +649,27 @@ describe('stream error containment', () => {// Regression guard for the listener drifting back below the write.const epipe = () => Object.assign(new Error('write EPIPE'), { code: 'EPIPE' });fakeProcess = makeFakeProcess();+ // Captured INSIDE write so the assertion is about ordering, not just+ // eventual presence — a guard moved below the write would read 0 here.+ let listenersAtWriteTime = null;fakeProcess.stdin = Object.assign(new EventEmitter(), {- write: vi.fn(() => { throw epipe(); }),+ write: vi.fn(function () {+ listenersAtWriteTime = fakeProcess.stdin.listenerCount('error');+ throw epipe();+ }),end: vi.fn(),+ destroy: vi.fn(),});const spawnPromise = spawnDirectly(minimalArgs);await new Promise((r) => setTimeout(r, 10));- // A listener IS attached, so the late pipe error is swallowed instead of thrown.+ // The guard was already in place when the write ran…+ expect(listenersAtWriteTime).toBe(1);+ // …so a late pipe error is swallowed instead of thrown.expect(() => fakeProcess.stdin.emit('error', epipe())).not.toThrow();+ // …and the pipe was closed anyway, so a child still reading stdin sees EOF.+ expect(fakeProcess.stdin.destroy).toHaveBeenCalled();fakeProcess.emit('close', 0);// The synchronous write throw did not escape as a rejected spawn either.diff --git a/server/services/runner.js b/server/services/runner.jsindex 15e637949c..0e42dfa12a 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -420,8 +420,11 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, scif (useStdin) childProcess.stdin.write(promptInput);childProcess.stdin.end();} catch {- // Synchronous write failure (already-destroyed stdin) — the 'error'/'close'- // handler settles the run with the real cause.+ // 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();}// Track active run via the toolkit's declared external-run registry so itsdiff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 99c28bc348..2dae8a465f 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -113,7 +113,9 @@ function makeChild() {Object.setPrototypeOf(child, ChildProcess.prototype);child.stdout = new EventEmitter();child.stderr = new EventEmitter();- 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.kill = vi.fn();child.killed = false;return child;diff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex e4875032d3..f2f1771ba9 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 } from '../lib/bufferedSpawn.js';+import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';const CLI_VISION_TIMEOUT_MS = 120000;@@ -286,13 +286,20 @@ async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnImreject(new Error(`${command} vision call exited ${code}${tail ? `: ${tail}` : ''}`));});+ // Guard the pipe before writing — a vision CLI that exits before reading+ // stdin emits EPIPE, and an unlistened stream 'error' out here crashes the+ // server rather than rejecting this promise. See guardChildStdin.+ guardChildStdin(child);+// When grok is delivered via a Windows temp file the prompt is already on// disk (writePromptToStdin=false) — just close stdin.- if (writePromptToStdin && stdin != null) {- child.stdin?.write(stdin);- child.stdin?.end();- } else {+ 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();}});