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.

refactor: extract retainExitedSession logic with tests and update engine exit handling

0xken15df08fd12ea2d
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 160a42a4c..d60a0404f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -87,6 +87,7 @@ import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from
import { createAndRegisterPane } from './lib/createAgentPane.js'
import { forkName, planFork } from './lib/forkAgent.js'
import { restoreAgents } from './lib/restoreAgents.js'
+import { createRetainExitedSession } from './lib/retainExitedSession.js'
import { repairClaudeCwd } from './lib/cwdRepair.js'
import { stoppedAgents } from './lib/stoppedAgents.js'
import { sweepWorktrees } from './lib/worktreeSweep.js'
@@ -2768,19 +2769,19 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
- /** Retain the conversation's identity; a surviving shell gets its own live identity. */
- const retainExitedSession = (entry: RegisteredSession, paneAlive: boolean): void => {
- stoppedAgents.save(entry)
- const saved = stoppedAgents.get(entry.agentId)!
- invalidateTerminalControl(entry.agentId)
- input.forget(entry.agentId)
- detachDsh(entry.agentId)
- const terminal = paneAlive ? registry.releaseEngine(entry.agentId, true) : null
- if (!paneAlive) registry.removeAgent(entry.agentId)
- syncRecapPool()
- void backend.publishStoppedAgent(saved).catch(error => console.warn('[resume] could not announce saved harness', error))
- if (terminal) announceSession(terminal, { device: false })
- }
+ const retainExitedSession = createRetainExitedSession({
+ stoppedAgents,
+ registry,
+ send: frame => backend.send(frame),
+ publishStoppedAgent: saved => backend.publishStoppedAgent(saved),
+ // A terminal is never the dial's business, and `syncSession` forces that for it anyway.
+ announceSession: session => announceSession(session, { device: false }),
+ invalidateTerminalControl,
+ forgetInput: agentId => input.forget(agentId),
+ detachDsh,
+ syncRecapPool,
+ warn: (message, error) => console.warn(message, error),
+ })
type RegisteredMeta = {
isNew: boolean
diff --git a/cli/src/lib/retainExitedSession.spec.ts b/cli/src/lib/retainExitedSession.spec.ts
new file mode 100644
index 000000000..6ab6b704b
--- /dev/null
+++ b/cli/src/lib/retainExitedSession.spec.ts
@@ -0,0 +1,85 @@
+import { describe, it, expect, vi } from 'vitest'
+import { createRetainExitedSession, type RetainExitedSessionDeps } from './retainExitedSession.js'
+import type { RegisteredSession } from './registry.js'
+
+const row = (over: Partial<RegisteredSession> = {}): RegisteredSession => ({
+ schemaVersion: 2, active: true, agentId: 'agent-a', sessionId: 'session-a', boundAt: 1,
+ engine: 'codex', gateway: null, grid: null, gridLaunch: null, gridWebSearch: null,
+ defaultName: 'harness Desktop', transcriptPath: '/tmp/rollout.jsonl', projectDir: 'demo',
+ cwd: '/tmp/demo', runtimes: [{ backend: 'tmux', paneId: '%7' }], primaryRuntimeKey: 'tmux\u0000%7',
+ tmuxPane: '%7', source: null, title: null, model: null, cliVersion: null, codexHome: null,
+ dsh: null, agent: null, processIdentity: null, registeredAt: 1, updatedAt: 1, lastHookAt: 1,
+ lastTranscriptAt: 1, ...over,
+} as RegisteredSession)
+
+function harness(over: Partial<RetainExitedSessionDeps> = {}) {
+ const frames: Array<{ type: string; payload: Record<string, unknown> }> = []
+ const calls: string[] = []
+ const archive = new Map<string, RegisteredSession>()
+ const shell = row({ agentId: 'agent-shell', engine: 'terminal', sessionId: '', defaultName: 'Terminal harness' })
+ const deps: RetainExitedSessionDeps = {
+ stoppedAgents: {
+ save: entry => { calls.push(`save:${entry.agentId}`); archive.set(entry.agentId, entry) },
+ get: agentId => archive.get(agentId) ?? null,
+ },
+ registry: {
+ releaseEngine: (agentId, separate) => { calls.push(`release:${agentId}:${separate}`); return shell },
+ removeAgent: agentId => { calls.push(`remove:${agentId}`); return true },
+ },
+ send: frame => { calls.push(`send:${frame.type}`); frames.push(frame) },
+ publishStoppedAgent: async saved => { calls.push(`publish:${saved.agentId}`) },
+ announceSession: session => { calls.push(`announce:${session.agentId}`) },
+ invalidateTerminalControl: agentId => calls.push(`control:${agentId}`),
+ forgetInput: agentId => calls.push(`input:${agentId}`),
+ detachDsh: agentId => calls.push(`dsh:${agentId}`),
+ syncRecapPool: () => calls.push('recap'),
+ warn: () => {},
+ ...over,
+ }
+ return { retain: createRetainExitedSession(deps), frames, calls, archive, shell }
+}
+
+describe('retainExitedSession', () => {
+ it('ends the identity that was running the engine so its views close, and keeps the surviving shell', () => {
+ const h = harness()
+ const entry = row()
+ h.retain(entry, true)
+
+ expect(h.frames).toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true } }])
+ // The archive exists BEFORE the client is told to go looking for it, and the ending reaches the
+ // client before the frame that is behind an await.
+ expect(h.calls.indexOf('save:agent-a')).toBeLessThan(h.calls.indexOf('send:agent_deleted'))
+ expect(h.calls.indexOf('send:agent_deleted')).toBeLessThan(h.calls.indexOf('publish:agent-a'))
+ expect(h.archive.get('agent-a')).toBe(entry)
+ expect(h.calls).toContain('release:agent-a:true')
+ expect(h.calls).not.toContain('remove:agent-a')
+ expect(h.calls).toContain('announce:agent-shell')
+ })
+
+ it('a pane that died with its engine leaves no shell, and its views close just the same', () => {
+ const h = harness()
+ h.retain(row(), false)
+
+ expect(h.frames).toEqual([{ type: 'agent_deleted', payload: { agentId: 'agent-a', retained: true } }])
+ expect(h.calls).toContain('remove:agent-a')
+ expect(h.calls.some(call => call.startsWith('release:'))).toBe(false)
+ expect(h.calls.some(call => call.startsWith('announce:'))).toBe(false)
+ expect(h.calls).toContain('publish:agent-a')
+ })
+
+ it('releases input, terminal control and the harness viewer before anything is announced', () => {
+ const h = harness()
+ h.retain(row(), true)
+ for (const call of ['control:agent-a', 'input:agent-a', 'dsh:agent-a']) {
+ expect(h.calls.indexOf(call)).toBeGreaterThanOrEqual(0)
+ expect(h.calls.indexOf(call)).toBeLessThan(h.calls.indexOf('send:agent_deleted'))
+ }
+ })
+
+ it('an archive that cannot be announced is warned about, never thrown at the caller', async () => {
+ const warn = vi.fn()
+ const h = harness({ publishStoppedAgent: () => Promise.reject(new Error('offline')), warn })
+ expect(() => h.retain(row(), true)).not.toThrow()
+ await vi.waitFor(() => expect(warn).toHaveBeenCalledTimes(1))
+ })
+})
diff --git a/cli/src/lib/retainExitedSession.ts b/cli/src/lib/retainExitedSession.ts
new file mode 100644
index 000000000..27dad2df1
--- /dev/null
+++ b/cli/src/lib/retainExitedSession.ts
@@ -0,0 +1,62 @@
+/**
+ * An engine that is no longer running, retained rather than lost.
+ *
+ * Reached from every place the daemon learns an engine process ended without anybody asking it to —
+ * the reconciler finding its pane empty, a restore or a create watcher meeting a pane whose engine
+ * exited, a resume that never came up — and it always does the same three things: save the
+ * conversation so it can be opened again, END THE IDENTITY THAT WAS RUNNING IT, and, when the tmux
+ * pane outlived the engine, keep that shell alive under an identity of its own.
+ *
+ * Extracted from cli.ts for the same reason as stopAgentService and restoreAgents: the ORDER of those
+ * steps is the part worth testing — the archive must exist before a client is told to look for it,
+ * and the ending must reach the client before the frame that is behind a filesystem await.
+ */
+import type { RegisteredSession } from './registry.js'
+
+export interface RetainExitedSessionDeps {
+ stoppedAgents: {
+ save(session: RegisteredSession): void
+ get(agentId: string): RegisteredSession | null
+ }
+ registry: {
+ releaseEngine(agentId: string, separateShell?: boolean): RegisteredSession | null
+ removeAgent(agentId: string): boolean
+ }
+ /** Web and desktop: `agent_deleted` closes this identity's views, `agent_synced` carries frames. */
+ send(frame: { type: string; payload: Record<string, unknown> }): void
+ /** The archive, announced to every client that lists saved harnesses (and removed from the dial). */
+ publishStoppedAgent(saved: RegisteredSession): Promise<void>
+ announceSession(session: RegisteredSession): void
+ invalidateTerminalControl(agentId: string): void
+ forgetInput(agentId: string): void
+ detachDsh(agentId: string): void
+ syncRecapPool(): void
+ warn(message: string, error: unknown): void
+}
+
+export function createRetainExitedSession(deps: RetainExitedSessionDeps) {
+ /** Retain the conversation's identity; a surviving shell gets its own live identity. */
+ return (entry: RegisteredSession, paneAlive: boolean): void => {
+ deps.stoppedAgents.save(entry)
+ const saved = deps.stoppedAgents.get(entry.agentId)!
+ deps.invalidateTerminalControl(entry.agentId)
+ deps.forgetInput(entry.agentId)
+ deps.detachDsh(entry.agentId)
+ // CLOSE THE VIEWS OF THE AGENT THAT JUST ENDED, the way a stop does.
+ //
+ // This identity has no runtime left: a surviving shell continues under a new one, and the
+ // conversation is now an archive to be opened. The `agent_synced` below says so, but a client
+ // treats that as a snapshot rather than a deletion — it cannot tell a real ending from the brief
+ // gap a process replacement leaves — so a tile left on this id sat on "terminal unavailable" with
+ // nothing to press, the shell it had been watching alive and typeable one identity away (#262).
+ // `retained` means here what it means in `forgetSession`: the row is archived, not gone, so the
+ // client re-reads its inventory and finds it among the saved harnesses. Sent BEFORE the archive
+ // frame, which is behind an await, so the view closes at once rather than a filesystem turn later.
+ deps.send({ type: 'agent_deleted', payload: { agentId: entry.agentId, retained: true } })
+ const terminal = paneAlive ? deps.registry.releaseEngine(entry.agentId, true) : null
+ if (!paneAlive) deps.registry.removeAgent(entry.agentId)
+ deps.syncRecapPool()
+ void deps.publishStoppedAgent(saved).catch(error => deps.warn('[resume] could not announce saved harness', error))
+ if (terminal) deps.announceSession(terminal)
+ }
+}
diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.ts
index 236a5e438..00f0f52d0 100644
--- a/cli/src/lib/sessionRepair.spec.ts
+++ b/cli/src/lib/sessionRepair.spec.ts
@@ -336,7 +336,10 @@ describe('claudeContinuation', () => {
JSON.stringify({ type: 'continued-in', sessionId: 'old-session', continuedInSessionId: newId }),
].join('\n') + '\n',
)
- writeFileSync(join(dir, `${newId}.jsonl`), `${JSON.stringify({ type: 'session', cwd: CWD, id: newId })}\n`)
+ writeFileSync(join(dir, `${newId}.jsonl`), [
+ JSON.stringify({ type: 'session', cwd: CWD, id: newId }),
+ JSON.stringify({ type: 'user', sessionId: newId, message: { role: 'user', content: 'carry on' } }),
+ ].join('\n') + '\n')
await expect(claudeContinuation(oldPath)).resolves.toEqual({
sessionId: newId,
@@ -369,7 +372,10 @@ describe('claudeContinuation', () => {
const lines = Array.from({ length: 50 }, () => filler)
lines.push(JSON.stringify({ type: 'continued-in', continuedInSessionId: newId }))
writeFileSync(oldPath, lines.join('\n') + '\n')
- writeFileSync(join(dir, `${newId}.jsonl`), `${JSON.stringify({ type: 'session', cwd: CWD, id: newId })}\n`)
+ writeFileSync(join(dir, `${newId}.jsonl`), [
+ JSON.stringify({ type: 'session', cwd: CWD, id: newId }),
+ JSON.stringify({ type: 'assistant', sessionId: newId, message: { role: 'assistant', content: 'hello' } }),
+ ].join('\n') + '\n')
await expect(claudeContinuation(oldPath)).resolves.toEqual({
sessionId: newId,
@@ -377,6 +383,51 @@ describe('claudeContinuation', () => {
})
})
+ it('does not follow the marker to a background session nobody has spoken in', async () => {
+ // `claude` writes the same marker when it moves a session to the BACKGROUND, and that file holds
+ // two bookkeeping lines forever while the conversation goes on in the original. Following it left
+ // the agent on an empty session, and Open then asked `--resume` for an id the CLI refuses because
+ // it is running in the background (#262 follow-up, measured on a real transcript).
+ const dir = tempRoot()
+ const oldPath = join(dir, 'old-session.jsonl')
+ const newId = '47a2bb52-5511-40ba-a9fb-8390572bc3de'
+ writeFileSync(oldPath, [
+ JSON.stringify({ type: 'user', sessionId: 'old-session', message: { role: 'user', content: 'hi' } }),
+ JSON.stringify({ type: 'continued-in', sessionId: 'old-session', continuedInSessionId: newId }),
+ ].join('\n') + '\n')
+ const background = join(dir, `${newId}.jsonl`)
+ writeFileSync(background, [
+ JSON.stringify({ type: 'ai-title', sessionId: newId, title: 'Merge PR' }),
+ JSON.stringify({ type: 'agent-name', sessionId: newId, name: 'harness Merge PR' }),
+ ].join('\n') + '\n')
+
+ await expect(claudeContinuation(oldPath)).resolves.toBeNull()
+
+ // The pass after its first turn lands binds it, so a real continuation is only ever deferred.
+ writeFileSync(background, [
+ JSON.stringify({ type: 'ai-title', sessionId: newId, title: 'Merge PR' }),
+ JSON.stringify({ type: 'user', sessionId: newId, message: { role: 'user', content: 'carry on' } }),
+ ].join('\n') + '\n')
+ await expect(claudeContinuation(oldPath)).resolves.toEqual({ sessionId: newId, transcriptPath: background })
+ })
+
+ it('follows a continuation whose first turn is past the bounded read', async () => {
+ // A rollover can open on a `file-history-snapshot` big enough to push the first turn out of the
+ // head this check reads. What it rules out is two short lines, so size alone answers for a file
+ // larger than the bound — the bound must never be the thing that refuses a real conversation.
+ const dir = tempRoot()
+ const oldPath = join(dir, 'old-session.jsonl')
+ const newId = 'c1d2e3f4-5511-40ba-a9fb-8390572bc3de'
+ writeFileSync(oldPath, `${JSON.stringify({ type: 'continued-in', continuedInSessionId: newId })}\n`)
+ const nextPath = join(dir, `${newId}.jsonl`)
+ writeFileSync(nextPath, [
+ JSON.stringify({ type: 'file-history-snapshot', sessionId: newId, blob: 'x'.repeat(300 * 1024) }),
+ JSON.stringify({ type: 'user', sessionId: newId, message: { role: 'user', content: 'carry on' } }),
+ ].join('\n') + '\n')
+
+ await expect(claudeContinuation(oldPath)).resolves.toEqual({ sessionId: newId, transcriptPath: nextPath })
+ })
+
it('returns null for a missing file', async () => {
await expect(claudeContinuation('/nonexistent/path/session.jsonl')).resolves.toBeNull()
})
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index b9ae503e4..e5ac9a625 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -407,6 +407,55 @@ async function tailBytes(path: string, maxBytes: number): Promise<string> {
}
const CLAUDE_CONTINUATION_TAIL_BYTES = 4 * 1024
+/** Enough of a continuation to see whether anybody ever spoke in it. Its first turn is within a few
+ * lines of the top — the records before it are bookkeeping (mode, file history, title, agent name). */
+const CLAUDE_CONTINUATION_HEAD_BYTES = 256 * 1024
+
+async function headBytes(path: string, maxBytes: number): Promise<string> {
+ const handle = await open(path, 'r')
+ try {
+ const length = Math.min((await handle.stat()).size, maxBytes)
+ if (length <= 0) return ''
+ const buffer = Buffer.alloc(length)
+ await handle.read(buffer, 0, length, 0)
+ return buffer.toString('utf-8')
+ } finally {
+ await handle.close()
+ }
+}
+
+/**
+ * Whether a transcript holds a CONVERSATION, rather than being the file Claude opens for a session
+ * nobody has spoken in yet.
+ *
+ * `claude` writes the same `continued-in` marker for a BACKGROUND session as for a rollover, and the
+ * file it points at then holds two bookkeeping lines (`ai-title`, `agent-name`) and never grows,
+ * while the real conversation goes on in the original file. Following that marker moved an agent onto
+ * an empty session: its tile went quiet, and the conversation archived when the engine exited was the
+ * empty one — Open then asked `claude --resume <background id>`, which the CLI refuses outright
+ * ("is running as a background session … run `claude attach`"). Measured on one machine: of nine
+ * `continued-in` markers, three named a background session and every one of those files had exactly
+ * these two lines and no turn.
+ */
+async function hasConversationTurn(path: string): Promise<boolean> {
+ let head: string
+ try {
+ head = await headBytes(path, CLAUDE_CONTINUATION_HEAD_BYTES)
+ } catch {
+ return false
+ }
+ for (const line of head.split('\n')) {
+ if (!line.trim() || (!line.includes('"user"') && !line.includes('"assistant"'))) continue
+ try {
+ const record = JSON.parse(line) as { type?: unknown }
+ if (record.type === 'user' || record.type === 'assistant') return true
+ } catch { /* a line cut by the read bound, or one this version does not know */ }
+ }
+ // Nothing in the head, but more file than we read: a continuation can open on a `file-history-snapshot`
+ // large enough to push the first turn past the bound, and the thing being ruled out is two short
+ // lines. Anything this size is a conversation, so the bound must never be what refuses one.
+ return head.length >= CLAUDE_CONTINUATION_HEAD_BYTES
+}
/**
* Claude rolls a long conversation's transcript over to a NEW file on its own (compaction, a resume
@@ -443,6 +492,10 @@ export async function claudeContinuation(transcriptPath: string): Promise<Repair
} catch {
return null
}
+ // A marker alone does not prove the conversation moved: the same one is written for a background
+ // session, whose file never holds a turn. Waiting for one costs nothing — this runs on every
+ // reconciler pass, so a continuation that is real binds on the pass after its first turn lands.
+ if (!await hasConversationTurn(nextPath)) return null
return { sessionId: nextId, transcriptPath: nextPath }
}
diff --git a/desktop/design/agent-lifecycle-map.md b/desktop/design/agent-lifecycle-map.md
index 141c00589..a8037581a 100644
--- a/desktop/design/agent-lifecycle-map.md
+++ b/desktop/design/agent-lifecycle-map.md
@@ -121,7 +121,7 @@ Evidence: [`notify.mjs`](../../cli/hook/notify.mjs),
| `agent_deleted` | Remove the row/view from the receiving client's live inventory. The `retained` flag tells desktop to reload the stopped catalog. | None. It is not itself a kill command or proof that the engine exited; terminal unavailability can also produce it. |
| `agent_renamed` | Update the Harness display name. | None; name/title mutation happened separately. |
-Natural engine exit sends `agent_synced` with `status: stopped` and no terminal route for the original identity. The separate shell is announced as a Terminal. Devices receive a deletion for the engine because they list live agents. Explicit Stop still sends `agent_deleted` with `retained: true`, so desktop closes its live views and refreshes the saved catalog.
+Natural engine exit ends the identity that ran the engine exactly as an explicit Stop does: `agent_deleted` with `retained: true`, so the desktop closes its live views and refreshes the saved catalog, followed by `agent_synced` with `status: stopped` and no terminal route for that identity. The separate shell is announced as a Terminal of its own, and the person opens it from the harness list if they want a view of it — a tile left pointing at the ended identity used to sit on "terminal unavailable" forever (#262). Devices receive the same deletion, because they list live agents.
## Cmd-P/T contract
diff --git a/desktop/test/stopped_harness_test.dart b/desktop/test/stopped_harness_test.dart
index bde84e443..cf3187e95 100644
--- a/desktop/test/stopped_harness_test.dart
+++ b/desktop/test/stopped_harness_test.dart
@@ -8,6 +8,7 @@ import 'package:harness/state/app_state.dart';
import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
+import 'package:harness/terminal/terminal_binary.dart';
import 'support/restart_connection.dart';
import 'swarm_interactions_test.dart' show chord;
@@ -58,6 +59,85 @@ void main() {
expect(connection.requests, isEmpty);
});
+ test(
+ 'an engine that exits into its shell closes the tile it was running in',
+ () async {
+ // Issue #262: Ctrl+C in a Codex tile. The conversation is archived under the identity that ran
+ // it, the surviving shell comes back as a terminal of its own, and the tile that was watching
+ // the engine must close rather than sit on "terminal unavailable" with nothing to press.
+ final pane = app.adoptSessionForTest(terminal('a0', <TerminalBinaryFrame>[]));
+ expect(app.panes, [pane]);
+ connection.inventory = Completer<Map<String, dynamic>>();
+
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'a0', 'retained': true},
+ });
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'a0',
+ 'name': 'Saved work',
+ 'engine': 'codex',
+ 'sessionId': 'exited-conversation',
+ 'status': 'stopped',
+ 'terminal': {'available': false},
+ },
+ },
+ });
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'shell-1',
+ 'name': 'Terminal harness',
+ 'engine': 'terminal',
+ 'terminal': {
+ 'available': true,
+ 'runtimes': [
+ {'backend': 'tmux', 'paneId': '%7'},
+ ],
+ },
+ },
+ },
+ });
+ connection.inventory!.complete({
+ 'agents': [
+ {
+ 'id': 'a0',
+ 'name': 'Saved work',
+ 'engine': 'codex',
+ 'sessionId': 'exited-conversation',
+ 'status': 'stopped',
+ 'terminal': {'available': false},
+ },
+ {
+ 'id': 'shell-1',
+ 'name': 'Terminal harness',
+ 'engine': 'terminal',
+ 'terminal': {
+ 'available': true,
+ 'runtimes': [
+ {'backend': 'tmux', 'paneId': '%7'},
+ ],
+ },
+ },
+ ],
+ });
+ await Future<void>.delayed(Duration.zero);
+
+ expect(app.allPanes, isEmpty);
+ final agents = app.stateOf('m')!.agents;
+ expect(agents.firstWhere((agent) => agent.id == 'a0').isStopped, isTrue);
+ expect(
+ agents.firstWhere((agent) => agent.id == 'shell-1').terminalAvailable,
+ isTrue,
+ );
+ expect(swarmDestinations(app).any((row) => row.agentId == 'a0'), isTrue);
+ },
+ );
+
test(
'a retained stop refreshes the saved row after closing its live view',
() async {