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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
End to end, round 7: the terminal stream, and a turn taken before the attach (#748)
Deed47ffd643aca
diff --git a/cli/e2e/harness/client.ts b/cli/e2e/harness/client.tsindex ced0e48f3..510bddb33 100644--- a/cli/e2e/harness/client.ts+++ b/cli/e2e/harness/client.ts@@ -1,22 +1,36 @@/*** A client that speaks to the daemon exactly as the desktop app does: the local WebSocket over the* daemon's Unix socket (or its loopback port), `machine_select`, request frames answered by- * `<type>_result`, and the event stream in between.+ * `<type>_result`, the event stream in between, and the terminals' binary frames beside it.*/import { randomUUID } from 'node:crypto'import WebSocket from 'ws'+import { decodeTerminalLocal, encodeTerminalLocal, type TerminalBinaryClear } from '../../src/lib/terminalBinary.js'import type { IsolatedDaemon } from './daemon.js'export type Frame = { type: string; payload?: Record<string, any>; [key: string]: unknown }export class LocalClient {readonly frames: Frame[] = []+ /** The terminals' binary frames (keyframes, output, sync), in the order they came. */+ readonly binaries: TerminalBinaryClear[] = []private waiters: Array<{ test: (frame: Frame) => boolean; done: (frame: Frame) => void }> = []+ private binaryWaiters: Array<{ test: (frame: TerminalBinaryClear) => boolean; done: (frame: TerminalBinaryClear) => void }> = []closed = false+ closeCode: number | null = nullprivate constructor(private readonly ws: WebSocket) {ws.on('message', (raw, binary) => {- if (binary) return+ if (binary) {+ const bytes = Array.isArray(raw) ? Buffer.concat(raw) : Buffer.from(raw as ArrayBuffer)+ const frame = decodeTerminalLocal(new Uint8Array(bytes))+ if (!frame) return+ this.binaries.push(frame)+ for (const waiter of [...this.binaryWaiters]) {+ if (waiter.test(frame)) { this.binaryWaiters.splice(this.binaryWaiters.indexOf(waiter), 1); waiter.done(frame) }+ }+ return+ }let frame: Frametry { frame = JSON.parse(raw.toString()) as Frame } catch { return }this.frames.push(frame)@@ -24,7 +38,7 @@ export class LocalClient {if (waiter.test(frame)) { this.waiters.splice(this.waiters.indexOf(waiter), 1); waiter.done(frame) }}})- ws.on('close', () => { this.closed = true })+ ws.on('close', (code) => { this.closed = true; this.closeCode = code })}static async connect(daemon: IsolatedDaemon, options: { tcp?: boolean; tool?: boolean } = {}): Promise<LocalClient> {@@ -46,6 +60,32 @@ export class LocalClient {this.ws.send(JSON.stringify({ type, payload }))}+ /** A terminal frame in the loopback wire format, as the desktop sends keystrokes and pastes. */+ sendBinary(frame: TerminalBinaryClear): void {+ const bytes = encodeTerminalLocal(frame)+ if (!bytes) throw new Error(`a terminal frame that cannot be encoded: ${JSON.stringify({ ...frame, bytes: frame.bytes.length })}`)+ this.ws.send(bytes, { binary: true })+ }++ /** Raw bytes on the socket, valid or not: what a broken or hostile client sends. */+ sendRaw(bytes: Uint8Array, binary: boolean): void {+ this.ws.send(bytes, { binary })+ }++ /** Resolves with the first binary frame, past or future, that passes `test`. */+ waitForBinary(test: (frame: TerminalBinaryClear) => boolean, ms = 20_000, what = 'a terminal frame', since = 0): Promise<TerminalBinaryClear> {+ const seen = this.binaries.slice(since).find(test)+ if (seen) return Promise.resolve(seen)+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ this.binaryWaiters = this.binaryWaiters.filter((waiter) => waiter.done !== done)+ reject(new Error(`timed out after ${ms}ms waiting for ${what}; ${this.binaries.length} terminal frames so far`))+ }, ms)+ const done = (frame: TerminalBinaryClear) => { clearTimeout(timer); resolve(frame) }+ this.binaryWaiters.push({ test, done })+ })+ }+/** Resolves with the first frame, past or future, that passes `test`. */waitFor(test: (frame: Frame) => boolean, ms = 20_000, what = 'a frame', since = 0): Promise<Frame> {const seen = this.frames.slice(since).find(test)diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex 4c55727f9..be0d87ab4 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -13,8 +13,9 @@// before answering (the transcripts that crashed the daemon on 2026-10-03), `!hold` leaves the turn// 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, `!exit` ends the process. Everything else is echoed as-// the answer.+// 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.import { randomUUID } from 'node:crypto'import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'import { dirname, join } from 'node:path'@@ -43,6 +44,10 @@ export async function run(engine, config) {return}process.title = engine+ // Raw at once, as the real CLIs are (Ink and ratatui take the terminal before they draw anything): a+ // terminal still in line mode keeps at most 1 KiB of a line, so a paste that arrived before the+ // engine was ready lost the rest of itself (measured: 1,018 of 2,406 characters).+ process.stdin.setRawMode?.(true)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@@ -204,6 +209,18 @@ export async function run(engine, config) {codex('response_item', { type: 'function_call_output', call_id: id, output: `ran ${directive[2]}` })}}+ if (directive?.[1] === 'flood') {+ // Numbered, so whoever reads the terminal can tell a lost, repeated or reordered line.+ const kib = Number(directive[2]) || 256+ let written = 0+ for (let line = 0; written < kib * 1024; line++) {+ const text = `flood ${String(line).padStart(7, '0')} ${'.'.repeat(80)}\r\n`+ process.stdout.write(text)+ written += text.length+ }+ finish(`flooded ${kib} KiB`)+ return+ }if (directive?.[1] === 'hold') returnif (directive?.[1] === 'permit') {const command = directive[2] || 'printf hi'@@ -254,7 +271,6 @@ export async function run(engine, config) {}// Raw input: bracketed paste brackets the text, Enter (\r) submits, Ctrl-C interrupts.- process.stdin.setRawMode?.(true)process.stdin.setEncoding('utf8')let buffer = ''let queue = Promise.resolve()diff --git a/cli/e2e/terminal.e2e.ts b/cli/e2e/terminal.e2e.tsnew file mode 100644index 000000000..7c8739f55--- /dev/null+++ b/cli/e2e/terminal.e2e.ts@@ -0,0 +1,478 @@+/**+ * The terminal, end to end, for Claude Code and Codex: the binary stream the desktop draws a pane from.+ * Opening one shows the engine's screen; keystrokes typed into it are a turn like any other; resizing+ * reflows it; one window takes a terminal from another, or watches it without taking it; a window that+ * goes, closes, freezes or floods its terminal costs only that stream, never the agent or the daemon.+ */+import { mkdirSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { TerminalBinaryKind, type TerminalBinaryClear } from '../src/lib/terminalBinary.js'+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 PROTOCOL = 3+const WELCOME: Record<Engine, string> = { claude: 'Welcome to Claude Code (fake)', codex: 'OpenAI Codex (fake)' }++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+}+const text = (bytes: Uint8Array) => Buffer.from(bytes).toString('utf8')++/** One terminal as a window holds it: its stream, what it has drawn, and the keystrokes it sent. */+class Terminal {+ private inputSeq = 0+ private constructor(readonly client: LocalClient, readonly agentId: string, readonly ready: Record<string, any>, private readonly since: number) {}++ get streamId(): string { return this.ready.streamId as string }+ get readOnly(): boolean { return this.ready.readOnly === true }++ /** Opens it, or rejects with the `terminal_error` code the daemon answered. */+ static async open(client: LocalClient, agentId: string, options: Record<string, unknown> = {}): Promise<Terminal> {+ const answer = await Terminal.answer(client, { agentId, cols: 100, rows: 30, ...options })+ if (answer.type !== 'terminal_ready') throw new Error(String(answer.payload?.code))+ return new Terminal(client, agentId, answer.payload!, client.binaries.length)+ }++ /** The frame `terminal_open` is answered with: `terminal_ready`, or `terminal_error` naming why. */+ static async answer(client: LocalClient, payload: Record<string, unknown>): Promise<Frame> {+ const requestId = `open-${Math.random().toString(36).slice(2)}`+ const answered = client.next((frame) => (frame.type === 'terminal_ready' || frame.type === 'terminal_error')+ && frame.payload?.requestId === requestId, 30_000, 'terminal_ready')+ client.send('terminal_open', { requestId, protocolVersion: PROTOCOL, ...payload })+ return answered+ }++ frames(): TerminalBinaryClear[] {+ return this.client.binaries.slice(this.since).filter((frame) => frame.streamId === this.streamId)+ }++ /** What the window would draw: the latest keyframe and the output after it. */+ screen(): string {+ const frames = this.frames()+ let start = -1+ for (let i = frames.length - 1; i >= 0; i--) if (frames[i].kind === TerminalBinaryKind.keyframe) { start = i; break }+ return frames.slice(Math.max(start, 0)).filter((frame) => frame.kind !== TerminalBinaryKind.sync).map((frame) => text(frame.bytes)).join('')+ }++ /** Every output byte since the stream opened, keyframes left out: the engine's writes, in order. */+ output(): string {+ return this.frames().filter((frame) => frame.kind === TerminalBinaryKind.output).map((frame) => text(frame.bytes)).join('')+ }++ keyframe(index = 0): Promise<TerminalBinaryClear> {+ return until(`keyframe ${index}`, () => this.frames().filter((frame) => frame.kind === TerminalBinaryKind.keyframe)[index] ?? null, 20_000, 50)+ }++ shows(what: string, ms = 20_000): Promise<string> {+ return until(`the terminal to show ${JSON.stringify(what)}`, () => { const now = this.screen(); return now.includes(what) ? now : null }, ms, 50)+ }++ /** Keystrokes, in frames of at most `chunk` bytes, numbered as the desktop numbers them. */+ type(keys: string, chunk = 8): void {+ const bytes = Buffer.from(keys, 'utf8')+ for (let offset = 0; offset < bytes.length; offset += chunk) {+ this.client.sendBinary({ kind: TerminalBinaryKind.input, streamId: this.streamId, seq: this.inputSeq++, compressed: false, bytes: bytes.subarray(offset, offset + chunk) })+ }+ }++ /** A keystroke frame with any seq at all: what a client whose counter drifted sends. */+ typeAt(seq: number, keys: string): void {+ this.client.sendBinary({ kind: TerminalBinaryKind.input, streamId: this.streamId, seq, compressed: false, bytes: Buffer.from(keys, 'utf8') })+ }++ paste(words: string): void {+ this.client.sendBinary({ kind: TerminalBinaryKind.paste, streamId: this.streamId, seq: 0, compressed: false, bytes: Buffer.from(words, 'utf8') })+ }++ /** Acknowledges everything drawn so far, as the renderer does once it has painted it. */+ ack(): void {+ const frames = this.frames()+ if (frames.length) this.client.send('terminal_ack', { streamId: this.streamId, lastSeq: frames[frames.length - 1].seq })+ }++ closed(ms = 20_000): Promise<Frame> {+ return this.client.waitFor((frame) => frame.type === 'terminal_closed' && frame.payload?.streamId === this.streamId, ms, 'terminal_closed')+ }++ error(code: string, ms = 20_000): Promise<Frame> {+ return this.client.waitFor((frame) => frame.type === 'terminal_error' && frame.payload?.code === code+ && (frame.payload?.streamId === undefined || frame.payload.streamId === this.streamId), ms, `terminal_error ${code}`)+ }+}++describe('the terminal', () => {+ 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+ }+ /** How many tmux clients are attached to the agent's pane: one per open stream, and none left over. */+ const attached = async (d: IsolatedDaemon, pane: string) => {+ const session = await d.tmux.run('display-message', '-p', '-t', pane, '#{session_name}')+ const clients = await d.tmux.run('list-clients', '-t', session).catch(() => '')+ return clients ? clients.split('\n').length : 0+ }++ it.each(engines)('%s: opening it shows the engine\'s screen, and what is typed into it is a turn', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `type-${engine}`)+ const terminal = await Terminal.open(client, agent.id)+ expect(terminal.readOnly).toBe(false)+ expect(terminal.ready.engineId).toBe(engine)+ const keyframe = await terminal.keyframe()+ expect(text(keyframe.bytes)).toContain(WELCOME[engine])+ expect([keyframe.cols, keyframe.rows]).toEqual([100, 30])++ const started = client.next(isTurn('turn_started', agent.id), 30_000, 'turn_started')+ const ended = client.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ terminal.type('typed into the terminal\r')+ expect((await started).payload?.userMessage).toBe('typed into the terminal')+ await ended+ await terminal.shows('answer 1: typed into the terminal')+ terminal.ack()+ // And the composer still works beside it: the same agent, the same conversation.+ await turn(client, agent.id, 'sent from the composer')+ await terminal.shows('answer 2: sent from the composer')+ client.close()+ })++ it.each(engines)('%s: keystrokes out of order type nothing and say which one was expected; JSON keystrokes are refused', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `order-${engine}`)+ const terminal = await Terminal.open(client, agent.id)+ await terminal.keyframe()+ terminal.typeAt(5, 'skipped ahead')+ const refused = await terminal.error('TERMINAL_INPUT_INVALID')+ expect(refused.payload).toMatchObject({ reason: 'seq', expectedSeq: 0 })+ client.send('terminal_input', { streamId: terminal.streamId, data: 'as json' })+ await terminal.error('TERMINAL_BINARY_REQUIRED')+ expect(await d.capture(agent.tmuxPane)).not.toMatch(/skipped ahead|as json/)+ // The counter realigns on what the daemon expects, and typing carries on.+ const ended = client.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ terminal.type('back in order\r')+ await ended+ await terminal.shows('answer 1: back in order')+ client.close()+ })++ it.each(engines)('%s: a paste lands whole, and Enter after it sends it', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `paste-${engine}`)+ const terminal = await Terminal.open(client, agent.id)+ await terminal.keyframe()+ const words = 'pasted ' + 'words '.repeat(400).trim()+ const started = client.next(isTurn('turn_started', agent.id), 30_000, 'turn_started')+ terminal.paste(words)+ await until('the paste to reach the composer', async () => (await d.capture(agent.tmuxPane)).includes('words words') || null, 15_000, 100)+ terminal.type('\r')+ expect((await started).payload?.userMessage).toBe(words)+ client.close()+ })++ it.each(engines)('%s: a resize reflows the pane and sends a fresh screen at the new size', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `resize-${engine}`)+ const terminal = await Terminal.open(client, agent.id)+ await terminal.keyframe()+ client.send('terminal_resize', { streamId: terminal.streamId, resizeSeq: 1, cols: 72, rows: 20 })+ const resized = await terminal.keyframe(1)+ expect([resized.cols, resized.rows]).toEqual([72, 20])+ expect(await d.tmux.run('display-message', '-p', '-t', agent.tmuxPane, '#{pane_width}x#{pane_height}')).toBe('72x20')+ // A stale resize (an older seq) is ignored; a size out of bounds is ignored; neither moves the pane.+ client.send('terminal_resize', { streamId: terminal.streamId, resizeSeq: 1, cols: 120, rows: 40 })+ client.send('terminal_resize', { streamId: terminal.streamId, resizeSeq: 2, cols: 0, rows: 9_999 })+ await turn(client, agent.id, 'after the resizes')+ expect(await d.tmux.run('display-message', '-p', '-t', agent.tmuxPane, '#{pane_width}x#{pane_height}')).toBe('72x20')+ client.close()+ })++ it('a second window takes the terminal over: the first is told who took it, and only the second types', async () => {+ const d = await fresh()+ const first = await LocalClient.connect(d)+ const second = await LocalClient.connect(d)+ const agent = await create(d, first, 'claude', 'takeover')+ const mine = await Terminal.open(first, agent.id, { client: { kind: 'desktop', name: 'First Mac' } })+ await mine.keyframe()+ const theirs = await Terminal.open(second, agent.id, { client: { kind: 'desktop', name: 'Second Mac' } })+ const lost = await mine.closed()+ expect(lost.payload).toMatchObject({ code: 'TERMINAL_TAKEN_OVER', takenBy: { name: 'Second Mac' } })+ expect(theirs.readOnly).toBe(false)+ await theirs.keyframe()+ // The first window's keystrokes name a stream that is gone: nothing reaches the pane.+ mine.type('from the first window\r')+ const ended = second.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ theirs.type('from the second window\r')+ await ended+ await theirs.shows('answer 1: from the second window')+ expect(await d.capture(agent.tmuxPane)).not.toContain('from the first window')+ expect(await attached(d, agent.tmuxPane)).toBe(1)+ first.close()+ second.close()+ })++ it('a window that asks not to take over watches instead: it sees the turn, and cannot type or resize', async () => {+ const d = await fresh()+ const desk = await LocalClient.connect(d)+ const phone = await LocalClient.connect(d)+ const agent = await create(d, desk, 'codex', 'watching')+ const driving = await Terminal.open(desk, agent.id, { client: { kind: 'desktop', name: 'Desk Mac' } })+ await driving.keyframe()+ const watching = await Terminal.open(phone, agent.id, { takeover: false })+ expect(watching.readOnly).toBe(true)+ expect(watching.ready.heldBy).toMatchObject({ name: 'Desk Mac' })+ await watching.keyframe()+ const ended = desk.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ driving.type('typed at the desk\r')+ await ended+ await watching.shows('answer 1: typed at the desk')+ // Both still hold their streams: watching took nothing from the desk.+ expect(desk.frames.some((frame) => frame.type === 'terminal_closed')).toBe(false)+ watching.type('typed by the watcher\r')+ phone.send('terminal_resize', { streamId: watching.streamId, resizeSeq: 1, cols: 50, rows: 15 })+ await watching.error('VIEW_ONLY')+ await turn(desk, agent.id, 'after the watcher tried')+ expect(await d.capture(agent.tmuxPane)).not.toContain('typed by the watcher')+ expect(await d.tmux.run('display-message', '-p', '-t', agent.tmuxPane, '#{pane_width}x#{pane_height}')).toBe('100x30')+ desk.close()+ phone.close()+ })++ it('one window holds four terminals at once, and each keystroke reaches only its own agent', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agents = []+ for (const [i, engine] of (['claude', 'codex', 'claude', 'codex'] as const).entries()) agents.push(await create(d, client, engine, `grid-${i}`))+ const terminals = await Promise.all(agents.map((agent) => Terminal.open(client, agent.id)))+ await Promise.all(terminals.map((terminal) => terminal.keyframe()))+ const ended = agents.map((agent) => client.next(isTurn('turn_ended', agent.id), 45_000, `turn_ended ${agent.id.slice(0, 8)}`))+ terminals.forEach((terminal, i) => terminal.type(`only for tile ${i}\r`, 3))+ await Promise.all(ended)+ for (const [i, terminal] of terminals.entries()) {+ await terminal.shows(`answer 1: only for tile ${i}`)+ for (const other of [0, 1, 2, 3].filter((j) => j !== i)) expect(terminal.output()).not.toContain(`only for tile ${other}`)+ }+ // Closing one leaves the other three working.+ client.send('terminal_close', { streamId: terminals[0].streamId })+ expect((await terminals[0].closed()).payload?.reason).toBe('client closed')+ const again = client.next(isTurn('turn_ended', agents[3].id), 45_000, 'turn_ended')+ terminals[3].type('still here\r')+ await again+ await terminals[3].shows('answer 2: still here')+ await until('the closed stream\'s tmux client to go', async () => (await attached(d, agents[0].tmuxPane)) === 0 || null, 5_000, 100)+ for (const agent of agents.slice(1)) expect(await attached(d, agent.tmuxPane)).toBe(1)+ client.close()+ })++ it('a window that goes without closing leaves no tmux client behind, and the next window opens cleanly', async () => {+ const d = await fresh()+ const gone = await LocalClient.connect(d)+ const agent = await create(d, gone, 'claude', 'gone-window')+ await (await Terminal.open(gone, agent.id)).keyframe()+ expect(await attached(d, agent.tmuxPane)).toBe(1)+ gone.close()+ await until('the stream\'s tmux client to go with its window', async () => (await attached(d, agent.tmuxPane)) === 0 || null, 15_000, 200)+ const next = await LocalClient.connect(d)+ const terminal = await Terminal.open(next, agent.id)+ expect(text((await terminal.keyframe()).bytes)).toContain(WELCOME.claude)+ expect(next.frames.some((frame) => frame.type === 'terminal_closed')).toBe(false)+ next.close()+ })++ it('a window that stops answering loses its stream after the heartbeat, and the agent goes on', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'codex', 'frozen-window')+ const terminal = await Terminal.open(client, agent.id)+ await terminal.keyframe()+ // No terminal_alive, no keystroke: the window is frozen. The socket itself stays up.+ const closed = await terminal.closed(50_000)+ expect(closed.payload?.reason).toBe('heartbeat timeout')+ expect(client.closed).toBe(false)+ await turn(client, agent.id, 'after the stream timed out')+ await (await Terminal.open(client, agent.id)).keyframe()+ client.close()+ }, 120_000)++ it('a window kept alive by its heartbeat keeps the stream past the timeout', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'claude', 'alive-window')+ const terminal = await Terminal.open(client, agent.id)+ await terminal.keyframe()+ const beat = setInterval(() => client.send('terminal_alive', { streamId: terminal.streamId }), 5_000)+ try {+ await new Promise((resolve) => setTimeout(resolve, 40_000))+ expect(client.frames.some((frame) => frame.type === 'terminal_closed')).toBe(false)+ // Syncs came while it was quiet, so the window knew the stream was live.+ expect(terminal.frames().some((frame) => frame.kind === TerminalBinaryKind.sync)).toBe(true)+ const ended = client.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ terminal.type('still mine\r')+ await ended+ } finally {+ clearInterval(beat)+ }+ client.close()+ }, 120_000)++ it.each(engines)('%s: a flood of output reaches a window that keeps up, every line in order', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `flood-${engine}`)+ const terminal = await Terminal.open(client, agent.id)+ await terminal.keyframe()+ const acking = setInterval(() => terminal.ack(), 20)+ try {+ await turn(client, agent.id, '!flood 1536')+ await terminal.shows('flooded 1536 KiB', 30_000)+ } finally {+ clearInterval(acking)+ }+ const lines = [...terminal.output().matchAll(/flood (\d{7}) /g)].map((match) => Number(match[1]))+ expect(lines.length).toBeGreaterThan(15_000)+ expect(lines.every((line, i) => line === i), 'a line lost, repeated or out of order').toBe(true)+ expect(client.frames.filter((frame) => frame.type === 'terminal_error')).toEqual([])+ client.close()+ })++ it('a window that stops drawing is cut off from a flood, alone: the agent, the daemon and other windows go on', async () => {+ const d = await fresh()+ const stuck = await LocalClient.connect(d)+ const other = await LocalClient.connect(d)+ const agent = await create(d, stuck, 'claude', 'stuck-renderer')+ const neighbour = await create(d, other, 'codex', 'neighbour')+ const frozen = await Terminal.open(stuck, agent.id)+ await frozen.keyframe()+ const fine = await Terminal.open(other, neighbour.id)+ await fine.keyframe()+ // The stuck window never acknowledges a frame, so its buffer fills and the daemon gives up on it.+ await turn(stuck, agent.id, '!flood 1536')+ const cut = await stuck.waitFor((frame) => frame.type === 'terminal_error'+ && ['TERMINAL_RENDER_STALLED', 'TERMINAL_OUTPUT_OVERFLOW'].includes(frame.payload?.code), 30_000, 'the stream cut off')+ expect(cut.payload?.streamId).toBe(frozen.streamId)+ await frozen.closed()+ expect(stuck.closed).toBe(false)+ const ended = other.next(isTurn('turn_ended', neighbour.id), 45_000, 'turn_ended')+ fine.type('the neighbour is unaffected\r')+ await ended+ await fine.shows('answer 1: the neighbour is unaffected')+ // Reopened, the stuck window gets the screen as it is now.+ const reopened = await Terminal.open(stuck, agent.id)+ expect(text((await reopened.keyframe()).bytes)).toContain('flooded 1536 KiB')+ expect(d.coresStarted()).toBe(1)+ stuck.close()+ other.close()+ })++ it('an agent stopped under an open terminal closes it, and once resumed it opens again', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'claude', 'stopped-under')+ const terminal = await Terminal.open(client, agent.id)+ await terminal.keyframe()+ const stopped = await client.request('agent_delete', { agentId: agent.id }, 60_000)+ expect(stopped.error, JSON.stringify(stopped)).toBeUndefined()+ await terminal.closed()+ const refused = await Terminal.answer(client, { agentId: agent.id, cols: 100, rows: 30 })+ expect(refused.type).toBe('terminal_error')+ const resumed = await client.request('agent_resume', { agentId: agent.id }, 90_000)+ expect(resumed.error, JSON.stringify(resumed)).toBeUndefined()+ const back = 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)+ const again = await Terminal.open(client, back.id)+ expect(text((await again.keyframe()).bytes)).toContain(WELCOME.claude)+ const ended = client.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ again.type('after the resume\r')+ await ended+ client.close()+ })++ it('a daemon restart under an open terminal: the window reconnects and the screen is still there', async () => {+ const d = await fresh()+ let client = await LocalClient.connect(d)+ const agent = await create(d, client, 'codex', 'daemon-restart')+ const terminal = await Terminal.open(client, agent.id)+ await terminal.keyframe()+ const ended = client.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ terminal.type('before the restart\r')+ await ended+ 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 again = await Terminal.open(client, agent.id)+ expect(text((await again.keyframe()).bytes)).toContain('answer 1: before the restart')+ const next = client.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ again.type('after the restart\r')+ await next+ await again.shows('answer 2: after the restart')+ client.close()+ })++ it('opens that cannot be served are answered with why, and leave nothing open', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'claude', 'bad-opens')+ const code = async (payload: Record<string, unknown>) => (await Terminal.answer(client, payload)).payload?.code+ expect(await code({ agentId: agent.id, cols: 100, rows: 30, protocolVersion: 2 })).toBe('TERMINAL_PROTOCOL_UNSUPPORTED')+ expect(await code({ agentId: 'no-such-agent', cols: 100, rows: 30 })).toBe('TERMINAL_AGENT_NOT_FOUND')+ expect(await code({ agentId: agent.id, cols: 0, rows: 30 })).toBe('TERMINAL_OPEN_INVALID')+ expect(await code({ agentId: agent.id, cols: 100, rows: 500 })).toBe('TERMINAL_OPEN_INVALID')+ expect(await code({ cols: 100, rows: 30 })).toBe('TERMINAL_OPEN_INVALID')+ expect(await attached(d, agent.tmuxPane)).toBe(0)+ // Frames naming a stream that does not exist do nothing at all.+ for (const type of ['terminal_ack', 'terminal_alive', 'terminal_resize', 'terminal_close', 'terminal_resync', 'terminal_scroll']) {+ client.send(type, { streamId: '00000000-0000-4000-8000-000000000000', lastSeq: 3, resizeSeq: 9, cols: 80, rows: 24, direction: 'up', lines: 3 })+ }+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId: '00000000-0000-4000-8000-000000000000', seq: 0, compressed: false, bytes: Buffer.from('ghost\r') })+ await turn(client, agent.id, 'after the bad opens')+ expect(await d.capture(agent.tmuxPane)).not.toContain('ghost')+ expect(client.closed).toBe(false)+ client.close()+ })++ it('a garbage binary frame ends only the connection that sent it', async () => {+ const d = await fresh()+ const good = await LocalClient.connect(d)+ const agent = await create(d, good, 'codex', 'garbage-frame')+ const terminal = await Terminal.open(good, agent.id)+ await terminal.keyframe()+ const bad = await LocalClient.connect(d)+ bad.sendRaw(Buffer.from('HTRL not really a terminal frame'), true)+ await until('the bad connection to be closed', () => bad.closed || null, 10_000, 50)+ expect(bad.closeCode).toBe(4400)+ const ended = good.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ terminal.type('the good window is fine\r')+ await ended+ expect(good.closed).toBe(false)+ good.close()+ })+})diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex d0f01b7f2..7a379e8ca 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -144,6 +144,7 @@ import { createAgyBackstop } from './core/turns/agyBackstop.js'import { createIngest } from './core/transcripts/ingest.js'import { createTurnHooks } from './core/turns/turnHooks.js'import { createAttach } from './core/transcripts/attach.js'+import { createRelaunchMarks, transcriptSize } from './core/transcripts/relaunch.js'import { createForgetSession } from './core/agents/forget.js'import { createBinding } from './core/agents/bind.js'import { createDiscoveryHandlers } from './core/agents/discovery.js'@@ -2011,6 +2012,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {})})+ // Where an engine's writing becomes live again after a resume or a daemon restart, read by the attach+ // that follows (core/transcripts/relaunch.ts).+ const relaunchMarks = createRelaunchMarks()// Following a session: its history read into its engine's normalizer, then its tail// (core/transcripts/attach.ts).const attach = createAttach({@@ -2030,6 +2034,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {devinHome: env.DEVIN_HOME,hermesDb: (s) => hermesDbForSession(s),concurrency: ATTACH_CONCURRENCY,+ relaunchMarks,})const attaches = attach.attachesconst attachSession = attach.attachSession@@ -3250,6 +3255,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {}watcher.start()await cursorDiscovery.start()+ // What a restored agent's engine writes from here on is live: the first attach of each folds its+ // conversation only up to this byte (core/transcripts/relaunch.ts). The request gate opens before+ // those attaches run, and a message answered in between was filed as history.+ for (const entry of registry.list()) {+ if (!entry.sessionId || !entry.transcriptPath || watcher.tails(entry.sessionId, entry.transcriptPath)) continue+ const offset = transcriptSize(entry.transcriptPath)+ if (offset !== null) relaunchMarks.note(entry.sessionId, offset)+ }// Panes that died while the daemon was down (a reboot takes the whole tmux server with it) are// rebuilt BEFORE the first reconcile pass: it would otherwise count them absent, and a second// pass five seconds later would drop the agents for good. Pane creation is awaited so the first@@ -3587,6 +3600,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {prepareSessionResume,refreshGridWebSearch,attachDsh,+ relaunchMarks,})const stopJobs = lifecycle.stopJobsconst stopAgent = lifecycle.stopAgentdiff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.tsindex fa4cef08b..9d85815ca 100644--- a/cli/src/core/agents/lifecycle.ts+++ b/cli/src/core/agents/lifecycle.ts@@ -37,12 +37,13 @@ export interface LifecycleDeps {prepareSessionResume: ResumeAgentServiceDeps['prepareSessionResume']refreshGridWebSearch: ResumeAgentServiceDeps['refreshGridWebSearch']attachDsh: ResumeAgentServiceDeps['attachDsh']+ relaunchMarks?: ResumeAgentServiceDeps['relaunchMarks']}export function createAgentLifecycle({registry, stoppedAgents, restartJobs, tmuxBackend, agentReconciler, forgetSession, markDeleted, clearDeleted,sessionCheckpoints, mirror, sessionSearch, send, pinnedControls, retainExitedSession, announceSession,- relaunchOverrides, prepareSessionResume, refreshGridWebSearch, attachDsh,+ relaunchOverrides, prepareSessionResume, refreshGridWebSearch, attachDsh, relaunchMarks,}: LifecycleDeps) {/*** Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live@@ -68,7 +69,7 @@ export function createAgentLifecycle({const resume = createResumeAgentService({registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,- refreshGridWebSearch, clearDeleted, attachDsh,+ refreshGridWebSearch, clearDeleted, attachDsh, relaunchMarks,})const resumeAgent: ResumeAgent = (id, permissionMode) => purgeAgentService.busy(id) || purgeAgentService.blocksFolder(stoppedAgents.get(id)?.cwd)? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resume(id, permissionMode)diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.tsindex 8b17f848e..2fc368aeb 100644--- a/cli/src/core/transcripts/attach.spec.ts+++ b/cli/src/core/transcripts/attach.spec.ts@@ -195,6 +195,25 @@ describe('attaching a session', () => {expect(await none.attach.attachSession(session('pi', transcript([{}])))).toBe(true)})+ it('folds a resumed conversation only up to where its relaunched engine began, and tails the rest live', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const take = vi.fn((_sessionId: string): number | undefined => undefined)+ const run = setup({ relaunchMarks: { take } })+ const history = JSON.stringify({ ...CLAUDE_PROMPT, uuid: 'before' })+ // The relaunched engine answered a message before this attach: a whole turn after the mark.+ const s = session('claude', transcript([history, { ...CLAUDE_PROMPT, uuid: 'after' }, { type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'hi' }], stop_reason: 'end_turn' }, uuid: 'a1' }]))+ const mark = Buffer.byteLength(history) + 1+ take.mockReturnValueOnce(mark)+ expect(await run.attach.attachSession(s)).toBe(true)+ expect(take).toHaveBeenCalledWith(s.sessionId)+ // The tail starts where the engine's own writing began, so its turn reaches every window live.+ expect(vi.mocked(run.deps.watcher.addSession).mock.calls[0][1]).toEqual({ fromOffset: mark })+ // A mark is for the next attach only: taken even by an attach that only makes sure the tail runs.+ take.mockReturnValueOnce(mark)+ expect(await run.attach.attachSession(s)).toBe(true)+ expect(take).toHaveBeenCalledTimes(2)+ })+it('takes over a tail it holds for a reset, resuming it where the read stopped', async () => {vi.spyOn(console, 'log').mockImplementation(() => {})const run = setup()diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.tsindex 68a351e6c..694c5b62d 100644--- a/cli/src/core/transcripts/attach.ts+++ b/cli/src/core/transcripts/attach.ts@@ -35,6 +35,7 @@ import type { RuntimeField, RuntimeProfileManager } from '../../lib/runtimeProfiimport { tailFile } from '../../lib/transcriptTail.js'import type { TailHold, Watcher } from '../../watcher/watcher.js'import type { SessionNormalizers } from './normalizers.js'+import type { RelaunchMarks } from './relaunch.js'export interface AttachDeps {validateTerminal: (session: RegisteredSession) => Promise<boolean>@@ -57,11 +58,13 @@ export interface AttachDeps {hermesDb: (session: RegisteredSession) => Promise<string>/** How many sessions attach at once. */concurrency: number+ /** Where an engine's writing became live again after a relaunch (core/transcripts/relaunch.ts): the fold stops there. */+ relaunchMarks?: Pick<RelaunchMarks, 'take'>}export function createAttach({validateTerminal, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,- announceTurnAborted, questionWatcher, terminalLabel, dbs, devinHome, hermesDb, concurrency,+ announceTurnAborted, questionWatcher, terminalLabel, dbs, devinHome, hermesDb, concurrency, relaunchMarks,}: AttachDeps) {const {turnStates, codexNormalizers, cursorNormalizers, opencodeReaders, kiloReaders, museNormalizers, ampNormalizers,@@ -111,6 +114,8 @@ export function createAttach({handover: { hold: TailHold | null; next: number | null } = { hold: null, next: null },): Promise<boolean> => {if (!await validateTerminal(session)) return false+ // Taken whichever way this attach goes: a mark is for the next attach of the conversation only.+ const relaunchedAt = relaunchMarks?.take(session.sessionId)if (!reset && normalizers.hasState(session.sessionId)) {if (session.transcriptPath) {const unseen = neverFoldedHistory.delete(session.sessionId)@@ -194,7 +199,7 @@ export function createAttach({profile: (line) => profile.ingest(line),fold: (line) => stream.push(line),observe,- }, { fromStart: live, end: handover.hold?.offset })+ }, { fromStart: live, end: handover.hold?.offset ?? relaunchedAt })if (handover.hold && (read.failed || handover.hold.expired)) {return keepLiveNormalizer(read.failed ? 'could not read the transcript' : 'outlasted its hold on the tail')}diff --git a/cli/src/core/transcripts/relaunch.spec.ts b/cli/src/core/transcripts/relaunch.spec.tsnew file mode 100644index 000000000..69cc5216b--- /dev/null+++ b/cli/src/core/transcripts/relaunch.spec.ts@@ -0,0 +1,50 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { createRelaunchMarks, transcriptSize } from './relaunch.js'++describe('relaunch marks', () => {+ it('gives the attach the byte the relaunched engine began at, once', () => {+ const marks = createRelaunchMarks()+ marks.note('conversation', 1457)+ expect(marks.size).toBe(1)+ expect(marks.take('conversation')).toBe(1457)+ expect(marks.take('conversation')).toBeUndefined()+ expect(marks.size).toBe(0)+ })++ it('has nothing for a conversation that was not relaunched', () => {+ expect(createRelaunchMarks().take('never')).toBeUndefined()+ })++ it('keeps the latest relaunch of a conversation', () => {+ const marks = createRelaunchMarks()+ marks.note('conversation', 10)+ marks.note('conversation', 20)+ expect(marks.take('conversation')).toBe(20)+ })++ it('reads a transcript\'s size, or nothing when there is no file', () => {+ const dir = mkdtempSync(join(tmpdir(), 'relaunch-'))+ try {+ writeFileSync(join(dir, 'session.jsonl'), '{"a":1}\n')+ expect(transcriptSize(join(dir, 'session.jsonl'))).toBe(8)+ expect(transcriptSize(join(dir, 'missing.jsonl'))).toBeNull()+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+ })++ it('drops a mark older than a resume can wait for', () => {+ let clock = 0+ const marks = createRelaunchMarks({ now: () => clock, maxAgeMs: 1_000 })+ marks.note('stale', 5)+ marks.note('fresh', 7)+ clock = 1_000+ expect(marks.take('fresh')).toBe(7)+ clock = 1_001+ expect(marks.take('stale')).toBeUndefined()+ expect(marks.size).toBe(0)+ })+})diff --git a/cli/src/core/transcripts/relaunch.ts b/cli/src/core/transcripts/relaunch.tsnew file mode 100644index 000000000..20b3e33c8--- /dev/null+++ b/cli/src/core/transcripts/relaunch.ts@@ -0,0 +1,53 @@+/**+ * Where an engine's writing becomes live again after a relaunch — of the engine, by a resume, or of the+ * daemon, by a restart.+ *+ * Either way the engine can take a turn before the daemon has attached its transcript: a resume waits+ * on the process to be confirmed, a restart opens its request gate before the restored agents' attaches+ * have run, and every attach waits its turn in the attach queue. The attach folds what is on disk as+ * history, so a turn the engine began and finished in that window reached no window as a turn — no+ * `turn_started`, no `turn_ended`, the answer only in history. Found end to end, both ways: a message+ * typed into an agent's terminal the moment it reopened after a resume, and after a daemon restart, was+ * answered and never seen (e2e/terminal.e2e.ts).+ *+ * So the transcript's size is noted where the engine's own writing begins: by a resume just before it+ * launches the engine, and by the daemon at start for every conversation it restores. The attach that+ * follows folds the conversation only up to that byte and tails from there, so what was written after+ * it is live. A mark is used once, by the next attach of that conversation; one older than a resume can+ * wait for (`RESUME_READINESS_BUDGET_MS`) belongs to an operation that is over and is not used.+ */+import { statSync } from 'node:fs'+import { RESUME_READINESS_BUDGET_MS } from '../../lib/resumeStoppedAgent.js'++/** A transcript's size now, or null when there is no file to tail. One stat: nothing for a launch to wait on. */+export function transcriptSize(path: string): number | null {+ try { return statSync(path).size } catch { return null }+}++export interface RelaunchMarkOptions {+ now?: () => number+ maxAgeMs?: number+}++export function createRelaunchMarks({ now = Date.now, maxAgeMs = RESUME_READINESS_BUDGET_MS }: RelaunchMarkOptions = {}) {+ const marks = new Map<string, { offset: number; at: number }>()+ return {+ /** Before the engine is launched: its own writing starts at `offset`. */+ note(sessionId: string, offset: number): void {+ marks.set(sessionId, { offset, at: now() })+ },+ /** At the attach: where the fold stops, once. */+ take(sessionId: string): number | undefined {+ const mark = marks.get(sessionId)+ if (!mark) return undefined+ marks.delete(sessionId)+ return now() - mark.at <= maxAgeMs ? mark.offset : undefined+ },+ /** How many marks are waiting for an attach — for tests and diagnostics. */+ get size(): number {+ return marks.size+ },+ }+}++export type RelaunchMarks = ReturnType<typeof createRelaunchMarks>diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.tsindex 0cb8bc429..35b4431c8 100644--- a/cli/src/lib/resumeAgentService.spec.ts+++ b/cli/src/lib/resumeAgentService.spec.ts@@ -103,6 +103,26 @@ describe('production resume handler', () => {expect(registry.byAgent(saved.agentId)?.permissionMode).toBe(permissionMode)})+ it('notes where the relaunched engine\'s writing begins, after the history is prepared and before the launch', async () => {+ writeFileSync(saved.transcriptPath!, '{"type":"session_meta"}\n')+ const note = vi.fn((_sessionId: string, _offset: number) => {+ // The pane is not allocated yet: the engine has written nothing of its own.+ expect(create).not.toHaveBeenCalled()+ })+ vi.mocked(deps.prepareSessionResume).mockImplementation(() => { writeFileSync(saved.transcriptPath!, '{"type":"session_meta"}\n{"prepared":true}\n') })+ deps = { ...deps, relaunchMarks: { note } }+ expect(await start()).toMatchObject({ ok: true, resumed: true })+ expect(note).toHaveBeenCalledWith(saved.sessionId, Buffer.byteLength('{"type":"session_meta"}\n{"prepared":true}\n'))+ })++ it('notes nothing for a conversation with no file to tail, or a file that is gone', async () => {+ const note = vi.fn()+ deps = { ...deps, relaunchMarks: { note } }+ // history.jsonl was never written: there is no byte to begin at.+ expect(await start()).toMatchObject({ ok: true, resumed: true })+ expect(note).not.toHaveBeenCalled()+ })+it('refuses an unsupported explicit permission choice before allocating a pane', async () => {rewrite({ engine: 'opencode', permissionMode: 'ask' })expect(await createResumeAgentService(deps)(saved.agentId, 'full')).toMatchObject({ error: 'INVALID_PERMISSION_MODE' })diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.tsindex cb09940ef..5529547d1 100644--- a/cli/src/lib/resumeAgentService.ts+++ b/cli/src/lib/resumeAgentService.ts@@ -1,4 +1,5 @@/** Exact-resume lifecycle shared by the daemon and its isolated acceptance tests. */+import { transcriptSize, type RelaunchMarks } from '../core/transcripts/relaunch.js'import { isTerminalEngine } from '../engines/types.js'import { installedDsh } from '../dsh/installed.js'import { engineKeepsTranscriptFile, registry as liveRegistry, validTranscriptPath, type RegisteredSession } from './registry.js'@@ -31,12 +32,14 @@ export interface ResumeAgentServiceDeps {refreshGridWebSearch(agentId: string, overrides: LaunchOverrides): voidclearDeleted(agentId: string): voidattachDsh(session: RegisteredSession): void+ /** Where the relaunched engine's own writing begins, for the attach that follows (core/transcripts/relaunch.ts). */+ relaunchMarks?: Pick<RelaunchMarks, 'note'>}export function createResumeAgentService(deps: ResumeAgentServiceDeps) {const { registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,- refreshGridWebSearch, clearDeleted, attachDsh } = deps+ refreshGridWebSearch, clearDeleted, attachDsh, relaunchMarks } = depsconst resumeConversations = new Set<string>()/** Same short form every other `[…]` line in the daemon logs uses. */const sid = (id: string) => id.slice(0, 8)@@ -199,6 +202,12 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {}}if (saved.sessionId && registry.bySession(saved.sessionId)) return { ok: false, error: 'AGENT_BUSY' }+ // Everything the engine writes from here on is its own, and live: the attach after it folds the+ // conversation only up to this byte. Taken after the history is prepared, which can rewrite it.+ if (resumeSessionId && saved.sessionId && saved.transcriptPath) {+ const offset = transcriptSize(saved.transcriptPath)+ if (offset !== null) relaunchMarks?.note(saved.sessionId, offset)+ }const { extraArgs, clearEnv } = built.overridesconst launchEnv = permissionMode === undefined ? built.overrides.env: harnessPermissionEnvironment(saved.engine, built.overrides.env, permissionMode)diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex f8c62691a..9870d410b 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -568,6 +568,15 @@ Found while mapping, and fixed on their own rather than inside a move:second agent for the same pane, and the first never bound. A scan now judges an agent only bywhat it could have seen: an agent created, a pane given to one, or an engine identified while theprobe ran is left to the next scan, and misses count against one engine identity at a time.+ - Part 17, found by the seventh round (`e2e/terminal.e2e.ts`, the terminal stream for both engines:+ open, type, paste, resize, take over and watch, four terminals on one connection, a window that+ goes, freezes or floods, a stopped and resumed agent, a daemon restart, bad opens and garbage+ frames): a turn an engine took before the daemon attached its transcript was filed as history,+ and reached no window as a turn. It happened after a resume, to a message typed the moment the+ terminal reopened, and after a daemon restart, whose request gate opens before the restored+ 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`).## Testing