Skip to content

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

fix(cli): preserve panes during daemon startup (#566)

Dee3d087336101f
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index cc3f543fa..8343f5279 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -146,6 +146,7 @@ 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 { createSessionSync } from './lib/sessionSync.js'
import { CloseAgentService, inspectCloseActivity } from './lib/closeAgentService.js'
import { OpenTabProtection } from './lib/openTabProtection.js'
import { sessionCheckpoints } from './lib/sessionCheckpoint.js'
@@ -2006,27 +2007,18 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (!daemons.on()) return null
try { return runtimeLessons(lessonStore, workspace) } catch { return null }
}
- const syncSession = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {
- // A terminal is not the dial's business (see `deviceAgentRow`): it is never upserted there, and
- // the one time it must be REMOVED from there — the engine it adopted has exited — the caller
- // sends that `agent_deleted` itself, because this row is still very much alive for the app.
- if (isTerminalEngine(s.engine)) opts = { ...opts, device: false }
- if (!registry.terminalAvailable(s.agentId)) {
- pairSensor.removed(s.agentId)
- lessonSignals.forget(s.agentId)
- backendRef?.send({ type: 'agent_deleted', payload: { agentId: s.agentId } })
- if (opts.device !== false) backendRef?.sendCommander({ type: 'agent_deleted', payload: { agentId: s.agentId } })
- return
- }
- if (s.launch?.state === 'failed') pairSensor.failed(s.agentId, s.launch.detail ?? s.launch.error)
- void projectFrame(s, runtimeProfiles.selectedModel(s))
- .then((project) => {
- const frame = { type: 'agent_synced', payload: { agent: project } }
- backendRef?.send(frame)
- if (opts.device !== false) backendRef?.sendCommander(frame)
- })
- .catch((err) => console.error('[cli] announceSession failed:', err instanceof Error ? err.message : err))
- }
+ const syncSession = createSessionSync({
+ terminalAvailable: (agentId) => registry.terminalAvailable(agentId),
+ project: (s) => projectFrame(s, runtimeProfiles.selectedModel(s)),
+ send: (frame) => backendRef?.send(frame),
+ sendCommander: (frame) => backendRef?.sendCommander(frame),
+ onUnavailable: (agentId) => {
+ pairSensor.removed(agentId)
+ lessonSignals.forget(agentId)
+ },
+ onFailed: (agentId, detail) => pairSensor.failed(agentId, detail),
+ warn: (err) => console.error('[cli] announceSession failed:', err instanceof Error ? err.message : err),
+ })
const announceRename = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {
if (isTerminalEngine(s.engine)) opts = { ...opts, device: false }
const name = projectDisplayName(s)
diff --git a/cli/src/lib/sessionSync.spec.ts b/cli/src/lib/sessionSync.spec.ts
new file mode 100644
index 000000000..d56e17e32
--- /dev/null
+++ b/cli/src/lib/sessionSync.spec.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it, vi } from 'vitest'
+import { agentFrame } from './agentFrame.js'
+import { registry, type RegisteredSession } from './registry.js'
+import { createSessionSync, type SessionSyncDeps } from './sessionSync.js'
+
+function row(overrides: Partial<RegisteredSession> = {}): RegisteredSession {
+ return {
+ schemaVersion: 2, active: true, agentId: 'agent-a', sessionId: 'session-a', boundAt: 1,
+ engine: 'codex', transcriptPath: null, projectDir: 'demo', cwd: null,
+ runtimes: [{ backend: 'tmux', paneId: '%16' }], primaryRuntimeKey: 'tmux\u0000%16', tmuxPane: '%16',
+ source: null, title: null, model: null, cliVersion: null, processIdentity: null,
+ registeredAt: 1, touchedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ ...overrides,
+ }
+}
+
+function harness(overrides: Partial<SessionSyncDeps> = {}) {
+ const deps = {
+ terminalAvailable: () => true,
+ project: vi.fn((session: RegisteredSession) => agentFrame(session, { selectedModel: null, terminalAvailable: true })),
+ send: vi.fn(),
+ sendCommander: vi.fn(),
+ onUnavailable: vi.fn(),
+ onFailed: vi.fn(),
+ warn: vi.fn(),
+ ...overrides,
+ }
+ return { ...deps, sync: createSessionSync(deps) }
+}
+
+describe('session sync', () => {
+ it('keeps an existing pane through registry reload, early metadata sync, and terminal rediscovery', async () => {
+ registry.load()
+ const opened = registry.openProcessAgent({
+ agentId: 'restart-agent', engine: 'codex', tmuxPane: '%16',
+ processIdentity: { pid: 42, executable: 'codex', startMarker: 'test-process' },
+ })!.entry
+ const h = harness({ terminalAvailable: (agentId) => registry.terminalAvailable(agentId) })
+ await h.sync(opened)
+ expect(h.send).toHaveBeenCalledTimes(1)
+
+ // A daemon restart forgets verification, not the pane or the process. Title/profile updates
+ // can arrive before discovery verifies that saved terminal locator again.
+ registry.load()
+ const restored = registry.byAgent(opened.agentId)!
+ expect(restored).toBeDefined()
+ expect(registry.terminalAvailable(restored.agentId)).toBe(false)
+ await h.sync(restored)
+ expect(h.send).toHaveBeenCalledTimes(1)
+ expect(h.sendCommander).toHaveBeenLastCalledWith({
+ type: 'agent_deleted', payload: { agentId: opened.agentId },
+ })
+
+ registry.setTerminalAvailable(restored.agentId, true)
+ await h.sync(restored)
+ expect(h.send).toHaveBeenCalledTimes(2)
+ for (const [frame] of vi.mocked(h.send).mock.calls) {
+ expect(frame).toMatchObject({ type: 'agent_synced', payload: { agent: { id: opened.agentId, terminal: { available: true } } } })
+ }
+ expect(h.warn).not.toHaveBeenCalled()
+ })
+
+ it.each([undefined, false])('does not close app panes for an unverified terminal (device=%s)', async (device) => {
+ const h = harness({ terminalAvailable: () => false })
+ await h.sync(row(), { device })
+ expect(h.send).not.toHaveBeenCalled()
+ expect(h.project).not.toHaveBeenCalled()
+ expect(h.onUnavailable).toHaveBeenCalledWith('agent-a')
+ expect(h.sendCommander).toHaveBeenCalledTimes(device === false ? 0 : 1)
+ })
+
+ it.each([true, false])('keeps plain terminals out of the dial (available=%s)', async (available) => {
+ const h = harness({ terminalAvailable: () => available })
+ await h.sync(row({ engine: 'terminal' }))
+ expect(h.send).toHaveBeenCalledTimes(available ? 1 : 0)
+ expect(h.sendCommander).not.toHaveBeenCalled()
+ })
+
+ it('honors app-only updates for a verified agent', async () => {
+ const h = harness()
+ await h.sync(row(), { device: false })
+ expect(h.send).toHaveBeenCalledWith(expect.objectContaining({ type: 'agent_synced' }))
+ expect(h.sendCommander).not.toHaveBeenCalled()
+ })
+
+ it('preserves launch-failure reporting and contains projection errors', async () => {
+ const error = new Error('projection failed')
+ const h = harness({ project: vi.fn().mockRejectedValue(error) })
+ await h.sync(row({ launch: { state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal.' } }))
+ expect(h.onFailed).toHaveBeenCalledWith('agent-a', 'See terminal.')
+ expect(h.warn).toHaveBeenCalledWith(error)
+ expect(h.send).not.toHaveBeenCalled()
+ expect(h.sendCommander).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/lib/sessionSync.ts b/cli/src/lib/sessionSync.ts
new file mode 100644
index 000000000..80903defc
--- /dev/null
+++ b/cli/src/lib/sessionSync.ts
@@ -0,0 +1,40 @@
+import { isTerminalEngine } from '../engines/types.js'
+import type { AgentFrame } from './agentFrame.js'
+import type { RegisteredSession } from './registry.js'
+
+export interface SessionSyncDeps {
+ terminalAvailable(agentId: string): boolean
+ project(session: RegisteredSession): Promise<AgentFrame>
+ send(frame: { type: string; payload: Record<string, unknown> }): void
+ sendCommander(frame: { type: string; payload: Record<string, unknown> }): void
+ onUnavailable(agentId: string): void
+ onFailed(agentId: string, detail: string): void
+ warn(error: unknown): void
+}
+
+/** Publish registry updates to the app and the dial without treating a liveness hint as an ending. */
+export function createSessionSync(deps: SessionSyncDeps) {
+ return async (session: RegisteredSession, opts: { device?: boolean } = {}): Promise<void> => {
+ // Plain terminals never appear on the dial. When an engine exits into a shell, the caller
+ // removes the old dial row explicitly while keeping the shell available to the app.
+ const device = opts.device !== false && !isTerminalEngine(session.engine)
+ if (!deps.terminalAvailable(session.agentId)) {
+ deps.onUnavailable(session.agentId)
+ // load() clears terminal verification at every daemon start. Metadata can sync before
+ // discovery restores it, so an app deletion here would permanently remove a live pane
+ // from the shared desk. Only confirmed removal/retirement may send that deletion.
+ // The dial still lists only usable agents; discovery will upsert this one when verified.
+ if (device) deps.sendCommander({ type: 'agent_deleted', payload: { agentId: session.agentId } })
+ return
+ }
+ if (session.launch?.state === 'failed') deps.onFailed(session.agentId, session.launch.detail ?? session.launch.error)
+ try {
+ const agent = await deps.project(session)
+ const frame = { type: 'agent_synced', payload: { agent } }
+ deps.send(frame)
+ if (device) deps.sendCommander(frame)
+ } catch (error) {
+ deps.warn(error)
+ }
+ }
+}