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.

End to end, rounds 13-14: input that must never reach a shell, a client that stops reading, and forks (#753)

Dee5d72625c36cf
diff --git a/cli/e2e/forks.e2e.ts b/cli/e2e/forks.e2e.ts
new file mode 100644
index 000000000..a3416483a
--- /dev/null
+++ b/cli/e2e/forks.e2e.ts
@@ -0,0 +1,132 @@
+/**
+ * Forks at their edges, for Claude Code and Codex: asked for in the middle of a turn, a fork of a fork, a
+ * source stopped under its fork, and both coming back after a daemon restart. A fork is its own agent
+ * with its own conversation from the moment it exists; nothing one does reaches the other.
+ */
+import { mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+type Engine = 'claude' | 'codex'
+const engines: Engine[] = ['claude', 'codex']
+
+const rows = async (client: LocalClient) =>
+ (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents
+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)
+const bound = (client: LocalClient, agentId: string) =>
+ until(`${agentId.slice(0, 8)} to bind its conversation`, async () => {
+ const agent = await row(client, agentId)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+async function create(daemon: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Record<string, any>> {
+ const cwd = join(daemon.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return bound(client, created.agent.id)
+}
+async function fork(client: LocalClient, agentId: string, name: string): Promise<Record<string, any>> {
+ const forked = await client.request('agent_fork', { agentId, name }, 90_000)
+ expect(forked.error, JSON.stringify(forked)).toBeUndefined()
+ const forkId: string = forked.agent?.id ?? forked.agentId ?? forked.session?.agentId
+ expect(forkId).toBeTruthy()
+ return bound(client, forkId)
+}
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ await ended
+}
+const users = async (client: LocalClient, sessionId: string): Promise<string[]> => {
+ const page = await client.request<{ events?: Array<{ type: string; payload: Record<string, any> }>; error?: string }>('session_get', { sessionId, limit: 200 }, 30_000)
+ expect(page.error, JSON.stringify(page)).toBeUndefined()
+ return (page.events ?? []).filter((event) => event.type === 'user_message').map((event) => String(event.payload.content))
+}
+
+describe('forks at their edges', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+ const fresh = async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await d.start()
+ return d
+ }
+
+ it.each(engines)('%s: a fork asked for in the middle of a turn is refused with why, the turn goes on, and after it the fork is made', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const source = await create(d, client, engine, `fork-mid-turn-${engine}`)
+ await turn(client, source.id, 'before the fork')
+ const ended = client.next(isTurn('turn_ended', source.id), 45_000, 'the source turn_ended')
+ client.send('message', { agentId: source.id, content: '!slow 3000' })
+ await client.next(isTurn('turn_started', source.id), 30_000, 'the source turn_started')
+ // Forking copies the conversation, and a turn half written is not one to copy.
+ const refused = await client.request('agent_fork', { agentId: source.id, name: 'too early' }, 90_000)
+ expect(refused.error, JSON.stringify(refused)).toBe('AGENT_BUSY')
+ expect(String(refused.detail)).toContain('middle of a turn')
+ await ended
+ const child = await fork(client, source.id, 'after the turn')
+ expect(child.sessionId).not.toBe(source.sessionId)
+ await turn(client, child.id, 'in the fork')
+ await turn(client, source.id, 'in the source')
+ expect(await users(client, child.sessionId)).not.toContain('in the source')
+ expect(await users(client, source.sessionId)).not.toContain('in the fork')
+ expect((await rows(client)).filter((agent) => agent.status === 'active')).toHaveLength(2)
+ client.close()
+ })
+
+ it.each(engines)('%s: a fork of a fork is a third agent with a third conversation', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const first = await create(d, client, engine, `fork-of-fork-${engine}`)
+ await turn(client, first.id, 'the first conversation')
+ const second = await fork(client, first.id, 'second')
+ await turn(client, second.id, 'the second conversation')
+ const third = await fork(client, second.id, 'third')
+ expect(new Set([first.sessionId, second.sessionId, third.sessionId]).size).toBe(3)
+ expect(new Set([first.tmuxPane, second.tmuxPane, third.tmuxPane]).size).toBe(3)
+ await Promise.all([first, second, third].map((agent, i) => turn(client, agent.id, `turn in agent ${i}`)))
+ client.close()
+ })
+
+ it.each(engines)('%s: the source stopped under its fork: the fork goes on, and the source resumes its own conversation', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const source = await create(d, client, engine, `fork-stop-source-${engine}`)
+ await turn(client, source.id, 'before the fork')
+ const child = await fork(client, source.id, 'the fork')
+ expect((await client.request('agent_delete', { agentId: source.id }, 60_000)).error).toBeUndefined()
+ await until('the source to stop', async () => (await row(client, source.id))?.status === 'stopped' || null, 45_000, 500)
+ await turn(client, child.id, 'the fork after the source stopped')
+ expect((await row(client, child.id))?.status).toBe('active')
+ expect((await client.request('agent_resume', { agentId: source.id }, 90_000)).error).toBeUndefined()
+ const back = await bound(client, source.id)
+ expect(back.sessionId).toBe(source.sessionId)
+ await turn(client, source.id, 'the source after its resume')
+ client.close()
+ })
+
+ it.each(engines)('%s: after a daemon restart the source and its fork are both back, each on its own conversation', async (engine) => {
+ const d = await fresh()
+ let client = await LocalClient.connect(d)
+ const source = await create(d, client, engine, `fork-restart-${engine}`)
+ await turn(client, source.id, 'before the fork')
+ const child = await fork(client, source.id, 'the fork')
+ await turn(client, child.id, 'the fork before the restart')
+ client.close()
+ await d.restart()
+ client = await LocalClient.connect(d)
+ const [sourceBack, childBack] = await Promise.all([source, child].map((agent) => until(`${agent.id.slice(0, 8)} back`, async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' && now.sessionId === agent.sessionId ? now : null
+ }, 60_000, 500)))
+ expect(sourceBack.tmuxPane).not.toBe(childBack.tmuxPane)
+ await Promise.all([source, child].map((agent) => turn(client, agent.id, `after the restart in ${agent.id.slice(0, 8)}`)))
+ client.close()
+ })
+})
diff --git a/cli/e2e/harness/client.ts b/cli/e2e/harness/client.ts
index 510bddb33..7150add06 100644
--- a/cli/e2e/harness/client.ts
+++ b/cli/e2e/harness/client.ts
@@ -112,6 +112,11 @@ export class LocalClient {
return (await answer).payload as T
}
+ /** Stops reading the socket, as a client that hangs does: the daemon's writes back up behind it. */
+ pauseReading(): void {
+ (this.ws as unknown as { _socket?: { pause(): void } })._socket?.pause()
+ }
+
close(): void {
try { this.ws.close() } catch { /* already closed */ }
}
diff --git a/cli/e2e/input-safety.e2e.ts b/cli/e2e/input-safety.e2e.ts
new file mode 100644
index 000000000..6e695f9d8
--- /dev/null
+++ b/cli/e2e/input-safety.e2e.ts
@@ -0,0 +1,124 @@
+/**
+ * What a message must never do, for Claude Code and Codex: reach the shell an exited engine leaves in
+ * its pane, where it would run as a command. And what a client must never cost the others: one that
+ * stops reading is cut off, alone, and the daemon's memory stays bounded while it is.
+ */
+import { existsSync, mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+type Engine = 'claude' | 'codex'
+const engines: Engine[] = ['claude', 'codex']
+
+const row = async (client: LocalClient, agentId: string) =>
+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)
+ .find((agent) => agent.id === agentId)
+async function create(daemon: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Record<string, any>> {
+ const cwd = join(daemon.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+}
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ await ended
+}
+/** A message that, typed into a shell, leaves a file behind: the proof it ran as a command. */
+const command = (marker: string) => `touch ${marker}`
+
+describe('what a message must never do', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+ const fresh = async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await d.start()
+ return d
+ }
+
+ it.each(engines)('%s: a message to an agent whose engine exited is refused, and nothing reaches the shell in its pane', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `exited-${engine}`)
+ client.send('message', { agentId: agent.id, content: '!exit' })
+ await until('the engine to be gone', async () => (await row(client, agent.id))?.status !== 'active' || null, 30_000, 250)
+ const marker = join(d.root, `pwned-after-exit-${engine}`)
+ client.send('message', { agentId: agent.id, content: command(marker) })
+ await new Promise((resolve) => setTimeout(resolve, 4_000))
+ expect(existsSync(marker), 'the message ran as a shell command').toBe(false)
+ client.close()
+ })
+
+ it.each(engines)('%s: a message right behind the one that makes the engine exit never runs in the shell', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `exit-race-${engine}`)
+ await turn(client, agent.id, 'a turn first')
+ const marker = join(d.root, `pwned-race-${engine}`)
+ // Back to back: the engine exits on the first, and the second is already on its way.
+ client.send('message', { agentId: agent.id, content: '!exit' })
+ client.send('message', { agentId: agent.id, content: command(marker) })
+ await new Promise((resolve) => setTimeout(resolve, 6_000))
+ expect(existsSync(marker), 'the second message ran as a shell command').toBe(false)
+ client.close()
+ })
+
+ it.each(engines)('%s: keystrokes queued for a terminal whose engine exited are the person\'s own to send', async (engine) => {
+ // The terminal is a terminal: what a person types into the pane goes to whatever runs there. The
+ // composer is what must never type into a shell; this pins that the two stay apart.
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `terminal-after-exit-${engine}`)
+ client.send('message', { agentId: agent.id, content: '!exit' })
+ await until('the engine to be gone', async () => (await row(client, agent.id))?.status !== 'active' || null, 30_000, 250)
+ const marker = join(d.root, `typed-by-hand-${engine}`)
+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, command(marker), 'Enter')
+ await until('the shell to run what was typed by hand', () => existsSync(marker) || null, 10_000, 100)
+ client.close()
+ })
+})
+
+describe('what a client must never cost the others', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+ it('a client that stops reading is cut off alone, and memory stays bounded while it lasts', async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-80).join('\n')}`) })
+ await d.start()
+ const driver = await LocalClient.connect(d)
+ const agents = [await create(d, driver, 'claude', 'slow-reader-a'), await create(d, driver, 'codex', 'slow-reader-b')]
+ const stuck = await LocalClient.connect(d)
+ const before = await d.rssMiB()
+ // It stops reading: its socket buffer fills and everything after waits in the daemon for it.
+ stuck.pauseReading()
+ const words = 'many words in a long answer '.repeat(2_000)
+ const started = Date.now()
+ let rounds = 0
+ // The daemon says when it cuts a connection off for silence; only the stuck one can be.
+ const cutOff = () => d.log().includes('— terminating')
+ while (!cutOff() && Date.now() - started < 90_000) {
+ await Promise.all(agents.map((agent) => turn(driver, agent.id, `${rounds} ${words}`)))
+ rounds++
+ driver.frames.splice(0, driver.frames.length)
+ }
+ const peak = await d.rssMiB()
+ expect(cutOff(), `the stuck client was never cut off (${rounds} rounds)`).toBe(true)
+ expect(Date.now() - started).toBeLessThan(80_000)
+ expect(peak - before, `rss ${before.toFixed(1)} → ${peak.toFixed(1)} MiB over ${rounds} rounds`).toBeLessThan(200)
+ // The client that kept reading never noticed.
+ await Promise.all(agents.map((agent) => turn(driver, agent.id, 'after the stuck client went')))
+ expect(d.coresStarted()).toBe(1)
+ driver.close()
+ }, 180_000)
+})
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
index 231f4696a..710419aa5 100644
--- a/cli/src/lib/sessionInput.ts
+++ b/cli/src/lib/sessionInput.ts
@@ -704,7 +704,6 @@ export class SessionInputController {
return
}
state.retries++
- console.log(`[inject] ${sid(sessionId)} resubmit Enter · engine=${session.engine} · retry=${state.retries}/${SUBMIT_MAX_RETRIES}`)
const valid = await this.deps.validateRuntime(session)
if (!valid) {
this.finishDelivery(sessionId, state, 'unknown', 'runtime_gone_post_paste')
@@ -715,6 +714,9 @@ export class SessionInputController {
return
}
if (state.deliveryId && (this.states.get(sessionId) !== state || !state.awaitingFingerprint || state.turnOpen)) return
+ // Said once the engine is known to be there: an engine that exited gets no Enter, and the log used
+ // to claim one anyway.
+ console.log(`[inject] ${sid(sessionId)} resubmit Enter · engine=${session.engine} · retry=${state.retries}/${SUBMIT_MAX_RETRIES}`)
// Only the submit key is retried. The prompt body is never pasted twice.
const delivery = await this.deps.sendKey(session.agentId, 'Enter')
state.ambiguousDispatch = typeof delivery === 'boolean'
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index 50fbd39c1..f195cd123 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -599,6 +599,13 @@ Found while mapping, and fixed on their own rather than inside a move:
question still open across a restart. Kept as it is, for now: a question's id is named from
its dialog so that it survives a restart. So a dialog asked again word for word has the same id,
and an answer delayed past the first one could land on the repeat.
+ - Part 20. Rounds 13 and 14 found no defect, and pin what had no end-to-end test before.
+ `e2e/input-safety.e2e.ts`: a message never reaches the shell an exited engine leaves in its
+ pane, including one sent right behind the message that makes the engine exit (refused by the
+ pre-paste check); typing by hand in the terminal still goes to the shell; a client that stops
+ reading is cut off alone within the 40 s heartbeat, with memory bounded meanwhile.
+ `e2e/forks.e2e.ts`: a fork asked for mid-turn is refused with the reason, then made after it;
+ a fork of a fork; a source stopped under its fork; both back after a restart.
## Testing