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 8-10: history, a new conversation in the pane, racing requests, and a Stop during start (#749)

Dee448758efe2ab
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index be0d87ab4..29037747b 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -14,8 +14,9 @@
// open until the next prompt, `!ask` asks the person which drink they would like in the engine's own
// dialog and answers with their choice, `!permit <command>` asks permission to run a command the way
// the engine does and runs it only if allowed, `!flood <KiB>` prints that much to the terminal, in
-// numbered lines, the way a build log or a long diff does, `!exit` ends the process. Everything else is
-// echoed as the answer.
+// numbered lines, the way a build log or a long diff does, `!clear` starts a new conversation in the
+// same pane as Claude Code's `/clear` and Codex's `/new` do, `!exit` ends the process. Everything else
+// is echoed as the answer.
import { randomUUID } from 'node:crypto'
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
@@ -52,9 +53,9 @@ export async function run(engine, config) {
const resumeAt = engine === 'claude' ? args.indexOf('--resume') : args.indexOf('resume')
const resumed = resumeAt >= 0 && args[resumeAt + 1] && !args[resumeAt + 1].startsWith('-') ? args[resumeAt + 1] : null
const fork = args.includes('--fork-session')
- const sessionId = resumed && !fork ? resumed : randomUUID()
+ let sessionId = resumed && !fork ? resumed : randomUUID()
const cwd = process.cwd()
- const transcript = engine === 'claude'
+ let transcript = engine === 'claude'
? join(config.claudeProjectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`)
: resumed && !fork && config.rolloutFor?.[resumed]
? config.rolloutFor[resumed]
@@ -174,6 +175,25 @@ export async function run(engine, config) {
const prompt = raw.trim()
if (!prompt) { draw(); return }
if (prompt === '!exit') { process.stdout.write('\x1b[?2004l\r\n'); process.exit(0) }
+ if (prompt === '!clear') {
+ // The old conversation ends (its open turn first), a new id and transcript begin, and the engine
+ // says both through its hooks, as the real CLIs do.
+ if (open) finish('(interrupted by a new conversation)')
+ await hook('session-end', { reason: 'clear' })
+ sessionId = randomUUID()
+ transcript = engine === 'claude'
+ ? join(config.claudeProjectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`)
+ : join(config.codexHome, 'sessions', '2026', '10', '03', `rollout-2026-10-03T00-00-00-${sessionId}.jsonl`)
+ mkdirSync(dirname(transcript), { recursive: true })
+ writeFileSync(transcript, '')
+ parent = null
+ turn = 0
+ if (engine === 'codex') codex('session_meta', { id: sessionId, cli_version: '0.159.0', cwd, source: 'cli' })
+ process.stdout.write('\r\n(new conversation)\r\n')
+ draw()
+ await hook('session-start', { hookEvent: 'SessionStart', source: 'clear' })
+ return
+ }
if (open) finish('(interrupted by a new prompt)')
turn++
open = `turn-${turn}`
diff --git a/cli/e2e/history.e2e.ts b/cli/e2e/history.e2e.ts
new file mode 100644
index 000000000..2b58c18fc
--- /dev/null
+++ b/cli/e2e/history.e2e.ts
@@ -0,0 +1,235 @@
+/**
+ * A thread's history read back page by page, for Claude Code and Codex, as a phone or the web scrolls
+ * it (`session_get` with a limit and a cursor): every message comes back exactly once and in order,
+ * whatever the page size, while turns are still being written, from two windows at once, across a
+ * daemon restart, across a resume and across a compaction. Requests that cannot be served are
+ * answered, never crashed on.
+ */
+import { mkdirSync, readdirSync, rmSync } 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']
+type Event = { type: string; payload: Record<string, any> }
+type Page = { events: Event[]; hasMore?: boolean; oldestCursor?: string | null; staleCursor?: boolean; error?: string }
+
+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
+}
+async function turns(client: LocalClient, agentId: string, from: number, to: number): Promise<void> {
+ for (let i = from; i <= to; i++) await turn(client, agentId, `question ${i}`)
+}
+const asked = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, i) => `question ${from + i}`)
+/** The fake engine numbers its answers by turn, so a resumed engine starts its count again. */
+const answered = (from: number, to: number, turnFrom = from) => asked(from, to).map((question, i) => `answer ${turnFrom + i}: ${question}`)
+
+/** The engine's own transcript files for a conversation, found where the fake engines write them. */
+function transcriptsOf(daemon: IsolatedDaemon, sessionId: string): string[] {
+ const found: string[] = []
+ const walk = (dir: string): void => {
+ let entries: ReturnType<typeof readdirSync<{ withFileTypes: true }>>
+ try { entries = readdirSync(dir, { withFileTypes: true }) as never } catch { return }
+ for (const entry of entries) {
+ const path = join(dir, String(entry.name))
+ if (entry.isDirectory()) walk(path)
+ else if (String(entry.name).endsWith('.jsonl') && String(entry.name).includes(sessionId)) found.push(path)
+ }
+ }
+ walk(join(daemon.root, 'claude'))
+ walk(join(daemon.root, 'codex'))
+ return found
+}
+
+const page = (client: LocalClient, sessionId: string, limit: unknown, before?: string): Promise<Page> =>
+ client.request<Page>('session_get', { sessionId, limit, ...(before ? { before } : {}) }, 60_000)
+
+/** Every page from the newest back to the first, as a client scrolling up collects them, oldest first. */
+async function thread(client: LocalClient, sessionId: string, limit: number, between?: (pageIndex: number) => Promise<void>) {
+ const pages: Page[] = []
+ let before: string | undefined
+ for (let n = 0; n < 2_000; n++) {
+ const next = await page(client, sessionId, limit, before)
+ expect(next.error, JSON.stringify(next)).toBeUndefined()
+ expect(next.staleCursor, `page ${n} (limit ${limit})`).toBeUndefined()
+ pages.unshift(next)
+ if (!next.hasMore || !next.oldestCursor) break
+ expect(next.oldestCursor, `page ${n} moves back`).not.toBe(before)
+ before = next.oldestCursor
+ await between?.(n)
+ }
+ const events = pages.flatMap((one) => one.events)
+ return {
+ pages: pages.length,
+ users: events.filter((event) => event.type === 'user_message').map((event) => String(event.payload.content)),
+ answers: events.filter((event) => event.type === 'text_delta').map((event) => String(event.payload.content)),
+ }
+}
+
+describe('a thread read back page by page', () => {
+ 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(-120).join('\n')}`) })
+ await d.start()
+ return d
+ }
+
+ it.each(engines)('%s: every message once and in order, whatever the page size', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `pages-${engine}`)
+ await turns(client, agent.id, 1, 30)
+ for (const limit of [1, 2, 7, 50, 500]) {
+ const read = await thread(client, agent.sessionId, limit)
+ expect(read.users, `limit ${limit}`).toEqual(asked(1, 30))
+ expect(read.answers, `limit ${limit}`).toEqual(answered(1, 30))
+ // A page's limit counts turns: one a page is a page a turn.
+ if (limit === 1) expect(read.pages).toBeGreaterThanOrEqual(30)
+ }
+ client.close()
+ })
+
+ it.each(engines)('%s: turns written while a client pages back leave the older pages as they were', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `paging-while-${engine}`)
+ await turns(client, agent.id, 1, 10)
+ let next = 11
+ // Between the first pages, the agent answers three more messages.
+ const read = await thread(client, agent.sessionId, 4, async (pageIndex) => {
+ if (pageIndex < 3) await turn(client, agent.id, `question ${next++}`)
+ })
+ expect(read.users).toEqual(asked(1, 10))
+ expect(read.answers).toEqual(answered(1, 10))
+ const again = await thread(client, agent.sessionId, 4)
+ expect(again.users).toEqual(asked(1, 13))
+ expect(again.answers).toEqual(answered(1, 13))
+ client.close()
+ })
+
+ it('two windows paging at once while the agent keeps working each read a whole thread, nothing missing or repeated', async () => {
+ const d = await fresh()
+ const writer = await LocalClient.connect(d)
+ const agent = await create(d, writer, 'codex', 'two-readers')
+ await turns(writer, agent.id, 1, 12)
+ const [first, second] = [await LocalClient.connect(d), await LocalClient.connect(d)]
+ let working = true
+ const working$ = (async () => { for (let i = 13; working && i <= 40; i++) await turn(writer, agent.id, `question ${i}`) })()
+ const [a, b] = await Promise.all([thread(first, agent.sessionId, 3), thread(second, agent.sessionId, 11)])
+ working = false
+ await working$
+ for (const read of [a, b]) {
+ // Whatever was written when the newest page was read, from the first message on: no gap, no repeat.
+ expect(read.users.length).toBeGreaterThanOrEqual(12)
+ expect(read.users).toEqual(asked(1, read.users.length))
+ expect(read.answers).toEqual(answered(1, read.answers.length))
+ expect(read.users.length - read.answers.length).toBeGreaterThanOrEqual(0)
+ expect(read.users.length - read.answers.length).toBeLessThanOrEqual(1)
+ }
+ for (const client of [writer, first, second]) client.close()
+ })
+
+ it.each(engines)('%s: a cursor taken before a daemon restart reads on after it', async (engine) => {
+ const d = await fresh()
+ let client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `cursor-restart-${engine}`)
+ await turns(client, agent.id, 1, 12)
+ const newest = await page(client, agent.sessionId, 6)
+ expect(newest.hasMore).toBe(true)
+ client.close()
+ await d.restart()
+ client = await LocalClient.connect(d)
+ await until('the agent to be back', async () => (await row(client, agent.id))?.status === 'active' || null, 60_000, 500)
+ const pages: Page[] = [newest]
+ let before = newest.oldestCursor ?? undefined
+ while (before) {
+ const older = await page(client, agent.sessionId, 6, before)
+ expect(older.staleCursor).toBeUndefined()
+ pages.unshift(older)
+ before = older.hasMore ? older.oldestCursor ?? undefined : undefined
+ }
+ const events = pages.flatMap((one) => one.events)
+ expect(events.filter((event) => event.type === 'user_message').map((event) => event.payload.content)).toEqual(asked(1, 12))
+ client.close()
+ })
+
+ it.each(engines)('%s: a resumed conversation reads back across the resume', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `resume-${engine}`)
+ await turns(client, agent.id, 1, 5)
+ expect((await client.request('agent_delete', { agentId: agent.id }, 60_000)).error).toBeUndefined()
+ await until('the agent to stop', async () => (await row(client, agent.id))?.status === 'stopped' || null, 45_000, 500)
+ expect((await client.request('agent_resume', { agentId: agent.id }, 90_000)).error).toBeUndefined()
+ await until('the agent to be back', async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' && now.sessionId === agent.sessionId ? now : null
+ }, 60_000, 500)
+ await turns(client, agent.id, 6, 10)
+ const read = await thread(client, agent.sessionId, 4)
+ expect(read.users).toEqual(asked(1, 10))
+ expect(read.answers).toEqual([...answered(1, 5), ...answered(6, 10, 1)])
+ client.close()
+ })
+
+ it.each(engines)('%s: a compaction in the middle of the thread pages through like any other record', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `compaction-${engine}`)
+ await turns(client, agent.id, 1, 4)
+ await turn(client, agent.id, '!grow 2')
+ await turns(client, agent.id, 6, 9)
+ const read = await thread(client, agent.sessionId, 3)
+ expect(read.users).toEqual([...asked(1, 4), '!grow 2', ...asked(6, 9)])
+ expect(read.answers).toEqual([...answered(1, 4), 'answer 5: !grow 2', ...answered(6, 9)])
+ client.close()
+ })
+
+ it('requests that cannot be served are answered, and the daemon goes on', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'claude', 'bad-pages')
+ await turns(client, agent.id, 1, 3)
+ expect((await client.request('session_get', {}, 30_000)).error).toBe('MISSING_SESSION_ID')
+ expect((await client.request('session_get', { sessionId: 'no-such-session', limit: 5 }, 30_000)).error).toBe('NOT_FOUND')
+ expect((await page(client, agent.sessionId, 5, 'a-cursor-from-nowhere')).staleCursor).toBe(true)
+ // Limits that make no sense read as no limit, as the most a page may ask for, or rounded down.
+ for (const limit of [0, -5, 'ten', 10_000, 2.5, null]) {
+ const answer = await page(client, agent.sessionId, limit)
+ expect(answer.error, `limit ${JSON.stringify(limit)}`).toBeUndefined()
+ expect(Array.isArray(answer.events), `limit ${JSON.stringify(limit)}`).toBe(true)
+ }
+ // No limit is the newest page's worth: here, the whole short thread.
+ expect((await page(client, agent.sessionId, null)).events.filter((event) => event.type === 'user_message').length).toBe(3)
+ // The transcript removed under the agent: the page is empty, not an error, and the agent goes on.
+ const files = transcriptsOf(d, agent.sessionId)
+ expect(files).toHaveLength(1)
+ rmSync(files[0])
+ const gone = await page(client, agent.sessionId, 5)
+ expect(gone.error, JSON.stringify(gone)).toBeUndefined()
+ await turn(client, agent.id, 'after the transcript went')
+ expect(client.closed).toBe(false)
+ client.close()
+ })
+})
diff --git a/cli/e2e/races.e2e.ts b/cli/e2e/races.e2e.ts
new file mode 100644
index 000000000..7b7028db7
--- /dev/null
+++ b/cli/e2e/races.e2e.ts
@@ -0,0 +1,190 @@
+/**
+ * Lifecycle requests that race each other, for Claude Code and Codex, on the real daemon: stopped while
+ * still starting, two restarts at once, two resumes at once, a stop during a restart, a restart while a
+ * message is being written, and two agents created in one folder at once. Whatever order they land in,
+ * every request is answered, an agent ends with one engine in one pane, and it takes the next message.
+ */
+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)
+async function folder(daemon: IsolatedDaemon, name: string): Promise<string> {
+ const cwd = join(daemon.projectsDir, name)
+ mkdirSync(cwd, { recursive: true })
+ return cwd
+}
+async function create(daemon: IsolatedDaemon, client: LocalClient, engine: Engine, name: string): Promise<Record<string, any>> {
+ const created = await client.request('agent_create', { engine, cwd: await folder(daemon, name), bypassPermission: true }, 90_000)
+ expect(created.error, `${name}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${name} 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
+}
+const active = (client: LocalClient, agentId: string, sessionId?: string) =>
+ until(`${agentId.slice(0, 8)} to be active`, async () => {
+ const now = await row(client, agentId)
+ return now?.status === 'active' && now.sessionId && (!sessionId || now.sessionId === sessionId) ? now : null
+ }, 60_000, 500)
+/** Engine processes in a pane: a pane must never end with two of them, or none while the agent is active. */
+async function engineProcesses(daemon: IsolatedDaemon, pane: string): Promise<number> {
+ const panePid = Number(await daemon.tmux.run('display-message', '-p', '-t', pane, '#{pane_pid}').catch(() => '0'))
+ if (!panePid) return 0
+ const { execFileSync } = await import('node:child_process')
+ const table = execFileSync('ps', ['-A', '-o', 'pid=,ppid=,command=']).toString().trim().split('\n')
+ .map((line) => line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/)).filter(Boolean) as RegExpMatchArray[]
+ const children = new Map<number, number[]>()
+ for (const [, pid, ppid] of table) children.set(Number(ppid), [...(children.get(Number(ppid)) ?? []), Number(pid)])
+ const tree = new Set<number>([panePid])
+ for (const pid of tree) for (const child of children.get(pid) ?? []) tree.add(child)
+ return table.filter(([, pid, , command]) => tree.has(Number(pid)) && /\b(claude|codex)\b/.test(command) && !/\bzsh\b|\bbash\b|\bsh -c\b/.test(command)).length
+}
+
+describe('lifecycle requests that race', () => {
+ 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: stopped while still starting, it stays stopped, and nothing binds it afterwards', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const created = await client.request('agent_create', { engine, cwd: await folder(d, `stop-starting-${engine}`), bypassPermission: true }, 90_000)
+ expect(created.error).toBeUndefined()
+ // Pressed while the engine is still starting: it used to be refused ("Try stopping again"), because
+ // the engine the agent launched was read as a replacement the moment it was identified.
+ const stopped = await client.request('agent_delete', { agentId: created.agent.id }, 60_000)
+ expect(stopped.error, JSON.stringify(stopped)).toBeUndefined()
+ await new Promise((resolve) => setTimeout(resolve, 5_000))
+ const all = await rows(client)
+ const mine = all.filter((agent) => agent.id === created.agent.id)
+ expect(mine).toHaveLength(1)
+ expect(mine[0].status).toBe('stopped')
+ // Nothing came back, and no second agent was minted for its pane.
+ expect(all.filter((agent) => agent.status === 'active')).toHaveLength(0)
+ client.close()
+ })
+
+ it.each(engines)('%s: two restarts at once leave one engine, and the agent takes the next message', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `double-restart-${engine}`)
+ const answers = await Promise.all([1, 2].map(() => client.request('agent_restart', { agentId: agent.id }, 90_000)))
+ for (const answer of answers) if (answer.error) expect(['AGENT_BUSY'], JSON.stringify(answer)).toContain(answer.error)
+ expect(answers.some((answer) => !answer.error), JSON.stringify(answers)).toBe(true)
+ const back = await active(client, agent.id, agent.sessionId)
+ await until('one engine in the pane', async () => (await engineProcesses(d, back.tmuxPane)) === 1 || null, 20_000, 250)
+ await turn(client, agent.id, 'after two restarts at once')
+ expect((await rows(client)).filter((one) => one.status === 'active')).toHaveLength(1)
+ client.close()
+ })
+
+ it.each(engines)('%s: two resumes at once resume it once', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `double-resume-${engine}`)
+ await turn(client, agent.id, 'before the stop')
+ expect((await client.request('agent_delete', { agentId: agent.id }, 60_000)).error).toBeUndefined()
+ await until('the agent to stop', async () => (await row(client, agent.id))?.status === 'stopped' || null, 45_000, 500)
+ const answers = await Promise.all([1, 2].map(() => client.request('agent_resume', { agentId: agent.id }, 90_000)))
+ for (const answer of answers) if (answer.error) expect(['AGENT_BUSY'], JSON.stringify(answer)).toContain(answer.error)
+ const back = await active(client, agent.id, agent.sessionId)
+ await until('one engine in the pane', async () => (await engineProcesses(d, back.tmuxPane)) === 1 || null, 20_000, 250)
+ expect((await rows(client)).filter((one) => one.status === 'active')).toHaveLength(1)
+ await turn(client, agent.id, 'after two resumes at once')
+ client.close()
+ })
+
+ it.each(engines)('%s: a stop that lands during a restart wins: the agent ends stopped, with no engine left running', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `stop-during-restart-${engine}`)
+ const restarting = client.request('agent_restart', { agentId: agent.id }, 90_000)
+ await new Promise((resolve) => setTimeout(resolve, 150))
+ const stopped = await client.request('agent_delete', { agentId: agent.id }, 90_000)
+ const restarted = await restarting
+ // Each is answered; which one wins depends on where the restart was, but the end state is coherent.
+ expect(restarted).toBeTruthy()
+ expect(stopped).toBeTruthy()
+ const settled = await until('the agent to settle', async () => {
+ const now = await row(client, agent.id)
+ return now && (now.status === 'stopped' || now.status === 'active') ? now : null
+ }, 60_000, 500)
+ if (!stopped.error) {
+ expect(settled.status).toBe('stopped')
+ await until('no engine left in the pane', async () => (await engineProcesses(d, agent.tmuxPane)) === 0 || null, 20_000, 250)
+ } else {
+ await turn(client, agent.id, 'the restart won')
+ }
+ client.close()
+ })
+
+ it.each(engines)('%s: a restart while a message is being written: the message is answered at most once, and the next one is', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `restart-mid-message-${engine}`)
+ const long = `a long message ${'with many words '.repeat(200)}`.trim()
+ client.send('message', { agentId: agent.id, content: long })
+ const restarted = await client.request('agent_restart', { agentId: agent.id }, 90_000)
+ expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()
+ await active(client, agent.id, agent.sessionId)
+ await turn(client, agent.id, 'the next message')
+ const page = await client.request<{ events: Array<{ type: string; payload: Record<string, any> }> }>('session_get', { sessionId: agent.sessionId, limit: 200 }, 30_000)
+ const users = page.events.filter((event) => event.type === 'user_message').map((event) => String(event.payload.content))
+ expect(users.filter((content) => content === long).length).toBeLessThanOrEqual(1)
+ expect(users.at(-1)).toBe('the next message')
+ // Nothing half-typed is left: no prompt made of the long message's tail and the next one.
+ expect(users.some((content) => content !== long && content.includes('with many words') && content.includes('the next message'))).toBe(false)
+ client.close()
+ })
+
+ it('two agents created in one folder at once are two agents, each with its own conversation', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const cwd = await folder(d, 'one-folder')
+ const created = await Promise.all((['claude', 'claude', 'codex', 'codex'] as const).map((engine) =>
+ client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)))
+ for (const one of created) expect(one.error, JSON.stringify(one)).toBeUndefined()
+ const ids = created.map((one) => one.agent.id as string)
+ expect(new Set(ids).size).toBe(4)
+ const bound = await Promise.all(ids.map((id) => active(client, id)))
+ expect(new Set(bound.map((agent) => agent.sessionId)).size).toBe(4)
+ expect(new Set(bound.map((agent) => agent.tmuxPane)).size).toBe(4)
+ await Promise.all(ids.map((id, i) => turn(client, id, `agent ${i} in the shared folder`)))
+ client.close()
+ })
+
+ it('a client that sends a restart and disconnects at once: the restart completes, and a new client sees it', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'claude', 'restart-and-go')
+ client.send('agent_restart', { requestId: 'fire-and-forget', agentId: agent.id })
+ client.close()
+ const other = await LocalClient.connect(d)
+ await active(other, agent.id, agent.sessionId)
+ await new Promise((resolve) => setTimeout(resolve, 2_000))
+ const back = await active(other, agent.id, agent.sessionId)
+ await until('one engine in the pane', async () => (await engineProcesses(d, back.tmuxPane)) === 1 || null, 20_000, 250)
+ await turn(other, agent.id, 'after a restart nobody waited for')
+ other.close()
+ })
+})
diff --git a/cli/e2e/rotation.e2e.ts b/cli/e2e/rotation.e2e.ts
new file mode 100644
index 000000000..2f1071fb9
--- /dev/null
+++ b/cli/e2e/rotation.e2e.ts
@@ -0,0 +1,145 @@
+/**
+ * A new conversation in the same pane, for Claude Code and Codex — Claude Code's `/clear`, Codex's
+ * `/new`: the engine ends one conversation and starts another without leaving the pane. The agent is
+ * the same agent, under the same id, bound to the new conversation; its turns are seen; it comes back
+ * bound to the new one after a restart, and resumes the new one after a stop.
+ */
+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)
+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<Frame> {
+ const started = client.next(isTurn('turn_started', agentId), 45_000, `turn_started (${content})`)
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ const frame = await started
+ await ended
+ return frame
+}
+/** Types the new-conversation command into the pane itself, as a person does. */
+async function newConversation(daemon: IsolatedDaemon, client: LocalClient, agent: Record<string, any>, from: string): Promise<Record<string, any>> {
+ await daemon.tmux.run('send-keys', '-t', agent.tmuxPane, '!clear', 'Enter')
+ return until('the agent to bind the new conversation', async () => {
+ const now = await row(client, agent.id)
+ return now?.sessionId && now.sessionId !== from && now.status === 'active' ? now : null
+ }, 30_000, 250)
+}
+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('a new conversation in the same pane', () => {
+ 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: the agent keeps its id, binds the new conversation, and its turns are seen', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `rotate-${engine}`)
+ await turn(client, agent.id, 'in the first conversation')
+ const rotated = await newConversation(d, client, agent, agent.sessionId)
+ expect(rotated.tmuxPane).toBe(agent.tmuxPane)
+ const started = await turn(client, agent.id, 'in the second conversation')
+ expect(started.payload?.userMessage).toBe('in the second conversation')
+ expect(await users(client, rotated.sessionId)).toEqual(['in the second conversation'])
+ // One agent for the pane, never a second minted beside it.
+ expect((await rows(client)).filter((one) => one.tmuxPane === agent.tmuxPane && one.status === 'active')).toHaveLength(1)
+ client.close()
+ })
+
+ it.each(engines)('%s: after a restart the agent is back on the new conversation', async (engine) => {
+ const d = await fresh()
+ let client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `rotate-restart-${engine}`)
+ await turn(client, agent.id, 'first')
+ const rotated = await newConversation(d, client, agent, agent.sessionId)
+ await turn(client, agent.id, 'second')
+ client.close()
+ await d.restart()
+ client = await LocalClient.connect(d)
+ const back = await until('the agent to be back', async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' ? now : null
+ }, 60_000, 500)
+ expect(back.sessionId).toBe(rotated.sessionId)
+ await turn(client, agent.id, 'third, after the restart')
+ expect(await users(client, rotated.sessionId)).toEqual(['second', 'third, after the restart'])
+ client.close()
+ })
+
+ it.each(engines)('%s: stopped and resumed after a new conversation, it resumes the new one', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `rotate-resume-${engine}`)
+ await turn(client, agent.id, 'first')
+ const rotated = await newConversation(d, client, agent, agent.sessionId)
+ await turn(client, agent.id, 'second')
+ expect((await client.request('agent_delete', { agentId: agent.id }, 60_000)).error).toBeUndefined()
+ await until('the agent to stop', async () => (await row(client, agent.id))?.status === 'stopped' || null, 45_000, 500)
+ expect((await client.request('agent_resume', { agentId: agent.id }, 90_000)).error).toBeUndefined()
+ const resumed = await until('the agent to be back', async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' && now.sessionId ? now : null
+ }, 60_000, 500)
+ expect(resumed.sessionId).toBe(rotated.sessionId)
+ await turn(client, agent.id, 'third, after the resume')
+ expect(await users(client, rotated.sessionId)).toEqual(['second', 'third, after the resume'])
+ client.close()
+ })
+
+ it.each(engines)('%s: a new conversation started in the middle of a turn ends that turn', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `rotate-mid-turn-${engine}`)
+ const started = client.next(isTurn('turn_started', agent.id), 30_000, 'turn_started')
+ client.send('message', { agentId: agent.id, content: '!hold' })
+ await started
+ await newConversation(d, client, agent, agent.sessionId)
+ await until('the agent to read as not working', async () => {
+ const now = await row(client, agent.id)
+ return now && now.activity?.state !== 'working' ? now : null
+ }, 30_000, 250)
+ await turn(client, agent.id, 'a fresh turn in the new conversation')
+ client.close()
+ })
+
+ it('two new conversations in a row: the agent follows both, and keeps its id', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'claude', 'rotate-twice')
+ const second = await newConversation(d, client, agent, agent.sessionId)
+ const third = await newConversation(d, client, second, second.sessionId)
+ expect(new Set([agent.sessionId, second.sessionId, third.sessionId]).size).toBe(3)
+ await turn(client, agent.id, 'in the third conversation')
+ expect(await users(client, third.sessionId)).toEqual(['in the third conversation'])
+ client.close()
+ })
+})
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
index 8f64f33f9..a1d8bbfec 100644
--- a/cli/src/lib/stopAgentService.spec.ts
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -131,6 +131,24 @@ it.each(['removed', 'replaced', 'conversation', 'route'] as const)('does not rem
expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
expect(deps.forgetSession).not.toHaveBeenCalled()
})
+it.each(['capture', 'termination'] as const)('stops an agent still starting when its engine is identified during %s', async stage => {
+ // Created, not yet bound to a process: the stop's snapshot has none.
+ row.processIdentity = null
+ const launched = { pid: 91, executable: 'codex', startMarker: 'launched' }
+ if (stage === 'capture') vi.mocked(captureResumeIdentity).mockImplementation(async session => { row.processIdentity = launched; return session })
+ else vi.mocked(terminateDeletedAgent).mockImplementation(async () => { row.processIdentity = launched; return 'terminated' })
+ await createStopAgentService(deps)(row.agentId)
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+ expect(deps.tmuxBackend!.kill).toHaveBeenCalledOnce()
+ // Identified before termination: that exact process is the one checked and signalled.
+ if (stage === 'capture') expect(vi.mocked(terminateDeletedAgent).mock.calls[0][0].processIdentity).toEqual(launched)
+})
+it('still refuses a starting agent whose pane or conversation changed under the stop', async () => {
+ row.processIdentity = null
+ vi.mocked(terminateDeletedAgent).mockImplementation(async () => { row.runtimes = [{ backend: 'tmux', paneId: '%89' }]; return 'gone' })
+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('changed while pausing')
+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
+})
it.each(['capture', 'termination'] as const)('accepts a hook rebuilding the same process during %s', async stage => {
const replacement = { ...row, title: 'Updated title',
processIdentity: { startMarker: 'fixture', executable: 'codex', pid: 77 },
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index 224645e48..b105b868a 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -43,9 +43,9 @@ export interface StopAgentOptions {
// Hooks rebuild registry objects. Compare stable values, never JavaScript object
// identity or property ordering, while retaining the exact PID-reuse guard.
-const runtimeIdentity = (entry: RegisteredSession | undefined) => entry ? JSON.stringify([
- entry.engine, entry.registeredAt, entry.processIdentity?.pid,
- entry.processIdentity?.executable, entry.processIdentity?.startMarker,
+const runtimeIdentity = (entry: RegisteredSession | undefined, withProcess = true) => entry ? JSON.stringify([
+ entry.engine, entry.registeredAt,
+ ...(withProcess ? [entry.processIdentity?.pid, entry.processIdentity?.executable, entry.processIdentity?.startMarker] : []),
entry.runtimes.map(terminalRouteKey).sort(),
]) : null
@@ -60,11 +60,16 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
const job = Promise.resolve().then(async () => {
const live = registry.resolve(sessionId)
if (!live) return
- const identity = runtimeIdentity(live)
+ // A row still starting has no process yet, and the one it gains while this stop runs is the engine
+ // it launched, not a replacement. Comparing it refused every Stop pressed on a starting agent with
+ // "Harness changed… Try stopping again" (e2e/races.e2e.ts). The process is still checked exactly
+ // before it is signalled; a row with no process at all is retired with its pane.
+ const starting = !live.processIdentity
+ const identity = runtimeIdentity(live, !starting)
const conversation = live.sessionId
const sameTarget = () => {
const current = registry.resolve(sessionId)
- return runtimeIdentity(current) === identity && (!conversation || current!.sessionId === conversation)
+ return runtimeIdentity(current, !starting) === identity && (!conversation || current!.sessionId === conversation)
}
const captured = await captureResumeIdentity({ ...live })
// Discovery or a hook may have updated this row while reading the native store.
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
index 523521c7a..fd8500692 100644
--- a/cli/src/lib/terminalAgentReconciler.spec.ts
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -262,6 +262,53 @@ describe('composite terminal reconciliation', () => {
expect(onRemoved).toHaveBeenCalledWith(agents[0], 'terminal runtime absent after 2 confirmed scans')
})
+ it('does not open an agent for a route that was held and released while the probe ran', async () => {
+ // A stop retiring a starting agent's pane holds its route and lets it go; a probe taken before it
+ // still saw the engine there, and opened a second agent for a pane that no longer existed.
+ const onDiscovered = vi.fn()
+ const route = terminalRouteKey(tmux)
+ let whileProbing: (() => void) | null = null
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [], backends: [], backendOrder: ['tmux'],
+ onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => {
+ whileProbing?.()
+ whileProbing = null
+ return probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }], [observed([tmux])])
+ },
+ })
+ whileProbing = () => { reconciler.holdRoute(route); reconciler.releaseRoute(route) }
+ await reconciler.trigger()
+ expect(onDiscovered).not.toHaveBeenCalled()
+ // Releasing a route nobody held changes nothing, and a probe that began afterwards speaks for it.
+ reconciler.releaseRoute(route)
+ await reconciler.trigger()
+ expect(onDiscovered).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not count a miss for an agent whose route changed hands while the probe ran', async () => {
+ const current = session([tmux])
+ const pane = { runtime: tmux, rootPid: 1, cwd: '/work' }
+ const route = terminalRouteKey(tmux)
+ let whileProbing: (() => void) | null = null
+ const onDormant = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved: vi.fn(),
+ probe: async () => {
+ whileProbing?.()
+ whileProbing = null
+ return probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [pane] } }])
+ },
+ })
+ await reconciler.trigger()
+ whileProbing = () => { reconciler.holdRoute(route); reconciler.releaseRoute(route) }
+ await reconciler.trigger()
+ expect(onDormant).not.toHaveBeenCalled()
+ await reconciler.trigger()
+ expect(onDormant).toHaveBeenCalledTimes(1)
+ })
+
it('keeps an agent active when pane-specific validation is inconclusive', async () => {
const current = session([tmux])
const onDormant = vi.fn()
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
index c5440205d..786406dd9 100644
--- a/cli/src/lib/terminalAgentReconciler.ts
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -110,6 +110,10 @@ export class TerminalAgentReconciler {
* finishes, so there is nothing to key a process-identity suppression on yet. */
private readonly heldRoutes = new Set<string>()
private readonly heldRouteTimers = new Map<string, NodeJS.Timeout>()
+ /** When each route was last held or released, as a sequence number, so a probe can tell a route
+ * that changed hands while it ran (see `reconcileOnce`). */
+ private routeSeq = 0
+ private readonly routeTouched = new Map<string, number>()
private pending = false
private inFlight: Promise<void> | null = null
private timer: NodeJS.Timeout | null = null
@@ -188,6 +192,7 @@ export class TerminalAgentReconciler {
*/
holdRoute(routeKey: string, autoReleaseMs = 30_000): void {
this.heldRoutes.add(routeKey)
+ this.routeTouched.set(routeKey, ++this.routeSeq)
const existing = this.heldRouteTimers.get(routeKey)
if (existing) clearTimeout(existing)
const timer = setTimeout(() => this.releaseRoute(routeKey), autoReleaseMs)
@@ -197,7 +202,7 @@ export class TerminalAgentReconciler {
/** Resume normal reconciliation for a route held by `holdRoute`. Idempotent. */
releaseRoute(routeKey: string): void {
- this.heldRoutes.delete(routeKey)
+ if (this.heldRoutes.delete(routeKey)) this.routeTouched.set(routeKey, ++this.routeSeq)
const timer = this.heldRouteTimers.get(routeKey)
if (timer) {
clearTimeout(timer)
@@ -205,8 +210,15 @@ export class TerminalAgentReconciler {
}
}
- private routeHeld(runtimes: readonly TerminalRuntimeRef[]): boolean {
- return runtimes.some((runtime) => this.heldRoutes.has(terminalRouteKey(runtime)))
+ /** Held now, or held or released since the probe numbered `probeSeq` began: that probe cannot speak
+ * for the route. A stop holds its agent's route while it retires the pane, and a probe taken before
+ * the stop, landing after it, otherwise opened a second agent for the engine it saw starting there
+ * (e2e/races.e2e.ts). */
+ private routeHeld(runtimes: readonly TerminalRuntimeRef[], probeSeq = this.routeSeq): boolean {
+ return runtimes.some((runtime) => {
+ const key = terminalRouteKey(runtime)
+ return this.heldRoutes.has(key) || (this.routeTouched.get(key) ?? 0) > probeSeq
+ })
}
trigger(): Promise<void> {
@@ -237,6 +249,10 @@ export class TerminalAgentReconciler {
processKey: currentProcessKey(agent),
placements: new Set(agent.runtimes.map(terminalPlacementKey)),
}]))
+ // Routes that change hands from here on are this probe's blind spot. Reconciliation is serial, so
+ // anything older matters to no probe still to come.
+ const probeSeq = this.routeSeq
+ for (const [key, seq] of this.routeTouched) if (seq <= probeSeq) this.routeTouched.delete(key)
const probe = await (this.deps.probe
? this.deps.probe(hints)
: probeTerminalAgents(
@@ -291,7 +307,7 @@ export class TerminalAgentReconciler {
// A restart in progress on this route: leave it untouched. The old process going dormant here
// and the new one being adopted by the discovery loop below are both races restart's `holdRoute`
// exists to prevent — see the class-level comment on `heldRoutes`.
- if (this.routeHeld(current.runtimes)) continue
+ if (this.routeHeld(current.runtimes, probeSeq)) continue
const processKey = currentProcessKey(current)
const observed = (processKey ? observedByProcess.get(processKey) : undefined)
?? unboundRouteObservation(current, probe.agents)
@@ -414,7 +430,7 @@ export class TerminalAgentReconciler {
if (matchedProcesses.has(key)) continue
// The replacement process for a restart in progress: the restart handler will bind it via
// `updateProcessIdentity` itself once confirmed, not through ordinary discovery.
- if (this.routeHeld(observed.runtimes)) continue
+ if (this.routeHeld(observed.runtimes, probeSeq)) continue
await this.deps.onDiscovered(observed)
}
}
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index 9870d410b..59527bb25 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -577,6 +577,17 @@ Found while mapping, and fixed on their own rather than inside a move:
agents' attaches run. The transcript's size is now noted where the engine's writing becomes live
(by a resume just before it launches the engine, and by the daemon at start for every conversation
it restores), and the first attach folds only up to it (`core/transcripts/relaunch.ts`).
+ - Part 18. History read back page by page (`e2e/history.e2e.ts`) returns every message once and
+ in order, whatever the page size: while turns are being written, from two windows at once,
+ across a daemon restart, a resume and a compaction. A new conversation in the same pane
+ (`e2e/rotation.e2e.ts`, Claude Code's `/clear` and Codex's `/new`) keeps the agent and its id,
+ and the agent comes back on the new conversation after a restart or a resume. Neither round
+ found a defect. Lifecycle requests that race (`e2e/races.e2e.ts`) found two, both in a Stop
+ pressed while an agent is still starting. The stop refused with "Try stopping again", because
+ the engine the agent launched, identified mid-stop, read as a replacement. And when it did go
+ through, a discovery probe taken before it opened a second agent for the engine it had seen
+ starting, on a pane that no longer existed. A stop now compares a row that had no process yet
+ without one. A probe is no longer evidence for a route held or released after it began.
## Testing