Skip to content

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.

fix(log): survive a revoked stdout/stderr instead of crashing the main process

enes5c2cb8227dcd
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4cb5bf426..8db9d21dc 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -134,6 +134,14 @@ here has: not while the kanban board covers it, not while the user is typing.
reasoning. A comment that restates the code is noise; one that says "do not simplify this back,
here is what broke" is the point.
+**A stream error is not a throw you can catch.** When a write to `process.stdout`/`stderr` fails —
+`EPIPE` down a closed pipe, `EIO` after macOS revokes a closed terminal's tty — node reports it by
+emitting `'error'` on the stream a tick later, and the default for an unhandled `'error'` event is
+to kill the process. The stack it carries was captured at the write, so the crash *reads* as if it
+happened synchronously at your `console.log`, and wrapping that call in `try/catch` changes nothing
+(measured on node 22). If you write to a stream that can go away, attach an `'error'` listener and
+latch the writer off — `installLogSink` (`src/core/log-sink.ts`) is the worked example. Issue #382.
+
**Agent features attach to base harness capabilities, not frontend allowlists.** A custom agent can
inherit a builtin harness, so add the capability and its one shared leaf (`src/shared/agents`) and
let every UI ask the helper. Repeating Claude/Codex/etc. cases in menus breaks that inheritance and
diff --git a/src/core/log-handlers.test.ts b/src/core/log-handlers.test.ts
index d99549781..bb8f6d9fb 100644
--- a/src/core/log-handlers.test.ts
+++ b/src/core/log-handlers.test.ts
@@ -86,4 +86,70 @@ describe('installLogSink', () => {
expect(splitTag('plain line')).toEqual({ tag: '', rest: 'plain line' })
expect(splitTag(42)).toEqual({ tag: '', rest: '42' })
})
+
+ // Issue #382: the terminal an `npm start` was launched from goes away, macOS revokes the tty
+ // fds, and the next console.log kills the main process. The failure is delivered as an 'error'
+ // EVENT on the stream (measured on node 22 — a try/catch at the call site catches nothing), so
+ // these drive it the way node does.
+ describe('a dying stdio stream', () => {
+ const eio = (): NodeJS.ErrnoException => Object.assign(new Error('write EIO'), { code: 'EIO' })
+
+ it("stops forwarding to a stream that emitted 'error' — that stream only — and keeps the ring", () => {
+ const b = new LogBuffer()
+ const out = vi.fn()
+ const err = vi.fn()
+ const origLog = console.log
+ const origError = console.error
+ console.log = out
+ console.error = err
+ const un = installLogSink(b)
+ try {
+ console.log('before')
+ process.stdout.emit('error', eio())
+ console.log('after')
+ console.error('stderr still works')
+ } finally {
+ un()
+ console.log = origLog
+ console.error = origError
+ }
+ expect(out).toHaveBeenCalledTimes(1)
+ expect(err).toHaveBeenCalledTimes(1)
+ const msgs = b.snapshot().map((r) => r.msg)
+ expect(msgs).toContain('before')
+ expect(msgs).toContain('after')
+ expect(msgs).toContain('stderr still works')
+ expect(msgs.some((m) => m.includes('forwarding to stdout disabled') && m.includes('EIO'))).toBe(true)
+ })
+
+ it('swallows a synchronous write failure instead of letting it reach the caller', () => {
+ const b = new LogBuffer()
+ const origLog = console.log
+ let calls = 0
+ console.log = () => {
+ calls++
+ throw eio()
+ }
+ const un = installLogSink(b)
+ try {
+ expect(() => console.log('boom')).not.toThrow()
+ console.log('again')
+ } finally {
+ un()
+ console.log = origLog
+ }
+ // Latched after the first failure: the second call never reached the broken original.
+ expect(calls).toBe(1)
+ expect(b.snapshot().map((r) => r.msg)).toContain('again')
+ })
+
+ it('removes its stream listeners on uninstall', () => {
+ const b = new LogBuffer()
+ const before = process.stdout.listenerCount('error')
+ const un = installLogSink(b)
+ expect(process.stdout.listenerCount('error')).toBe(before + 1)
+ un()
+ expect(process.stdout.listenerCount('error')).toBe(before)
+ })
+ })
})
diff --git a/src/core/log-sink.ts b/src/core/log-sink.ts
index acf18d7fe..a2aa65176 100644
--- a/src/core/log-sink.ts
+++ b/src/core/log-sink.ts
@@ -16,6 +16,17 @@ const LEVEL: Record<string, LogRecord['level']> = {
error: 'error'
}
+type StdioName = 'stdout' | 'stderr'
+
+/** Which stdio stream each console method writes to — node's own Console contract. */
+const STREAM_OF: Record<keyof typeof LEVEL, StdioName> = {
+ log: 'stdout',
+ info: 'stdout',
+ debug: 'stdout',
+ warn: 'stderr',
+ error: 'stderr'
+}
+
/** The `[subsystem]` prefix convention: split it off the first arg when present. */
export function splitTag(first: unknown): { tag: string; rest: string } {
if (typeof first === 'string') {
@@ -26,6 +37,12 @@ export function splitTag(first: unknown): { tag: string; rest: string } {
return { tag: '', rest: formatArg(first) }
}
+/** `EIO` / `EPIPE` / … when the failure carries one, else something printable. */
+function errCode(e: unknown): string {
+ const code = (e as NodeJS.ErrnoException | null)?.code
+ return typeof code === 'string' && code ? code : String(e)
+}
+
function formatArg(a: unknown): string {
if (typeof a === 'string') return a
if (a instanceof Error) return a.stack ?? String(a)
@@ -46,6 +63,29 @@ function formatArg(a: unknown): string {
* dies), and a debug log must observe failures, not swallow them. There is no monitor
* equivalent for 'unhandledRejection', and installing that listener suppresses the default
* throw-on-unhandled behavior — so rejections are left alone here on purpose.
+ *
+ * **A dying stdio stream must not take the app with it** (issue #382: `write EIO` killed the
+ * main process after the terminal a `npm start` was launched from went away — macOS `revoke()`s
+ * the tty's fds, and every later `console.log` writes into a revoked descriptor). Two facts
+ * decide the shape of the guard, and the first one is counter-intuitive:
+ *
+ * 1. **The error does NOT arrive as a throw at the call site.** When stdout is a pipe or a tty
+ * node writes it as a Socket, so the failure comes back through the write callback and is
+ * re-emitted as an `'error'` EVENT on `process.stdout` on a later tick. The stack it carries
+ * was captured at the write, which is why the report *looks* synchronous — measured on node
+ * 22: a `try/catch` around `originals[name].apply(...)` catches nothing at all, and the
+ * process still dies. So the load-bearing half of the fix is an `'error'` listener on each
+ * stdio stream; the `try/catch` is only there for the stdout-is-a-plain-file shape, where
+ * node writes synchronously through `fs.writeSync` and a throw really can reach us.
+ * 2. **A dead stream stays dead**, and every subsequent write raises the error again (29 of 31
+ * writes, measured). So the first failure LATCHES that stream off: forwarding stops, the ring
+ * keeps everything, and the app's own observability is untouched — which is the whole reason
+ * the ring exists. Any error latches, whatever its code; a stdio stream we could not write to
+ * is not one worth probing again for a dev convenience.
+ *
+ * The listener is global by nature — it also stops a crash from some other writer's failed
+ * `process.stdout.write`. That is a strict improvement (the alternative is the default: die),
+ * and it is removed again by the uninstaller.
*/
export function installLogSink(buffer: LogBuffer): () => void {
const originals = {
@@ -55,9 +95,45 @@ export function installLogSink(buffer: LogBuffer): () => void {
warn: console.warn,
error: console.error
}
+ const dead: Record<StdioName, boolean> = { stdout: false, stderr: false }
+ const note = (which: StdioName, why: string): void => {
+ if (dead[which]) return
+ dead[which] = true
+ try {
+ buffer.push({
+ level: 'warn',
+ tag: 'log-sink',
+ msg: `console forwarding to ${which} disabled after a stream failure (${why}); the ring keeps logging`
+ })
+ } catch {
+ /* see below — logging must never throw */
+ }
+ }
+ const streams: Record<StdioName, NodeJS.WritableStream | undefined> = {
+ stdout: process.stdout,
+ stderr: process.stderr
+ }
+ const streamListeners: { which: StdioName; fn: (err: unknown) => void }[] = []
+ for (const which of Object.keys(streams) as StdioName[]) {
+ const stream = streams[which]
+ if (!stream || typeof stream.on !== 'function') continue
+ const fn = (err: unknown): void => note(which, errCode(err))
+ stream.on('error', fn)
+ streamListeners.push({ which, fn })
+ }
+
for (const name of Object.keys(originals) as (keyof typeof originals)[]) {
+ const which = STREAM_OF[name]
console[name] = (...args: unknown[]): void => {
- originals[name].apply(console, args)
+ if (!dead[which]) {
+ try {
+ originals[name].apply(console, args)
+ } catch (e) {
+ // Only the synchronous shape lands here (see the doc comment); the common one is the
+ // stream 'error' event above. Either way the stream is done — never rethrow.
+ note(which, errCode(e))
+ }
+ }
try {
const { tag, rest } = splitTag(args[0])
const tail = args.slice(1).map(formatArg).join(' ')
@@ -78,5 +154,6 @@ export function installLogSink(buffer: LogBuffer): () => void {
return () => {
Object.assign(console, originals)
process.removeListener('uncaughtExceptionMonitor', onUncaught)
+ for (const { which, fn } of streamListeners) streams[which]?.removeListener('error', fn)
}
}