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
Fix closing retained terminal panes marked inactive (#724)
Deefedb172ce6b6
diff --git a/cli/package.json b/cli/package.jsonindex d4ab5a574..550a734ca 100644--- a/cli/package.json+++ b/cli/package.json@@ -23,7 +23,7 @@"test:sharing-e2e": "tsx scripts/share-harness-e2e.ts","test:remote-viewers": "vitest run --config vitest.viewer.config.ts","test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",- "test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts src/lib/engineShellStartup.spec.ts src/lib/restartDiscovery.real.spec.ts --reporter=verbose",+ "test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts src/lib/engineShellStartup.spec.ts src/lib/restartDiscovery.real.spec.ts src/lib/terminalClose.real.spec.ts --reporter=verbose","test:resume": "vitest run src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume","test:resume-native": "tsx scripts/resume-native-e2e.ts","test:portability": "vitest run --config vitest.portability.config.ts"diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex a2d8dfbbd..8c8babbe3 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -4699,9 +4699,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {const screen = await captureTerminal(s.agentId, 80)return inspectCloseActivity(s, screen, sessionTurnState(s.sessionId), openQuestions.has(s.sessionId))},- checkpoint: async (s, phase) => sessionCheckpoints.save(s, {- screen: phase === 'before' ? await captureTerminal(s.agentId, 2000) : null,- }),+ checkpoint: async (s, phase) => {+ const captured = phase === 'before' ? await terminals.captureRetained(s, { historyLines: 2000 }) : null+ await sessionCheckpoints.save(s, { screen: captured?.state === 'succeeded' ? captured.value : null })+ },stop: stopAgent,changed: announceSession,})diff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.tsindex 62d933d82..5aee42394 100644--- a/cli/src/lib/terminalBackendCoordinator.spec.ts+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts@@ -133,6 +133,40 @@ describe('TerminalBackendCoordinator', () => {expect(coordinator.leaseIsCurrent(acquired.value, current)).toBe(true)})+ it.each(['terminal', 'claude'] as const)('captures a retained %s pane without enabling dormant engine controls', async engine => {+ const tmuxBackend = backend('tmux:default', vi.fn())+ tmuxBackend.capture = vi.fn(async () => ({ state: 'succeeded' as const, value: 'saved screen' }))+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])+ const current = { ...session(), engine, active: false }+ await expect(coordinator.capture(current)).resolves.toMatchObject({ state: 'failed' })+ await expect(coordinator.acquireLease(current)).resolves.toMatchObject({ state: 'failed' })+ await expect(coordinator.validate(current)).resolves.toMatchObject({ state: 'gone' })+ expect(tmuxBackend.capture).not.toHaveBeenCalled()+ await expect(coordinator.captureRetained(current, { historyLines: 2000 })).resolves.toEqual({+ state: 'succeeded', value: 'saved screen',+ })+ expect(tmuxBackend.capture).toHaveBeenCalledExactlyOnceWith(tmux, { historyLines: 2000 })+ expect(tmuxBackend.validate).not.toHaveBeenCalled()+ expect(current.active).toBe(false)+ })++ it('captures only retained routes and reports unavailable panes instead of inventing a snapshot', async () => {+ const tmuxBackend = backend('tmux:default', vi.fn())+ const captures = vi.fn(async (runtime: TerminalRuntimeRef) => runtime.paneId === tmux.paneId+ ? { state: 'failed' as const, reason: 'pane unavailable' }+ : { state: 'succeeded' as const, value: '' })+ tmuxBackend.capture = captures+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])+ const current = { ...session(), active: false }+ await expect(coordinator.captureRetained(current)).resolves.toEqual({ state: 'succeeded', value: '' })+ expect(captures.mock.calls.map(([runtime]) => runtime)).toEqual([tmux, second])+ current.runtimes = [tmux]+ await expect(coordinator.captureRetained(current)).resolves.toEqual({ state: 'failed', reason: 'pane unavailable' })+ coordinator.replaceBackends([])+ await expect(coordinator.captureRetained(current)).resolves.toMatchObject({ state: 'failed' })+ expect(captures).toHaveBeenCalledTimes(3)+ })+it('uses lease-aware pre-dispatch fallback but never retries ambiguous completion', async () => {const tmuxBackend = backend('tmux:default', submitBy({ state: 'failed', dispatch: 'rejected', reason: 'rejected' }))const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.tsindex ad08d4462..1be11526a 100644--- a/cli/src/lib/terminalBackendCoordinator.ts+++ b/cli/src/lib/terminalBackendCoordinator.ts@@ -156,6 +156,14 @@ export class TerminalBackendCoordinator {async capture(session: RegisteredSession, options?: TerminalCaptureOptions): Promise<TerminalReadResult<string>> {if (!session.active) return { state: 'failed', reason: 'terminal agent is dormant' }+ return this.captureRetained(session, options)+ }++ /** Save a retained pane even when no engine is active (for example, a shell+ * after a daemon restart). This is read-only: control leases and activity+ * reads keep their active-process guards. Close checks identity again before+ * stopping anything and still requires a successful durable checkpoint. */+ async captureRetained(session: RegisteredSession, options?: TerminalCaptureOptions): Promise<TerminalReadResult<string>> {let reason = 'no configured terminal runtime is available'for (const runtime of this.orderedRuntimes(session)) {const result = await this.backendFor(runtime)!.capture(runtime, options)diff --git a/cli/src/lib/terminalClose.real.spec.ts b/cli/src/lib/terminalClose.real.spec.tsnew file mode 100644index 000000000..c7bfec041--- /dev/null+++ b/cli/src/lib/terminalClose.real.spec.ts@@ -0,0 +1,88 @@+import { readFile, readdir, stat } from 'node:fs/promises'+import { join } from 'node:path'+import { expect, it, vi } from 'vitest'+import { env } from '../config/env.js'+import { createTerminalControl } from '../core/terminals/control.js'+import { isolatedTmux } from '../testing/isolatedTmux.js'+import { CloseAgentService, inspectCloseActivity } from './closeAgentService.js'+import { registry } from './registry.js'+import { AgentRestartCoordinator } from './restartAgent.js'+import { SessionCheckpointStore } from './sessionCheckpoint.js'+import { createStopAgentService } from './stopAgentService.js'+import { stoppedAgents } from './stoppedAgents.js'+import { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'+import { TmuxBackend } from './tmuxBackend.js'++it.runIf(process.env.RUN_REAL_TMUX_DISCOVERY === '1')('saves and closes an inactive shell without closing its neighboring pane', async () => {+ const server = await isolatedTmux({ PATH: process.env.PATH, TERM: 'xterm-256color' })+ vi.stubEnv('TMUX', undefined)+ vi.stubEnv('TMUX_PANE', undefined)+ vi.stubEnv('TMUX_TMPDIR', server.root)+ let close: CloseAgentService | undefined+ let agentId: string | undefined+ try {+ const neighbor = await server.run('new-session', '-d', '-P', '-F', '#{pane_id}', '-s', 'terminal-close', 'sleep', '600')+ const pane = await server.run('split-window', '-h', '-P', '-F', '#{pane_id}', '-t', neighbor, '/bin/sh', '-i')+ await server.run('send-keys', '-t', pane, '-l', "printf 'saved terminal output\\n'")+ await server.run('send-keys', '-t', pane, 'Enter')+ await server.run('send-keys', '-t', pane, '-l', 'keep this unsent draft')+ const backend = new TmuxBackend()+ const terminals = new TerminalBackendCoordinator([backend], ['tmux'])+ const control = createTerminalControl({ resolve: id => registry.resolve(id), terminals })+ const row = registry.openPendingAgent({ engine: 'terminal', cwd: env.ADAPTER_DATA_DIR,+ runtimes: [{ backend: 'tmux', paneId: pane }] })!+ agentId = row.agentId+ // Registry reloads can leave a perfectly live shell inactive: no engine is+ // running to rediscover. Its retained pane is still visible in the app.+ registry.setActive(row.agentId, false)+ await vi.waitFor(async () => {+ const capture = await backend.capture(row.runtimes[0])+ expect(capture).toMatchObject({ state: 'succeeded', value: expect.stringContaining('keep this unsent draft') })+ })+ expect(await control.captureTerminal(row.agentId)).toBeNull()+ const directory = join(env.ADAPTER_DATA_DIR, 'terminal-checkpoints')+ const checkpoints = new SessionCheckpointStore(directory)+ const savedScreen = async () => {+ const files = await readdir(directory)+ const manifest = JSON.parse(await readFile(join(directory, files.find(file => /^[a-f0-9]{64}\.json$/.test(file))!), 'utf8'))+ const file = join(directory, manifest.file)+ expect((await stat(file)).mode & 0o777).toBe(0o600)+ const saved = JSON.parse(await readFile(file, 'utf8'))+ expect(saved.agentId).toBe(row.agentId)+ expect(saved.screen).toContain('saved terminal output')+ expect(saved.screen).toContain('keep this unsent draft')+ }+ const actualKill = backend.kill.bind(backend)+ const kill = vi.spyOn(backend, 'kill')+ kill.mockImplementation(async runtime => {+ await savedScreen() // The backup must exist before the pane is killed.+ return actualKill(runtime)+ })+ const stop = createStopAgentService({ registry, stoppedAgents,+ restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(), tmuxBackend: backend,+ agentReconciler: { suppress() {}, holdRoute() {}, releaseRoute() {}, trigger: async () => {} },+ forgetSession: id => registry.removeAgent(id), markDeleted() {}, clearDeleted() {},+ })+ close = new CloseAgentService({ registry, stop, changed() {},+ activity: async session => inspectCloseActivity(session, await control.captureTerminal(session.agentId), undefined, false),+ checkpoint: async (session, phase) => {+ const captured = phase === 'before' ? await terminals.captureRetained(session, { historyLines: 2000 }) : null+ await checkpoints.save(session, { screen: captured?.state === 'succeeded' ? captured.value : null })+ },+ })+ const request = { agentId: row.agentId, sessionId: '', createdAt: new Date(row.registeredAt).toISOString() }+ expect(await close.request({ ...request, mode: 'idle' })).toMatchObject({ error: 'SESSION_NOT_IDLE' })+ expect(kill).not.toHaveBeenCalled()+ expect(await close.request({ ...request, mode: 'now' })).toEqual({ closed: true })+ expect(kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: pane })+ expect(registry.byAgent(row.agentId)).toBeUndefined()+ await savedScreen()+ expect(await server.run('list-panes', '-t', 'terminal-close', '-F', '#{pane_id}')).toBe(neighbor)+ } finally {+ close?.dispose()+ if (agentId) registry.removeAgent(agentId)+ vi.restoreAllMocks()+ vi.unstubAllEnvs()+ await server.close()+ }+}, 15_000)