Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix: contain asynchronous tmux control pipe errors

deed9dace5a4c76
diff --git a/cli/src/lib/tmuxStream.failure.spec.ts b/cli/src/lib/tmuxStream.failure.spec.ts
new file mode 100644
index 000000000..673502e29
--- /dev/null
+++ b/cli/src/lib/tmuxStream.failure.spec.ts
@@ -0,0 +1,82 @@
+import { EventEmitter } from 'node:events'
+import { PassThrough, Writable } from 'node:stream'
+import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { TmuxControlStream } from './tmuxStream.js'
+
+vi.mock('node:child_process', async (importOriginal) => ({
+ ...await importOriginal<typeof import('node:child_process')>(),
+ execFile: vi.fn(),
+ spawn: vi.fn(),
+}))
+
+afterEach(() => vi.resetAllMocks())
+
+function controlClient() {
+ const metadata = '$1|@1|1|80|24|80|24|0|0|0|1|0|0|0|0|0\n'
+ const child = new EventEmitter() as {
+ -readonly [K in keyof ChildProcessWithoutNullStreams]: ChildProcessWithoutNullStreams[K]
+ }
+ child.stdout = new PassThrough()
+ child.stderr = new PassThrough()
+ child.exitCode = null
+ child.signalCode = null
+ let failed = false
+ let command = 1
+ const exit = () => {
+ if (child.exitCode != null) return
+ child.exitCode = 0
+ child.emit('close', 0)
+ }
+ child.kill = () => { exit(); return true }
+ child.stdin = new Writable({
+ write(chunk, _encoding, callback) {
+ const number = command++
+ setImmediate(() => {
+ if (failed) {
+ // A dead control client's pipe reports this asynchronously, outside
+ // any try/catch around stdin.write().
+ callback(Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }))
+ setImmediate(exit)
+ return
+ }
+ callback()
+ if (chunk.toString().startsWith('detach-client')) { exit(); return }
+ child.stdout.emit('data', Buffer.from(`%begin 1 ${number} 0\n${metadata}%end 1 ${number} 0\n`))
+ })
+ },
+ })
+ vi.mocked(execFile).mockImplementation(((...args: unknown[]) => {
+ const callback = args.at(-1) as (error: null, stdout: Buffer) => void
+ callback(null, Buffer.from(metadata))
+ return child
+ }) as typeof execFile)
+ vi.mocked(spawn).mockImplementation(() => {
+ setImmediate(() => {
+ child.emit('spawn')
+ setImmediate(() => child.stdout.emit('data', Buffer.from('%begin 1 0 0\n%end 1 0 0\n')))
+ })
+ return child
+ })
+ return { breakPipe: () => { failed = true } }
+}
+
+describe('tmux control pipe failure', () => {
+ for (const action of ['input', 'close'] as const) {
+ it(`contains an asynchronous broken pipe during ${action}`, async () => {
+ const client = controlClient()
+ const onClose = vi.fn()
+ const opened = await TmuxControlStream.open('%1', { cols: 80, rows: 24 }, {
+ onData: () => {}, onClose,
+ })
+ expect(opened.state).toBe('succeeded')
+ if (opened.state !== 'succeeded') return
+ client.breakPipe()
+ if (action === 'input') {
+ expect((await opened.value.writeRaw(Buffer.from('hello'))).state).not.toBe('succeeded')
+ }
+ await opened.value.close()
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+ }
+})
diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.ts
index 5b4b83cf7..677b3e6ac 100644
--- a/cli/src/lib/tmuxStream.ts
+++ b/cli/src/lib/tmuxStream.ts
@@ -452,6 +452,12 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
},
})
child.stdout.on('data', (chunk: Buffer) => this.onStdout(chunk))
+ // Pipe failures are emitted asynchronously by stdin, not by ChildProcess.
+ // A control client that exits during a write must only end this stream.
+ child.stdin.on('error', (error) => {
+ this.notifyClose(this.closed ? 'closed' : `tmux control input failed: ${error.message}`)
+ void this.close()
+ })
child.once('error', (error) => this.notifyClose(`tmux control client error: ${error.message}`))
child.once('close', (code) => this.notifyClose(this.closed ? 'closed' : `tmux control client exited (${code ?? 'signal'})`))
}
@@ -764,7 +770,9 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
// makes agent switching shrink and immediately re-expand the pane; TUIs
// such as Grok preserve those intermediate repaint fragments in the live
// screen. The next controller will resize only if its grid truly differs.
- try { this.child.stdin.write('detach-client\n') } catch { /* ignore */ }
+ if (this.child.stdin.writable) {
+ try { this.child.stdin.write('detach-client\n') } catch { /* ignore */ }
+ }
const exited = await new Promise<boolean>((resolve) => {
if (this.child.exitCode != null || this.child.signalCode != null) { resolve(true); return }
const timer = setTimeout(() => resolve(false), 500)