Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(main): handle child-stdin EPIPE as the async error event it is
enes0e6b9f750f27
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e63c9a0a3..f071d95b3 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -86,6 +86,16 @@ need it too, and wire it in the same change.see. Keep a remote temp's own leaf bounded: extending an already-valid maximum-length target leafwith a UUID suffix turns an atomic write into a guaranteed `ENAMETOOLONG` failure.+- **Never write to a child's stdin without an `'error'` listener on that stream.** A pipe write's+ failure is not a throw at the call site: when the child exits before draining stdin (a CLI handed+ a flag it doesn't know, an unreachable ssh host), Node re-emits the EPIPE as an async `'error'`+ EVENT on the stream — a try/catch around the write is inert, and the unhandled event crashes the+ whole main process with an "Uncaught Exception: write EPIPE" dialog (issue #382's class). Attach+ `child.stdin.on('error', ...)` before the first write — log via `console.warn` so the debug ring+ sees it, or settle the pending call; the child's exit code stays the authority on the outcome+ (see `tmux-control-client.ts` and `pty-manager.ts` `runWithStdin` for the house pattern). A test+ (`src/core/stream-epipe.guard.test.ts`) scans for this and will fail your PR.+- **Never unmount, move or re-key a browser/web node's element.** An Electron `<webview>`'s guestprocess dies on DOM detach — and a detach includes any `insertBefore`/`appendChild` MOVE of anattached element, which React performs whenever a kept child's relative order among kept keyeddiff --git a/src/core/commit-message.epipe.test.ts b/src/core/commit-message.epipe.test.tsnew file mode 100644index 000000000..f972b4691--- /dev/null+++ b/src/core/commit-message.epipe.test.ts@@ -0,0 +1,65 @@+// Repro for the "Uncaught Exception: write EPIPE" dialog (issue #382's class, second wave).+//+// spawnAgent pipes the whole prompt (a staged diff can be 200 KB) into the agent CLI's stdin.+// When the CLI exits before draining it — bad flag, instant auth failure, crash on boot — the+// kernel closes the pipe's read end and the pending write fails with EPIPE. That failure does NOT+// arrive as a throw at `child.stdin.write(...)`: Node re-emits it as an async 'error' EVENT on the+// stdin stream, so a try/catch around the write is inert (measured in #382 for stdio; same+// mechanics here), and with no 'error' listener the event became an uncaught exception that put an+// error dialog over the whole app.+//+// The fake CLI below exits without reading a byte, and the prompt is far larger than the kernel+// pipe buffer (64 KB on Linux), so the EPIPE is deterministic. Before the fix the trap catches an+// EPIPE uncaught exception; after it, the handler logs and the call resolves normally.++import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'fs'+import os from 'os'+import { join } from 'path'+import { runAgent } from './commit-message'+import type { Settings } from '../shared/types'++const wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))++describe.skipIf(process.platform === 'win32')('agent stdin EPIPE stays inside the call', () => {+ let dir: string+ let uncaught: unknown[]+ const trap = (e: unknown): void => {+ uncaught.push(e)+ }++ beforeEach(() => {+ dir = mkdtempSync(join(os.tmpdir(), 'nt-epipe-'))+ uncaught = []+ process.on('uncaughtException', trap)+ })++ afterEach(() => {+ process.removeListener('uncaughtException', trap)+ rmSync(dir, { recursive: true, force: true })+ })++ it('an agent CLI that exits without reading its prompt does not crash the process', async () => {+ const fakeCli = join(dir, 'fake-agent')+ // Exits immediately, never reads stdin — the shape of a CLI refusing its flags.+ writeFileSync(fakeCli, '#!/bin/sh\nexit 7\n')+ chmodSync(fakeCli, 0o755)++ const settings = {+ commitAgent: 'custom',+ commitAgentCommand: fakeCli,+ commitExtraPrompt: ''+ } as unknown as Settings++ // Far past the 64 KB pipe buffer, so the write is still in flight when the child dies.+ const prompt = 'x'.repeat(1024 * 1024)+ const res = await runAgent(prompt, dir, settings)++ // The failure is reported through the call's own contract...+ expect(res.ok).toBe(false)+ // ...and the EPIPE stays an event the handler consumed, never an uncaught exception. The+ // 'error' event fires on a later tick than the close that resolved us, so give it room.+ await wait(150)+ expect(uncaught).toEqual([])+ })+})diff --git a/src/core/commit-message.test.ts b/src/core/commit-message.test.tsindex 69a79924e..433adecaf 100644--- a/src/core/commit-message.test.ts+++ b/src/core/commit-message.test.ts@@ -60,7 +60,7 @@ describe('runAgent — where the agent is actually spawned', () => {const child = {stdout: { on: (_e: string, cb: (d: Buffer) => void) => cb(Buffer.from('a message')) },stderr: { on: () => {} },- stdin: { write: () => {}, end: () => {} },+ stdin: { write: () => {}, end: () => {}, on: () => {} },kill: () => {},on: (e: string, cb: (...a: unknown[]) => void) => {;(listeners[e] ??= []).push(cb)diff --git a/src/core/commit-message.ts b/src/core/commit-message.tsindex 0f09dd5ca..02c44d3db 100644--- a/src/core/commit-message.ts+++ b/src/core/commit-message.ts@@ -184,6 +184,14 @@ function spawnAgent(resolve({ code: code ?? 1, stdout, stderr })})if (stdin !== null) {+ // The agent CLI can exit before draining the prompt (bad flag, instant auth failure, crash+ // on boot) — the resulting EPIPE is NOT a throw at the write below but an async 'error'+ // EVENT on the pipe, and unhandled it takes the whole main process down (issue #382's+ // class). The close handler above already owns the outcome; log it and let the exit code+ // plus stderr tell the real story.+ child.stdin.on('error', (e: NodeJS.ErrnoException) => {+ console.warn(`[commit-message] agent stdin write failed (${e.code ?? e})`)+ })child.stdin.write(stdin)child.stdin.end()}diff --git a/src/core/git-service.ts b/src/core/git-service.tsindex 30777b88d..fb07b54b5 100644--- a/src/core/git-service.ts+++ b/src/core/git-service.ts@@ -202,6 +202,13 @@ function githubTokenFromGitCredentials(cwd: string): Promise<string | null> {const token = line ? line.slice('password='.length).trim() : ''resolve(token || null)})+ // `git credential fill` can exit before reading the query (no helper configured, killed by+ // the timeout above) — the EPIPE arrives as an async 'error' EVENT on the pipe, not a throw+ // here, and unhandled it kills the main process (issue #382's class). The close handler+ // already resolves this call; the error never carries the token, so logging the code is safe.+ child.stdin.on('error', (e: NodeJS.ErrnoException) => {+ console.warn(`[git] credential-fill stdin write failed (${e.code ?? e})`)+ })child.stdin.write('protocol=https\nhost=github.com\n\n')child.stdin.end()})diff --git a/src/core/stream-epipe.guard.test.ts b/src/core/stream-epipe.guard.test.tsnew file mode 100644index 000000000..fd3256226--- /dev/null+++ b/src/core/stream-epipe.guard.test.ts@@ -0,0 +1,92 @@+// A child's stdin is a pipe, and a pipe's write failure is NOT a throw at the call site: Node+// re-emits it as an async 'error' EVENT on the stream, so a try/catch around `stdin.write(...)`+// is inert and an unhandled event kills the whole main process with the "Uncaught Exception:+// write EPIPE" dialog. Issue #382 taught this for process stdio (PR #395 guarded the log sink);+// the second wave was every OTHER naked child-stdin write in the tree — the AI commit-message+// spawn, `git credential fill`, the ssh run() leg, the codex app-server probe. Each looked+// correct in review, because on the happy path a pipe write never fails; the error needs the+// child to die mid-write, which is exactly what a CLI does when handed a flag it does not know.+//+// So the rule is enforced by scan, in the fs-atomic.guard.test.ts mold: any file that writes to+// a `stdin` stream must also attach an 'error' listener to one. File granularity is a tripwire,+// not a proof — a file can attach the listener to one child and leave another naked — but it is+// the shape every past regression had (a NEW file, or a new spawn in a file with no handler at+// all), and a reviewer pointed at the file by a red test can check the pairing in seconds.++import { describe, expect, it } from 'vitest'+import { readFileSync, readdirSync, statSync } from 'fs'+import { join, relative } from 'path'++const ROOTS = ['core', 'main', 'server', 'session-host'].map((d) => join(__dirname, '..', d))+const SOURCE_ROOT = join(__dirname, '..')++function sources(dir: string, out: string[] = []): string[] {+ for (const entry of readdirSync(dir)) {+ const p = join(dir, entry)+ if (statSync(p).isDirectory()) {+ if (entry !== 'node_modules') sources(p, out)+ } else if (/\.ts$/.test(entry) && !/\.test\.ts$/.test(entry)) {+ out.push(p)+ }+ }+ return out+}++/** Strip comments so a documented example cannot trip (or satisfy) the needles. String literals+ * are kept: a generated-sh template writing `stdin.write` into a script would be a real hazard in+ * the generated program too, and none exist today. */+function stripComments(text: string): string {+ return text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')+}++/** Every spelling a child-stdin write takes in this tree: `child.stdin.write(`,+ * `child.stdin?.end(`, `cp.stdin!.write(`, and a destructured/aliased `stdin.end(`. */+const WRITE_NEEDLE = /\bstdin[!?]*\.(?:write|end)\s*\(/+/** ...and the guard that makes those writes safe. */+const HANDLER_NEEDLE = /\bstdin[!?]*\.(?:on|once)\s*\(\s*['"]error['"]/++describe('every child-stdin writer handles the pipe error event', () => {+ const files = ROOTS.flatMap((r) => sources(r))++ it('finds the source tree (a zero-file scan would pass silently)', () => {+ expect(files.length).toBeGreaterThan(100)+ })++ it('no stdin write without an error listener in the same file', () => {+ const offenders: string[] = []+ for (const f of files) {+ const code = stripComments(readFileSync(f, 'utf8'))+ if (WRITE_NEEDLE.test(code) && !HANDLER_NEEDLE.test(code)) {+ offenders.push(relative(SOURCE_ROOT, f).replace(/\\/g, '/'))+ }+ }+ expect(+ offenders,+ 'these write to a child stdin with no \'error\' listener on it — the EPIPE from a child ' ++ 'that exits early is an async event, not a throw, and unhandled it crashes the app. ' ++ "Attach `child.stdin.on('error', ...)` (log via console.warn so the debug ring sees it, " ++ 'or settle the pending call) before the first write; see tmux-control-client.ts and ' ++ 'pty-manager.ts runWithStdin for the house pattern.'+ ).toEqual([])+ })++ it('the needles actually bite, and the guard patterns do not', () => {+ expect(WRITE_NEEDLE.test('child.stdin.write(payload)')).toBe(true)+ expect(WRITE_NEEDLE.test('child.stdin?.end(stdin)')).toBe(true)+ expect(WRITE_NEEDLE.test('cp.stdin!.write(s)')).toBe(true)+ expect(WRITE_NEEDLE.test('stdin.end(input)')).toBe(true)+ // A stdout write is a different stream with a different owner (the log sink).+ expect(WRITE_NEEDLE.test('process.stdout.write(line)')).toBe(false)+ // The handler spellings in the tree today.+ expect(HANDLER_NEEDLE.test("child.stdin.on('error', onErr)")).toBe(true)+ expect(HANDLER_NEEDLE.test("cp.stdin?.on('error', () => {})")).toBe(true)+ expect(HANDLER_NEEDLE.test("stdin.once('error', () => {})")).toBe(true)+ // Listening on the CHILD is not listening on the pipe — the crash the rule is about.+ expect(HANDLER_NEEDLE.test("child.on('error', () => {})")).toBe(false)+ })++ it('comments neither trip nor satisfy the scan', () => {+ expect(WRITE_NEEDLE.test(stripComments('// child.stdin.write(payload)'))).toBe(false)+ expect(HANDLER_NEEDLE.test(stripComments("// child.stdin.on('error', cb)"))).toBe(false)+ })+})diff --git a/src/core/usage/codex-usage.ts b/src/core/usage/codex-usage.tsindex efa89823d..cf97ccb3d 100644--- a/src/core/usage/codex-usage.ts+++ b/src/core/usage/codex-usage.ts@@ -181,6 +181,11 @@ async function fetchViaAppServer(home: string): Promise<ProviderUsage | null> {// A missing `codex` binary surfaces here, not as a spawn throw.child.on('error', () => finish(null))child.on('exit', () => finish(null))+ // codex can exit before draining a request (an older CLI without `app-server` prints usage+ // and quits) — the EPIPE from the stdin writes below is an async 'error' EVENT on the pipe,+ // not a throw at the call site, and unhandled it kills the main process (issue #382's+ // class). A broken pipe means no reply is coming, so settle instead of waiting the timer out.+ child.stdin?.on('error', () => finish(null))let buf = ''child.stdout?.on('data', (chunk: Buffer) => {diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 1b38085bf..6d0e3d896 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -2320,6 +2320,13 @@ export function initSshProject(resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, stdout: stdout ?? '' }))if (stdin !== undefined) {+ // ssh can die before draining stdin (unreachable host, bad option, instant auth+ // refusal) — that EPIPE is an async 'error' EVENT on the pipe, not a throw here, and+ // unhandled it kills the main process (issue #382's class). The execFile callback+ // above already reports the child's exit; log and stand by.+ child.stdin?.on('error', (e: NodeJS.ErrnoException) => {+ console.warn(`[ssh-project] ssh stdin write failed (${e.code ?? e})`)+ })child.stdin?.end(stdin)}}),