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.

Save closed sessions, release their memory, and add a live resource monitor (#524)

Dee022d4799e334
diff --git a/cli/scripts/codex-shared-close-e2e.ts b/cli/scripts/codex-shared-close-e2e.ts
new file mode 100644
index 000000000..222a70785
--- /dev/null
+++ b/cli/scripts/codex-shared-close-e2e.ts
@@ -0,0 +1,63 @@
+/** Disposable real Codex shared-server lifecycle test. No paid provider or user profile. */
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+const exec = promisify(execFile)
+const root = mkdtempSync(join(tmpdir(), 'harness-codex-shared-close-'))
+const binary = (await exec('/usr/bin/which', ['codex'])).stdout.trim()
+for (const key of Object.keys(process.env)) if (/^(HARNESS|CODEX|CLAUDE|ANTHROPIC|OPENAI)_/.test(key)) delete process.env[key]
+Object.assign(process.env, { CODEX_HOME: root, CODEX_PATH: binary, ADAPTER_DATA_DIR: join(root, 'harness') })
+const { connectCodexControl, stopSharedCodexSession } = await import('../src/lib/codexSessionLifecycle.js')
+const { registry } = await import('../src/lib/registry.js')
+const provider = createServer((_request, _response) => { /* Holds the synthetic turn until interrupted. */ })
+await new Promise<void>(resolve => provider.listen(0, '127.0.0.1', resolve))
+const providerPort = (provider.address() as { port:number }).port
+writeFileSync(join(root, 'config.toml'), `model_provider = "fixture"\ncheck_for_update_on_startup = false\n[model_providers.fixture]\nname = "Local fixture"\nbase_url = "http://127.0.0.1:${providerPort}/v1"\nwire_api = "responses"\nrequires_openai_auth = false\n[projects.${JSON.stringify(root)}]\ntrust_level = "trusted"\n`)
+let control: Awaited<ReturnType<typeof connectCodexControl>> | undefined
+try {
+ await exec(binary, ['app-server', 'daemon', 'start'], { env: process.env, timeout: 15000 })
+ control = await connectCodexControl(root)
+ const threads: Array<{ id: string; path: string }> = []
+ for (let index = 0; index < 2; index++) {
+ const id = randomUUID(), timestamp = new Date().toISOString()
+ const folder = join(root, 'sessions', timestamp.slice(0,4), timestamp.slice(5,7), timestamp.slice(8,10))
+ mkdirSync(folder, { recursive: true })
+ const path = join(folder, `rollout-${timestamp.slice(0,19).replace(/:/g, '-')}-${id}.jsonl`)
+ writeFileSync(path, [
+ { timestamp, type:'session_meta', payload: { id, timestamp, cwd:root, originator:'codex_cli_rs', cli_version:'0.159.0', source:'cli', model_provider:'fixture' } },
+ { timestamp, type:'response_item', payload: { type:'message',role:'user',content:[{type:'input_text',text:`SHARED_HISTORY_${id}`}] } },
+ ].map(row=>JSON.stringify(row)).join('\n')+'\n')
+ const resumed = await control.request('thread/resume', { threadId:id, cwd:root })
+ assert.equal(resumed.thread.id, id)
+ threads.push({ id, path })
+ }
+ const [target, neighbour] = threads
+ await control.request('turn/start', { threadId:target.id, input:[{type:'text',text:'Local loopback fixture only; do not use tools.'}] })
+ const until = Date.now() + 5000
+ while ((await control.request('thread/read', { threadId:target.id })).thread.status.type !== 'active' && Date.now() < until) await new Promise(resolve => setTimeout(resolve, 20))
+ assert.equal((await control.request('thread/read', { threadId:target.id })).thread.status.type, 'active')
+ await control.request('thread/goal/set', { threadId:target.id, objective:'Only wait for the local fixture; do not use tools.', status:'active' })
+ const row = registry.openPendingAgent({ engine:'codex', runtimes:[{backend:'tmux',paneId:'%999999'}],cwd:root,codexHome:root })!
+ Object.assign(row, { sessionId:target.id, transcriptPath:target.path })
+ await stopSharedCodexSession(row, ()=>true)
+ assert.equal((await control.request('thread/read', { threadId:target.id })).thread.status.type, 'notLoaded')
+ assert.equal((await control.request('thread/read', { threadId:neighbour.id })).thread.status.type, 'idle')
+ assert.equal((await control.request('thread/goal/get', { threadId:target.id })).goal.status, 'paused')
+ assert(existsSync(target.path), 'the native conversation must be back in sessions')
+ assert(readFileSync(target.path,'utf8').includes(`SHARED_HISTORY_${target.id}`))
+ const resumed = await control.request('thread/resume', { threadId:target.id })
+ assert.equal(resumed.thread.id, target.id)
+ assert.equal(resumed.thread.status.type, 'idle')
+ console.log('PASS shared Codex: active turn stopped, target unloaded, neighbour remained loaded, history retained, same conversation resumed')
+} finally {
+ control?.close()
+ provider.closeAllConnections(); provider.close()
+ await exec(binary, ['app-server', 'daemon', 'stop'], { env:process.env, timeout:15000 }).catch(error=>console.error('fixture cleanup:',error.message))
+ console.log('fixture:',root)
+ if (!process.env.KEEP_RESUME_FIXTURE) rmSync(root,{recursive:true,force:true})
+}
diff --git a/cli/scripts/resume-native-e2e.ts b/cli/scripts/resume-native-e2e.ts
index 9b4fee118..1629b620a 100644
--- a/cli/scripts/resume-native-e2e.ts
+++ b/cli/scripts/resume-native-e2e.ts
@@ -6,7 +6,7 @@
*/
import { execFile as execCallback } from 'node:child_process'
import { promisify } from 'node:util'
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, realpathSync } from 'node:fs'
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, realpathSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { randomUUID } from 'node:crypto'
@@ -22,6 +22,10 @@ const socket = `resume-e2e-${process.pid}`
const quote = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`
const bin = join(root, 'bin'); mkdirSync(bin)
writeFileSync(join(bin, 'tmux'), `#!/bin/sh\nexec ${quote(tmuxBinary)} -L ${quote(socket)} -f /dev/null "$@"\n`, { mode: 0o700 })
+// Do not propagate this agent's account, swarm or engine overrides into the disposable TUIs.
+for (const key of Object.keys(process.env)) {
+ if (/^(HARNESS|CODEX|CLAUDE|ANTHROPIC|OPENAI)_/.test(key) || key === 'CLAUDECODE') delete process.env[key]
+}
Object.assign(process.env, {
PATH: `${bin}:${process.env.PATH}`, ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime'),
ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'), HARNESS_AUTH_DIR: join(root, 'auth'), DSH_DIR: join(root, 'dsh'),
@@ -33,9 +37,16 @@ const { registry } = await import('../src/lib/registry.js')
const { stoppedAgents } = await import('../src/lib/stoppedAgents.js')
const { TmuxBackend } = await import('../src/lib/tmuxBackend.js')
const { createStopAgentService } = await import('../src/lib/stopAgentService.js')
+const { CloseAgentService, inspectCloseActivity } = await import('../src/lib/closeAgentService.js')
+const { sessionCheckpoints } = await import('../src/lib/sessionCheckpoint.js')
+const { createHarnessResourcesReader } = await import('../src/lib/harnessResources.js')
+const { CodexNormalizer } = await import('../src/engines/codex/normalizer.js')
+const { lineToEvents, newTurnState } = await import('../src/lib/normalize.js')
+const { agentFrame } = await import('../src/lib/agentFrame.js')
+const { buildEngineLaunchArgv } = await import('../src/lib/engineLaunch.js')
const { createResumeAgentService } = await import('../src/lib/resumeAgentService.js')
const { AgentRestartCoordinator } = await import('../src/lib/restartAgent.js')
-const { resolvePaneEngineProcess, checkSessionRuntime } = await import('../src/lib/tmux.js')
+const { resolvePaneEngineProcess, checkSessionRuntime, lookupPaneEngineProcess, tmuxPaneProcessTree } = await import('../src/lib/tmux.js')
const { captureResumeIdentity } = await import('../src/lib/captureResumeIdentity.js')
const { claudeProcessSession } = await import('../src/lib/sessionRepair.js')
const { checkPidRuntime } = await import('../src/lib/deleteAgentFallback.js')
@@ -51,7 +62,8 @@ const server = await startHookServer(0, {
resolveHookAgent: async input => {
if (!input.tmuxPane) return null
const identity = await resolvePaneEngineProcess(input.tmuxPane, input.engine)
- if (!identity) { console.error('[fixture] no process for', input); return null }
+ if (!identity) { console.error('[fixture] no process for', input,
+ await lookupPaneEngineProcess(input.tmuxPane, input.engine), await tmuxPaneProcessTree(input.tmuxPane)); return null }
const row = registry.byPaneEngine(input.tmuxPane, input.engine)
if (!row || row.engine !== input.engine) { console.error('[fixture] no registry route', input, identity, registry.list().map(r => ({ id: r.agentId, pane: r.tmuxPane }))); return null }
return registry.openProcessAgent({ engine: input.engine, processIdentity: identity, runtimes: row.runtimes, primaryRuntimeKey: row.primaryRuntimeKey, cwd: row.cwd })?.entry ?? null
@@ -71,6 +83,8 @@ try {
// Anchor keeps pane IDs monotonic even after Stop removes the last engine session.
await tmux('new-session', '-d', '-s', 'fixture-anchor', '/bin/sh')
for (const engine of ['claude', 'codex'] as const) {
+ const selected = process.argv.find(arg => arg.startsWith('--engine='))?.slice('--engine='.length)
+ if (selected && selected !== engine) continue
const cwd = join(root, engine, 'workspace'); mkdirSync(cwd, { recursive: true })
const profile = join(root, engine)
const sessionId = randomUUID(); const marker = `RESUME_HISTORY_${engine}_${sessionId.slice(0, 8)}`
@@ -89,7 +103,7 @@ try {
writeFileSync(join(profile, 'settings.json'), JSON.stringify({ apiKeyHelper: 'printf fixture-never-used', hooks: { SessionStart: [{ hooks: [{ type: 'command', command: cmd, timeout: 5 }] }] } }))
} else {
const folder = join(profile, 'sessions', timestamp.slice(0,4), timestamp.slice(5,7), timestamp.slice(8,10)); mkdirSync(folder, { recursive: true })
- transcriptPath = join(folder, `rollout-${timestamp.replace(/:/g, '-')}-${sessionId}.jsonl`)
+ transcriptPath = join(folder, `rollout-${timestamp.slice(0, 19).replace(/:/g, '-')}-${sessionId}.jsonl`)
writeFileSync(transcriptPath, [
{ timestamp, type: 'session_meta', payload: { id: sessionId, timestamp, cwd, originator: 'codex_cli_rs', cli_version: '0.154.0', source: 'cli', model_provider: 'fixture' } },
{ timestamp, type: 'event_msg', payload: { type: 'task_started', turn_id: sessionId, model_context_window: 100000 } },
@@ -114,7 +128,7 @@ try {
PATH: `${bin}:${process.env.PATH}`, HARNESS_HOOK_DATA_DIR: process.env.ADAPTER_DATA_DIR!,
}
if (engine === 'codex') {
- const bootstrap = await backend.create({ cwd, label: 'fixture-hook-trust', command: [codexBinary, '--no-alt-screen'], env: launchEnv })
+ const bootstrap = await backend.create({ cwd, label: 'fixture-hook-trust', command: buildEngineLaunchArgv('codex', { extraArgs: ['--no-alt-screen'] }), env: launchEnv })
assert.equal(bootstrap.state, 'succeeded')
if (bootstrap.state === 'succeeded') {
const until = Date.now() + 15000
@@ -131,10 +145,34 @@ try {
}
const jobs = new AgentRestartCoordinator()
const stopJobs = new Map<string, Promise<void>>()
- socketBackend.onDeleteAgent = createStopAgentService({
+ const stopAgent = createStopAgentService({
registry, stoppedAgents, restartJobs: jobs, stopJobs, tmuxBackend: backend,
agentReconciler: { suppress: () => {}, holdRoute: () => {}, releaseRoute: () => {}, trigger: async () => {} },
- forgetSession: id => registry.removeAgent(id), markDeleted: () => {}, clearDeleted: () => {},
+ forgetSession: id => { registry.removeAgent(id); socketBackend.send({ type: 'agent_deleted', payload: { agentId: id, retained: true } }) }, markDeleted: () => {}, clearDeleted: () => {},
+ })
+ socketBackend.onDeleteAgent = stopAgent
+ socketBackend.closeAgentService?.dispose()
+ socketBackend.closeAgentService = new CloseAgentService({
+ registry,
+ activity: async row => {
+ const screen = await tmux('capture-pane', '-p', '-S', '-80', '-t', row.tmuxPane)
+ const raw = row.transcriptPath ? readFileSync(row.transcriptPath, 'utf8').trim().split('\n') : []
+ let turnOpen: boolean | undefined
+ if (row.engine === 'codex') {
+ const normalizer = new CodexNormalizer('live')
+ for (const line of raw) normalizer.ingest(line)
+ if (raw.length) turnOpen = normalizer.turnOpen
+ } else if (row.engine === 'claude') {
+ const state = newTurnState()
+ for (const line of raw) lineToEvents(line, state)
+ if (raw.length) turnOpen = state.turnOpen
+ }
+ return inspectCloseActivity(row.engine, screen, turnOpen, false)
+ },
+ checkpoint: async (row, explicitlyStopped, phase) => sessionCheckpoints.save(row, {
+ explicitlyStopped, screen: phase === 'before' ? await tmux('capture-pane', '-p', '-S', '-2000', '-t', row.tmuxPane) : null,
+ }),
+ stop: stopAgent, changed: row => { void agentFrame(row, { selectedModel: null, terminalAvailable: true, dsh: null }).then(agent => socketBackend.send({ type: 'agent_synced', payload: { agent } })) },
})
socketBackend.onResumeAgent = createResumeAgentService({
registry, stoppedAgents, tmuxBackend: backend, restartJobs: jobs, stopJobs, pinnedControls: new Set(),
@@ -193,7 +231,8 @@ try {
const neighbour = (await tmux('split-window', '-d', '-P', '-F', '#{pane_id}', '-t', route, '/bin/sh')).trim()
const neighbourPid = (await tmux('display-message', '-p', '-t', neighbour, '#{pane_pid}')).trim()
assert.equal((await checkSessionRuntime(live)).state, 'alive')
- assert.equal((await rpc('agent_resume', { agentId: old.agentId, creationId: randomUUID() })).resumed, true)
+ const reattached = await rpc('agent_resume', { agentId: old.agentId, creationId: randomUUID() })
+ assert.equal(reattached.resumed, true, JSON.stringify(reattached))
assert.equal(registry.byAgent(old.agentId)!.processIdentity!.pid, pid); assert.equal(registry.byAgent(old.agentId)!.tmuxPane, route)
assert.equal((await rpc('agent_create_status', { creationId })).state, 'created')
// Reproduce a legacy daemon row whose hook binding was lost. Remove the earlier
@@ -247,11 +286,43 @@ try {
assert.equal((await openSaved(randomUUID())).state, 'created')
const current = registry.byAgent(old.agentId)!
assert.equal(current.sessionId, sessionId)
- const paused = await rpc('agent_delete', { agentId: old.agentId })
- assert.equal(paused.deleted, true, JSON.stringify(paused))
+ const closeTarget = { agentId: current.agentId, sessionId: current.sessionId, createdAt: new Date(current.registeredAt).toISOString() }
+ // Deferred intent is durable, but opening/cancelling must leave the same process alive.
+ assert.equal((await rpc('agent_close', { ...closeTarget, mode: 'after_task' })).deferred, true)
+ registry.load()
+ assert.equal(registry.byAgent(current.agentId)?.closePlan?.state, 'waiting')
+ assert.equal((await rpc('agent_close', { ...closeTarget, mode: 'cancel' })).cancelled, true)
+ assert.equal((await checkPidRuntime(current)).state, 'alive')
+ const reading = (await createHarnessResourcesReader(() => [current])()).agents[0]
+ assert(reading.memoryBytes !== null && reading.memoryBytes > 0, 'monitor must read the real process tree')
+ const inspected = await rpc('agent_close', { ...closeTarget, mode: 'inspect' })
+ assert(inspected.activity, JSON.stringify(inspected))
+ const paused = await rpc('agent_close', { ...closeTarget, mode: inspected.activity === 'idle' ? 'idle' : 'now' })
+ assert.equal(paused.closed, true, JSON.stringify(paused))
+ assert.equal((await checkPidRuntime(current)).state, 'gone')
+ const after = (await createHarnessResourcesReader(() => [current])()).agents[0]
+ assert.equal(after.memoryBytes, null, 'a dead process must not retain an old RAM reading')
+ const folder = join(root, 'data', 'session-checkpoints')
+ const manifest = readdirSync(folder).filter(f => /^[a-f0-9]{64}\.json$/.test(f))
+ .map(f => JSON.parse(readFileSync(join(folder, f), 'utf8'))).find(m => m.agentId === current.agentId)
+ assert(manifest, 'close must commit a durable checkpoint')
+ assert(readFileSync(join(folder, manifest.file), 'utf8').includes(marker), 'checkpoint must retain the original conversation')
+ log(`${engine} close ${cycle + 1}: ${inspected.activity}, ${Math.round(reading.memoryBytes / 1024 / 1024)} MB released, checkpoint verified`)
+ }
+ if (engine === 'claude') {
+ assert.equal((await openSaved(randomUUID())).state, 'created')
+ const current = registry.byAgent(old.agentId)!
+ const queued = await rpc('agent_close', { agentId: current.agentId, sessionId: current.sessionId,
+ createdAt: new Date(current.registeredAt).toISOString(), mode: 'after_task' })
+ assert.equal(queued.deferred, true)
+ const deferredDeadline = Date.now() + 25000
+ while (registry.byAgent(current.agentId) && Date.now() < deferredDeadline) await new Promise(resolve => setTimeout(resolve, 100))
+ assert.equal(registry.byAgent(current.agentId), undefined, 'a deferred idle close must complete without another client request')
assert.equal((await checkPidRuntime(current)).state, 'gone')
+ assert.equal(stoppedAgents.get(current.agentId)?.sessionId, sessionId)
+ log('PASS deferred close: real idle Claude saved and exited through the background timer')
}
- log(`PASS ${engine}: native history + hook, three immediate pause/resume cycles, new tmux runtime, same id, attach same PID, receipt replay, missing-ID recovery before Stop, stop persistence, neighbouring pane and surviving shell preserved`)
+ log(`PASS ${engine}: native history + hook, three close/checkpoint/resume cycles, deferred close persistence/cancel, measured RAM released, new tmux runtime, same id, attach same PID, receipt replay, missing-ID recovery before Stop, neighbouring pane and surviving shell preserved`)
}
if (process.argv.includes('--serve')) {
// The desktop acceptance test uses the real local WS transport and terminal streams.
@@ -259,7 +330,6 @@ try {
const { attachLocalWsServer } = await import('../src/localWsServer.js')
const { TerminalStreamManager } = await import('../src/lib/terminalStreamManager.js')
const { TerminalBackendCoordinator } = await import('../src/lib/terminalBackendCoordinator.js')
- const { agentFrame } = await import('../src/lib/agentFrame.js')
const streams = new TerminalStreamManager({
terminals: new TerminalBackendCoordinator([backend], ['tmux'], []),
resolveAgent: id => registry.byAgent(id), streamingAvailable: true,
@@ -274,7 +344,7 @@ try {
const resume = socketBackend.onResumeAgent!
socketBackend.onResumeAgent = async id => {
const fixture = fixtures.find(f => f.agentId === id); assert(fixture, 'only fixture sessions may resume')
- let done = false, submitted = false
+ let done = false
const result = resume(id).finally(() => { done = true })
let announced = ''
while (!done) {
@@ -285,15 +355,8 @@ try {
announced = state
socketBackend.send({ type: 'agent_synced', payload: { agent: await agentFrame(row, { selectedModel: null, terminalAvailable: true, dsh: null }) } })
}
- if (fixture.engine === 'codex' && !submitted) {
- const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', row.tmuxPane)
- if (screen.includes(fixture.marker) && /Ask Codex/.test(screen)) {
- submitted = true
- await tmux('send-keys', '-t', row.tmuxPane, '-l', 'Fixture verification only. Do not use tools.')
- await new Promise(r => setTimeout(r, 600))
- await tmux('send-keys', '-t', row.tmuxPane, 'Enter')
- }
- }
+ // The standalone native check already proved the deferred startup
+ // hook. UI resume must behave like production: never submit a turn.
}
await new Promise(r => setTimeout(r, 100))
}
@@ -308,7 +371,6 @@ try {
console.error('[resume-native] native pause failed:', error, { before, after: JSON.stringify(registry.byAgent(id)) })
throw error
}
- socketBackend.send({ type: 'agent_deleted', payload: { agentId: id, retained: true } })
}
let finish!: () => void
const finished = new Promise<void>(resolve => { finish = resolve })
@@ -325,7 +387,15 @@ try {
assert.equal(saved?.sessionId, fixture.sessionId)
if (row) {
assert.equal(row.sessionId, fixture.sessionId)
- const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', row.tmuxPane)
+ // Process readiness precedes the native TUI's first paint. Check the
+ // real terminal with a bounded wait, including background resumes.
+ let screen = ''
+ const paintDeadline = Date.now() + 10000
+ do {
+ screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', row.tmuxPane)
+ if (screen.includes(fixture.marker)) break
+ await new Promise(resolve => setTimeout(resolve, 100))
+ } while (Date.now() < paintDeadline)
assert(screen.includes(fixture.marker), 'native terminal must show original history')
} else {
assert.equal((await checkPidRuntime(saved!)).state, 'gone', 'Paused must mean the original process is gone')
@@ -341,7 +411,7 @@ try {
const endpoint = `http://127.0.0.1:${(http.address() as { port: number }).port}`
writeFileSync(join(tmpdir(), 'harness-resume-ui-endpoint.json'), JSON.stringify({ endpoint, root }))
log(`desktop fixture ready: ${endpoint}`)
- const expiry = setTimeout(finish, 10 * 60_000)
+ const expiry = setTimeout(finish, 30 * 60_000)
process.once('SIGINT', finish); process.once('SIGTERM', finish)
await finished
clearTimeout(expiry); process.off('SIGINT', finish); process.off('SIGTERM', finish)
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 0e838b386..f565e84de 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -25,7 +25,31 @@ import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixture
import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
import { LocalModels } from './lib/localModels.js'
import type { GridAttachResult } from './lib/gridAttach.js'
-import { STRICT_DOWN_TYPES } from './lib/e2ee/applicationFrames.js'
+import { STRICT_DOWN_TYPES, encryptDownFrame, encryptRpcResult } from './lib/e2ee/applicationFrames.js'
+import type { CloseAgentService } from './lib/closeAgentService.js'
+
+describe('safe session close RPC', () => {
+ it('requires encrypted remote frames and never blocks unrelated inventory while saving', async () => {
+ const socket = new BackendSocket('fixture')
+ const frames: any[] = []
+ socket.registerLocalClient('local:close', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })
+ let finish!: (value: { closed: true }) => void
+ const request = vi.fn(() => new Promise<{ closed: true }>(resolve => { finish = resolve }))
+ socket.closeAgentService = { request, dispose() {} } as unknown as CloseAgentService
+ const payload = { requestId: 'closing', agentId: 'fixture', sessionId: 'history', createdAt: '2026-09-30T12:00:00.000Z', mode: 'idle' }
+ expect(encryptDownFrame('agent_close')).toBe(true)
+ expect(encryptRpcResult('agent_close_result')).toBe(true)
+ await (socket as any).dispatchDown({ type: 'agent_close', payload }, 'remote')
+ expect(request).not.toHaveBeenCalled()
+ socket.handleLocalFrame('local:close', { type: 'agent_close', payload })
+ socket.handleLocalFrame('local:close', { type: 'agents_list', payload: { requestId: 'inventory' } })
+ await vi.waitFor(() => expect(frames.some(f => f.type === 'agents_list_result')).toBe(true))
+ expect(frames.some(f => f.type === 'agent_close_result')).toBe(false)
+ finish({ closed: true })
+ await vi.waitFor(() => expect(frames.find(f => f.type === 'agent_close_result')?.payload).toMatchObject({ requestId: 'closing', closed: true }))
+ await socket.stop()
+ })
+})
describe('local model lifecycle RPCs', () => {
afterEach(() => vi.restoreAllMocks())
@@ -1174,6 +1198,27 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('serves per-session resource readings without blocking input or sampling system totals', async () => {
+ const system = vi.spyOn(machineResources, 'readMachineResources')
+ const socket = new BackendSocket('token')
+ let finish!: (value: { sampledAt: string; agents: [] }) => void
+ socket.harnessResourcesReader = vi.fn(() => new Promise<{ sampledAt: string; agents: [] }>(resolve => { finish = resolve }))
+ socket.runtimeModelsProvider = async () => []
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:monitor', {
+ sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true,
+ })
+ socket.handleLocalFrame('local:monitor', { type: 'machine_resources', payload: { requestId: 'resources', harnesses: true } })
+ socket.handleLocalFrame('local:monitor', { type: 'models_list', payload: { requestId: 'models' } })
+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'models_list_result', payload: { requestId: 'models', models: [] } }))
+ expect(system).not.toHaveBeenCalled()
+ const reading = { sampledAt: '2026-09-30T12:00:00Z', agents: [] as [] }
+ finish(reading)
+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'machine_resources_result', payload: { requestId: 'resources', harnesses: reading } }))
+ await socket.unregisterLocalClient('local:monitor')
+ await socket.stop()
+ })
+
it('rejects unpaired plaintext stats requests before sampling the machine', async () => {
const read = vi.spyOn(machineResources, 'readMachineResources')
const socket = new BackendSocket('token')
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index c64db04a5..bd0202d8c 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -30,6 +30,7 @@ import { AuthSessionManager, AuthSessionError } from './lib/authSession.js'
import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import { AgentStopError } from './lib/stopAgentService.js'
+import type { CloseAgentService, CloseMode } from './lib/closeAgentService.js'
import { isHiddenBuiltin } from './dsh/builtins.js'
import { ENGINES, PROCESS_ENGINES, isTerminalEngine, type AgentEngine, type ProcessEngine } from './engines/types.js'
import { listDir } from './lib/fsBrowse.js'
@@ -51,6 +52,7 @@ import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, Nam
import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'
import { probeEngines } from './lib/engineProbe.js'
import { readMachineResources } from './lib/machineResources.js'
+import { createHarnessResourcesReader } from './lib/harnessResources.js'
import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError } from './lib/projectFolder.js'
@@ -496,6 +498,7 @@ export class BackendSocket {
/** Called when the web deletes an agent (`agent_delete`) — cli.ts signals only the validated engine
* process and forgets the session. Keeps recap + agent name. */
onDeleteAgent: ((sessionId: string) => void | Promise<void>) | null = null
+ closeAgentService: CloseAgentService | null = null
/** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the
* requested folder and returns its process-agent. Session metadata may bind later through hooks. */
onCreateAgent: ((input: {
@@ -755,6 +758,7 @@ export class BackendSocket {
/** Answers `usage_read` — this machine's own agent-account usage (lib/accountUsage.ts). A field
* rather than a direct call so a spec answers it without a real home, Keychain or network. */
accountUsageReader: () => Promise<AccountUsageReading[]> = readAccountUsage
+ harnessResourcesReader = createHarnessResourcesReader(() => registry.advertised())
/** The grid listing currently out, shared by every `grid_models_list` for the same own grid
* that lands meanwhile. */
private gridModelsInFlight: { gridName: string | null; grids: ReturnType<typeof listAllGridModels> } | null = null
@@ -1200,6 +1204,7 @@ export class BackendSocket {
async stop(): Promise<void> {
this.closed = true
+ this.closeAgentService?.dispose()
this.stopGridModelsPush()
this.orchestratorService?.stop()
this.teamService?.stop()
@@ -2070,7 +2075,9 @@ export class BackendSocket {
switch (type) {
case 'machine_resources':
// Sampling CPU must not hold up typing or other machine requests.
- void readMachineResources()
+ void (payload.harnesses === true
+ ? this.harnessResourcesReader().then(harnesses => ({ harnesses }))
+ : readMachineResources())
.then(resources => reply(type, requestId, { ...resources }))
.catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))
return
@@ -2657,6 +2664,7 @@ export class BackendSocket {
// clock was set back) never throttles: the next open corrects it.
let opened = false
if (hasOpened) {
+ this.closeAgentService?.cancel(s.agentId)
const since = Date.now() - (s.lastOpenedAt ?? 0)
if (!s.lastOpenedAt || since < 0 || since >= AGENT_OPENED_THROTTLE_MS) {
s = registry.markOpened(s.agentId) ?? s
@@ -3008,6 +3016,19 @@ export class BackendSocket {
// Delete an agent: signal its validated engine process and drop it from the list. Idempotent — an already
// gone target still acks + re-emits agent_deleted so the web/device converge. E2EE-gated (the
// frame arrived decrypted). Keeps the persisted recap + agent name for a later resume.
+ case 'agent_close': {
+ if (!this.closeAgentService) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }
+ const { agentId, sessionId, createdAt, mode } = payload
+ if (typeof agentId !== 'string' || typeof sessionId !== 'string' || typeof createdAt !== 'string'
+ || typeof mode !== 'string' || !['inspect', 'idle', 'now', 'after_task', 'cancel'].includes(mode)) {
+ reply(type, requestId, { error: 'INVALID_CLOSE_REQUEST' }); return
+ }
+ // Saving/exit may take seconds; terminal input and unrelated agents keep flowing.
+ void this.closeAgentService.request({ agentId, sessionId, createdAt, mode: mode as CloseMode },
+ () => this.terminalStreams?.hasOtherViews(agentId, connId) ?? false)
+ .then(result => reply(type, requestId, result), () => reply(type, requestId, { error: 'CLOSE_FAILED' }))
+ return
+ }
case 'agent_delete': {
const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index dd576fa20..4c651f3e1 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -143,6 +143,8 @@ 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 { CloseAgentService, inspectCloseActivity } from './lib/closeAgentService.js'
+import { sessionCheckpoints } from './lib/sessionCheckpoint.js'
import { repairClaudeCwd } from './lib/cwdRepair.js'
import { stoppedAgents } from './lib/stoppedAgents.js'
import { SessionSearchIndex, folderWords, type SearchSource } from './lib/sessionSearch/indexer.js'
@@ -2384,7 +2386,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const devinReaders = new Map<string, DevinReader>()
const commandcodeNormalizers = new Map<string, CommandCodeNormalizer>()
/** Whether this session's engine state says a turn is open right now, whichever engine it is. */
- const sessionTurnOpen = (sessionId: string): boolean =>
+ const sessionTurnState = (sessionId: string): boolean | undefined =>
turnStates.get(sessionId)?.turnOpen
?? codexNormalizers.get(sessionId)?.turnOpen
?? cursorNormalizers.get(sessionId)?.turnOpen
@@ -2399,7 +2401,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
?? hermesReaders.get(sessionId)?.turnOpen
?? devinReaders.get(sessionId)?.turnOpen
?? commandcodeNormalizers.get(sessionId)?.turnOpen
- ?? false
+ const sessionTurnOpen = (sessionId: string): boolean => sessionTurnState(sessionId) ?? false
const watcher = new Watcher()
const queuedSessionEvents: Array<{
sessionId: string
@@ -6766,10 +6768,25 @@ async function runForeground(session: AuthSession | null): Promise<void> {
* SIGTERM/SIGKILL fallback. Engine conversation files, recaps and the Harness name remain on disk.
*/
const stopJobs = new Map<string, Promise<void>>()
- backend.onDeleteAgent = createStopAgentService({
+ const stopAgent = createStopAgentService({
registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,
forgetSession, markDeleted, clearDeleted,
})
+ backend.onDeleteAgent = stopAgent
+ backend.closeAgentService = new CloseAgentService({
+ registry,
+ activity: async s => {
+ if (s.sessionId) await watcher.pollSession(s.sessionId)
+ const screen = await captureTerminal(s.agentId, 80)
+ return inspectCloseActivity(s.engine, screen, sessionTurnState(s.sessionId), openQuestions.has(s.sessionId))
+ },
+ checkpoint: async (s, explicitlyStopped, phase) => sessionCheckpoints.save(s, {
+ explicitlyStopped, screen: phase === 'before' ? await captureTerminal(s.agentId, 2000) : null,
+ }),
+ stop: stopAgent,
+ changed: announceSession,
+ })
+ backend.closeAgentService.start()
backend.onResumeAgent = createResumeAgentService({
registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index a48043a79..737b3a93d 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -59,6 +59,8 @@ export type AgentFrame = {
*/
title: string | null
status: string
+ closePlan: { state: 'waiting' | 'failed'; detail?: string } | null
+ closeSupported: boolean
launch: NonNullable<RegisteredSession['launch']>
createdAt: string
updatedAt: string
@@ -196,6 +198,8 @@ export async function agentFrame(
name: projectDisplayName(s),
title: frameTitle(s),
status: s.active ? 'active' : 'offline',
+ closePlan: s.closePlan ? { state: s.closePlan.state, ...(s.closePlan.detail ? { detail: s.closePlan.detail } : {}) } : null,
+ closeSupported: true,
launch: s.launch ?? { state: 'ready' },
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(updatedAt).toISOString(),
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
new file mode 100644
index 000000000..6aa282ffa
--- /dev/null
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -0,0 +1,229 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { CloseAgentService, inspectCloseActivity, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'
+import { registry, type RegisteredSession } from './registry.js'
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+
+let row: RegisteredSession
+let service: CloseAgentService
+let deps: CloseAgentServiceDeps
+let time: number
+const request = (mode: AgentCloseRequest['mode'] = 'idle'): AgentCloseRequest => ({ agentId: row.agentId,
+ sessionId: row.sessionId, createdAt: new Date(row.registeredAt).toISOString(), mode })
+beforeEach(() => {
+ time = 10_000
+ row = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%88' }], cwd: '/tmp' })!
+ Object.assign(row, { sessionId: 'history', processIdentity: { pid: 777, startMarker: 'born', executable: 'codex' } })
+ const home = join(env.ADAPTER_DATA_DIR, 'close-history', row.agentId)
+ mkdirSync(join(home, 'sessions'), { recursive: true })
+ Object.assign(row, { codexHome: home, transcriptPath: join(home, 'sessions', 'history.jsonl') })
+ writeFileSync(row.transcriptPath!, '{"history":"fixture"}\n')
+ deps = { registry, now: () => time, activity: vi.fn(async (): Promise<CloseActivity> => 'idle'), checkpoint: vi.fn(async () => {}),
+ changed: vi.fn(), stop: vi.fn(async (id, options) => {
+ await options.checkpoint?.(row, 'before')
+ await options.beforeStop?.(row)
+ if (options.current?.() === false) throw new Error('cancelled')
+ registry.removeAgent(id)
+ }) }
+ service = new CloseAgentService(deps)
+})
+afterEach(() => { service.dispose(); vi.useRealTimers(); vi.restoreAllMocks(); for (const s of registry.list()) registry.removeAgent(s.agentId) })
+
+it('backs up an idle session before stopping, without treating a tab switch as Close', async () => {
+ service.start()
+ expect(deps.activity).not.toHaveBeenCalled()
+ expect(await service.request(request())).toEqual({ closed: true })
+ expect(deps.checkpoint).toHaveBeenCalledOnce()
+ expect(deps.activity).toHaveBeenCalledTimes(2)
+})
+it.each<CloseActivity>(['working', 'needs_input', 'draft', 'unknown'])('leaves %s work alive until explicitly approved', async activity => {
+ vi.mocked(deps.activity).mockResolvedValue(activity)
+ expect(await service.request(request())).toEqual({ error: 'SESSION_NOT_IDLE', activity })
+ expect(deps.stop).not.toHaveBeenCalled()
+ expect(await service.request(request('now'))).toEqual({ closed: true })
+ expect(deps.checkpoint).toHaveBeenCalledOnce()
+})
+it.each(['session', 'creation'] as const)('rejects an outdated %s before reading or stopping', async part => {
+ const stale = request()
+ if (part === 'session') row.sessionId = 'new'
+ else row.registeredAt++
+ expect(await service.request(stale)).toEqual({ error: 'AGENT_CHANGED' })
+ expect(deps.activity).not.toHaveBeenCalled()
+ expect(deps.stop).not.toHaveBeenCalled()
+})
+it('rechecks activity after the checkpoint so newly started work stays alive', async () => {
+ vi.mocked(deps.activity).mockResolvedValueOnce('idle').mockResolvedValue('working')
+ expect(await service.request(request())).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'working' })
+ expect(registry.byAgent(row.agentId)).toBe(row)
+})
+it('requires an explicit choice when another window is using an idle session', async () => {
+ expect(await service.request(request('inspect'), () => true)).toEqual({ activity: 'in_use' })
+ expect(await service.request(request('idle'), () => true)).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'in_use' })
+ expect(deps.stop).not.toHaveBeenCalled()
+ expect(await service.request(request('now'), () => true)).toEqual({ closed: true })
+})
+it('does not stop if another view opens during the backup', async () => {
+ let opened = false
+ vi.mocked(deps.checkpoint).mockImplementation(async () => { opened = true })
+ expect(await service.request(request(), () => opened)).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'in_use' })
+ expect(registry.byAgent(row.agentId)).toBe(row)
+})
+it('checkpoint failure retains the session and reports the failure', async () => {
+ vi.mocked(deps.checkpoint).mockRejectedValue(Object.assign(new Error('Disk full'), { code: 'HISTORY_NOT_SAVED' }))
+ expect(await service.request(request())).toMatchObject({ error: 'HISTORY_NOT_SAVED', detail: 'Disk full' })
+ expect(registry.byAgent(row.agentId)).toBe(row)
+})
+it('joins repeated clicks and cancels a pending close when reopened during its backup', async () => {
+ let finish!: () => void
+ vi.mocked(deps.checkpoint).mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const first = service.request(request())
+ expect(service.request(request())).toBe(first)
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
+ service.cancel(row.agentId)
+ finish()
+ expect((await first).error).toBeTruthy()
+ expect(registry.byAgent(row.agentId)).toBe(row)
+})
+it('persists a deferred close, survives a daemon restart and waits for sustained idle', async () => {
+ vi.mocked(deps.activity).mockResolvedValue('working')
+ expect(await service.request(request('after_task'))).toEqual({ deferred: true })
+ const plan = row.closePlan!
+ expect(plan.state).toBe('waiting')
+ expect(deps.stop).not.toHaveBeenCalled()
+ expect(await service.request(request('after_task'))).toEqual({ deferred: true })
+ expect(row.closePlan?.id).toBe(plan.id)
+ service.dispose()
+ registry.load()
+ row = registry.byAgent(row.agentId)!
+ expect(row.closePlan?.id).toBe(plan.id)
+ service = new CloseAgentService(deps)
+ await service.tick()
+ vi.mocked(deps.activity).mockResolvedValue('idle')
+ await service.tick()
+ expect(deps.stop).not.toHaveBeenCalled()
+ time += 5_000
+ await service.tick()
+ expect(deps.stop).toHaveBeenCalledOnce()
+})
+it('keeps questions and subsequent turns alive during a deferred close', async () => {
+ await service.request(request('after_task'))
+ await service.tick()
+ time += 5_000
+ vi.mocked(deps.activity).mockResolvedValue('needs_input')
+ await service.tick()
+ vi.mocked(deps.activity).mockResolvedValue('working')
+ await service.tick()
+ vi.mocked(deps.activity).mockResolvedValue('idle')
+ await service.tick()
+ expect(deps.stop).not.toHaveBeenCalled()
+ time += 5_000
+ await service.tick()
+ expect(deps.stop).toHaveBeenCalledOnce()
+})
+it.each(['cancel', 'new-process', 'new-conversation'] as const)('does not execute a queued close after %s', async action => {
+ await service.request(request('after_task'))
+ await service.tick()
+ time += 5_000
+ if (action === 'cancel') expect(await service.request(request('cancel'))).toEqual({ cancelled: true })
+ else if (action === 'new-process') row.processIdentity!.startMarker = 'replacement'
+ else row.sessionId = 'replacement'
+ await service.tick()
+ expect(deps.stop).not.toHaveBeenCalled()
+ expect(row.closePlan).toBeUndefined()
+})
+it('reports one deferred save failure instead of retrying forever', async () => {
+ await service.request(request('after_task'))
+ await service.tick()
+ vi.mocked(deps.checkpoint).mockRejectedValue(new Error('Disk full'))
+ time += 5_000
+ await service.tick()
+ expect(row.closePlan).toMatchObject({ state: 'failed', detail: 'Disk full' })
+ await service.tick()
+ expect(deps.stop).toHaveBeenCalledOnce()
+})
+it('will not acknowledge a deferred close when durable storage fails', async () => {
+ vi.spyOn(registry, 'setClosePlan').mockImplementation(() => { throw new Error('Disk full') })
+ expect(await service.request(request('after_task'))).toMatchObject({ error: 'CLOSE_FAILED' })
+ expect(deps.stop).not.toHaveBeenCalled()
+})
+
+it('uses a known empty composer, not inactivity, to establish idle', () => {
+ const screen = '›\n\n 100% context left'
+ expect(inspectCloseActivity('codex', screen, false, false)).toBe('idle')
+ expect(inspectCloseActivity('codex', screen, undefined, false)).toBe('unknown')
+ expect(inspectCloseActivity('codex', screen, true, false)).toBe('working')
+ expect(inspectCloseActivity('codex', screen, false, true)).toBe('needs_input')
+ expect(inspectCloseActivity('codex', null, false, false)).toBe('unknown')
+ expect(inspectCloseActivity('codex', '› A draft\n 100% context left', false, false)).toBe('draft')
+ expect(inspectCloseActivity('codex', `${screen}\n ◎ /goal active (41m)`, false, false)).toBe('working')
+ expect(inspectCloseActivity('claude', '❯\n 2 background tasks', false, false)).toBe('working')
+})
+
+it('automatically stops only after two timer observations of sustained idle', async () => {
+ vi.useFakeTimers()
+ service.dispose()
+ const { now: _now, ...realClock } = deps
+ service = new CloseAgentService(realClock)
+ await service.request(request('after_task'))
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(deps.stop).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(deps.stop).toHaveBeenCalledOnce()
+ service.dispose()
+ await service.tick()
+})
+it('resets a deferred idle observation after a failed read instead of stopping on stale evidence', async () => {
+ await service.request(request('after_task'))
+ await service.tick()
+ time += 5_000
+ vi.mocked(deps.activity).mockRejectedValueOnce(new Error('disconnected'))
+ await service.tick()
+ await service.tick()
+ expect(deps.stop).not.toHaveBeenCalled()
+ time += 4_999
+ await service.tick()
+ expect(deps.stop).not.toHaveBeenCalled()
+ time += 1
+ await service.tick()
+ expect(deps.stop).toHaveBeenCalledOnce()
+})
+it('rejects a disposed service and a target replaced while reading activity', async () => {
+ service.dispose()
+ expect(await service.request(request('inspect'))).toEqual({ error: 'AGENT_CHANGED' })
+ service = new CloseAgentService(deps)
+ vi.mocked(deps.activity).mockImplementation(async () => { row.processIdentity!.pid++; return 'idle' })
+ expect(await service.request(request('inspect'))).toEqual({ error: 'AGENT_CHANGED' })
+ expect(deps.stop).not.toHaveBeenCalled()
+})
+it.each(['unbound', 'terminal'])('never automatically closes %s work on an empty composer alone', async kind => {
+ if (kind === 'unbound') row.sessionId = ''
+ else row.engine = 'terminal'
+ expect(await service.request(request('idle'))).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'unknown' })
+ expect(deps.stop).not.toHaveBeenCalled()
+})
+it('retains the pane if cancellation arrives during the final activity check', async () => {
+ vi.mocked(deps.activity).mockResolvedValueOnce('idle').mockImplementationOnce(async () => { service.cancel(row.agentId); return 'idle' })
+ expect((await service.request(request())).error).toBe('CLOSE_FAILED')
+ expect(registry.byAgent(row.agentId)).toBeTruthy()
+})
+it('returns a useful error when storage throws a non-Error value', async () => {
+ vi.mocked(deps.checkpoint).mockRejectedValue('disk failure')
+ expect(await service.request(request())).toMatchObject({ error: 'CLOSE_FAILED', detail: 'Could not close this session safely. Please try again.' })
+})
+it('does not stop a cancelled deferred plan after its activity read finishes', async () => {
+ await service.request(request('after_task'))
+ vi.mocked(deps.activity).mockImplementationOnce(async () => { service.cancel(row.agentId); return 'idle' })
+ await service.tick()
+ expect(deps.stop).not.toHaveBeenCalled()
+})
+it('a concurrent deferred tick never starts a second stop', async () => {
+ await service.request(request('after_task'))
+ let finish!: () => void
+ vi.mocked(deps.checkpoint).mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const closing = service.request(request())
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
+ await service.tick()
+ expect(deps.stop).toHaveBeenCalledOnce()
+ finish(); await closing
+})
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
new file mode 100644
index 000000000..caf801628
--- /dev/null
+++ b/cli/src/lib/closeAgentService.ts
@@ -0,0 +1,186 @@
+/** User Close is a disk-backed lifecycle operation. Hiding/switching a tab never calls this. */
+import { stripVTControlCharacters } from 'node:util'
+import { randomUUID } from 'node:crypto'
+import { teamWriteHold } from '../teams/preflight.js'
+import { terminalActivity } from '../cable/terminalActivity.js'
+import type { RegisteredSession, registry as liveRegistry } from './registry.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+import type { StopAgentOptions } from './stopAgentService.js'
+import { resumeMode } from './resumeCapability.js'
+
+export type CloseActivity = 'idle' | 'working' | 'needs_input' | 'draft' | 'in_use' | 'unknown'
+export type CloseMode = 'inspect' | 'idle' | 'now' | 'after_task' | 'cancel'
+export type AgentClosePlan = {
+ id: string
+ requestedAt: number
+ identity: string
+ state: 'waiting' | 'failed'
+ detail?: string
+}
+export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode }
+export type AgentCloseResult = { closed?: true; deferred?: true; cancelled?: true; error?: string; detail?: string; activity?: CloseActivity }
+
+/** A quiet CPU is never evidence of an idle agent. Require both its engine state and empty composer. */
+export function inspectCloseActivity(engine: RegisteredSession['engine'], screen: string | null,
+ turnOpen: boolean | undefined, needsInput: boolean): CloseActivity {
+ if (needsInput) return 'needs_input'
+ if (turnOpen === true) return 'working'
+ if (!screen) return 'unknown'
+ const footer = stripVTControlCharacters(screen).split('\n').slice(-16).join('\n')
+ // Codex can be between turns of an active goal; Claude can have background tasks.
+ if (/\bgoal\s+active\b|\b[1-9]\d*\s+background\s+(?:tasks?|agents?)\b/i.test(footer)
+ || terminalActivity(engine, screen)) return 'working'
+ const hold = teamWriteHold(engine, screen)
+ if (hold === 'team_waiting_draft') return 'draft'
+ if (hold === 'team_waiting_user') return 'needs_input'
+ if (hold || turnOpen === undefined) return 'unknown'
+ return 'idle'
+}
+
+function identity(s: RegisteredSession): string {
+ return JSON.stringify([s.agentId, s.sessionId, s.engine, s.registeredAt, s.processIdentity?.pid,
+ s.processIdentity?.startMarker, s.processIdentity?.executable, s.runtimes.map(terminalRouteKey).sort()])
+}
+function matches(s: RegisteredSession | undefined, request: AgentCloseRequest): s is RegisteredSession {
+ return !!s && s.sessionId === request.sessionId && new Date(s.registeredAt).toISOString() === request.createdAt
+}
+
+export interface CloseAgentServiceDeps {
+ registry: Pick<typeof liveRegistry, 'byAgent' | 'list' | 'setClosePlan'>
+ activity(s: RegisteredSession): Promise<CloseActivity>
+ checkpoint(s: RegisteredSession, explicitlyStopped: boolean, phase: 'before' | 'after'): Promise<void>
+ stop(agentId: string, options: StopAgentOptions): Promise<void>
+ changed(s: RegisteredSession): void
+ now?: () => number
+}
+
+class CloseRefused extends Error {
+ constructor(readonly activity: CloseActivity) { super('The session is not idle.') }
+}
+
+/** Only explicitly deferred closes own a timer. Their intent survives an app/daemon restart,
+ * but is never transferred to a replacement process or another conversation under the same ID. */
+export class CloseAgentService {
+ private readonly jobs = new Map<string, Promise<AgentCloseResult>>()
+ private readonly idleSince = new Map<string, number>()
+ private readonly revisions = new Map<string, number>()
+ private timer: ReturnType<typeof setTimeout> | null = null
+ private disposed = false
+ private readonly now: () => number
+ constructor(private readonly deps: CloseAgentServiceDeps) { this.now = deps.now ?? Date.now }
+
+ start(): void { this.schedule() }
+ dispose(): void { this.disposed = true; if (this.timer) clearTimeout(this.timer); this.timer = null }
+
+ /** Opening a queued session means it should stay available. No other queued work is affected. */
+ cancel(agentId: string): void {
+ this.revisions.set(agentId, (this.revisions.get(agentId) ?? 0) + 1)
+ this.idleSince.delete(agentId)
+ if (!this.deps.registry.byAgent(agentId)?.closePlan) return
+ const updated = this.deps.registry.setClosePlan(agentId, null)
+ if (updated) this.deps.changed(updated)
+ if (!this.pending().length && this.timer) { clearTimeout(this.timer); this.timer = null }
+ }
+
+ request(request: AgentCloseRequest, otherViews: () => boolean = () => false): Promise<AgentCloseResult> {
+ const current = this.deps.registry.byAgent(request.agentId)
+ if (!matches(current, request)) return Promise.resolve({ error: 'AGENT_CHANGED' })
+ if (request.mode === 'cancel') { this.cancel(request.agentId); return Promise.resolve({ cancelled: true }) }
+ const pending = this.jobs.get(request.agentId)
+ if (pending) return pending
+ const target = identity(current)
+ const revision = this.revisions.get(request.agentId) ?? 0
+ const job = this.execute(request, target, revision, otherViews).finally(() => {
+ if (this.jobs.get(request.agentId) === job) this.jobs.delete(request.agentId)
+ this.schedule()
+ })
+ this.jobs.set(request.agentId, job)
+ return job
+ }
+
+ private async execute(request: AgentCloseRequest, target: string, revision: number, otherViews: () => boolean): Promise<AgentCloseResult> {
+ const current = () => {
+ const s = this.deps.registry.byAgent(request.agentId)
+ return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision
+ && s && identity(s) === target ? s : undefined
+ }
+ try {
+ const s = current()
+ if (!s) return { error: 'AGENT_CHANGED' }
+ const observed = await this.deps.activity(s)
+ const activity = otherViews() ? 'in_use'
+ : observed === 'idle' && (!s.sessionId || resumeMode(s.engine) !== 'conversation') ? 'unknown' : observed
+ if (!current()) return { error: 'AGENT_CHANGED' }
+ if (request.mode === 'inspect') return { activity }
+ if (request.mode === 'after_task') {
+ if (s.closePlan?.identity === target && s.closePlan.state === 'waiting') return { deferred: true }
+ const updated = this.deps.registry.setClosePlan(s.agentId, { id: randomUUID(), identity: target, requestedAt: this.now(), state: 'waiting' })
+ this.idleSince.delete(s.agentId)
+ if (updated) this.deps.changed(updated)
+ this.schedule()
+ return { deferred: true }
+ }
+ if (request.mode === 'idle' && activity !== 'idle') return { error: 'SESSION_NOT_IDLE', activity }
+ await this.deps.stop(s.agentId, {
+ current: () => !!current() && (request.mode === 'now' || !otherViews()),
+ checkpoint: (s, phase) => this.deps.checkpoint(s, request.mode === 'now', phase),
+ beforeStop: async () => {
+ const latest = current()
+ if (!latest) throw new Error('The session changed while saving. Please try again.')
+ if (request.mode !== 'now') {
+ if (otherViews()) throw new CloseRefused('in_use')
+ const activity = await this.deps.activity(latest)
+ if (activity !== 'idle') throw new CloseRefused(activity)
+ if (!current()) throw new Error('The session changed while saving. Please try again.')
+ }
+ },
+ })
+ this.idleSince.delete(s.agentId)
+ return { closed: true }
+ } catch (error) {
+ if (error instanceof CloseRefused) return { error: 'SESSION_NOT_IDLE', activity: error.activity }
+ const code = (error as { code?: unknown })?.code
+ return { error: typeof code === 'string' ? code : 'CLOSE_FAILED',
+ detail: error instanceof Error ? error.message : 'Could not close this session safely. Please try again.' }
+ }
+ }
+
+ private pending(): RegisteredSession[] { return this.deps.registry.list().filter(s => s.closePlan?.state === 'waiting') }
+ private schedule(): void {
+ if (this.disposed || this.timer || !this.pending().length) return
+ this.timer = setTimeout(() => { this.timer = null; void this.tick().finally(() => this.schedule()) }, 5_000)
+ this.timer.unref?.()
+ }
+ async tick(): Promise<void> {
+ if (this.disposed) return
+ // Serial reads avoid a process/transcript sampling burst when a whole tab was closed.
+ for (const s of this.pending()) {
+ if (this.disposed) return
+ if (this.jobs.has(s.agentId)) continue
+ const plan = s.closePlan!
+ if (identity(s) !== plan.identity) { this.cancel(s.agentId); continue }
+ try {
+ const activity = await this.deps.activity(s)
+ if (this.disposed || this.deps.registry.byAgent(s.agentId)?.closePlan?.id !== plan.id) continue
+ if (activity !== 'idle') { this.idleSince.delete(s.agentId); continue }
+ const since = this.idleSince.get(s.agentId)
+ if (since === undefined) { this.idleSince.set(s.agentId, this.now()); continue }
+ // A turn boundary alone is not completion. Give chained turns and delayed questions time to surface.
+ if (this.now() - since < 5_000) continue
+ const result = await this.request({ agentId: s.agentId, sessionId: s.sessionId,
+ createdAt: new Date(s.registeredAt).toISOString(), mode: 'idle' })
+ if (result.error && result.error !== 'SESSION_NOT_IDLE') {
+ const latest = this.deps.registry.byAgent(s.agentId)
+ if (latest?.closePlan?.id === plan.id) {
+ const changed = this.deps.registry.setClosePlan(s.agentId, { ...plan, state: 'failed',
+ detail: result.detail ?? 'Could not save and close this session. Open it to try again.' })
+ if (changed) this.deps.changed(changed)
+ }
+ }
+ } catch {
+ // A read failure is unknown activity, never proof that the task finished.
+ this.idleSince.delete(s.agentId)
+ }
+ }
+ }
+}
diff --git a/cli/src/lib/codexSessionLifecycle.spec.ts b/cli/src/lib/codexSessionLifecycle.spec.ts
new file mode 100644
index 000000000..9aad6c515
--- /dev/null
+++ b/cli/src/lib/codexSessionLifecycle.spec.ts
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { stopSharedCodexSession, type CodexStopDeps } from './codexSessionLifecycle.js'
+import { registry, type RegisteredSession } from './registry.js'
+let row: RegisteredSession
+let deps: CodexStopDeps
+let request: ReturnType<typeof vi.fn<(method: string, params?: Record<string, unknown>) => Promise<any>>>
+let close: ReturnType<typeof vi.fn<() => void>>
+let loaded: boolean
+beforeEach(() => {
+ row = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%500' }], cwd: '/tmp', codexHome: '/tmp/fixture-home' })!
+ Object.assign(row, { sessionId: 'conversation' })
+ loaded = true
+ request = vi.fn(async (method: string) => {
+ if (method === 'thread/read') return { thread: { id: row.sessionId, status: { type: loaded ? 'active' : 'notLoaded' } } }
+ if (method === 'thread/goal/get') return { goal: { status: 'active' } }
+ if (method === 'thread/turns/list') return { data: [{ id: 'turn', status: 'inProgress' }] }
+ if (method === 'thread/archive') loaded = false
+ return {}
+ })
+ close = vi.fn()
+ deps = { daemonIdentity: vi.fn(async () => ({ pid: 78, processStartTime: 'Thu Oct 1 01:00:00 2026' })),
+ rows: vi.fn(async () => [{ pid: 78, parentPid: 1, executable: 'codex', args: 'codex app-server', startMarker: 'Thu Oct 1 01:00:00 2026' }]),
+ connect: vi.fn(async () => ({ request, close })),
+ }
+})
+afterEach(() => { for (const entry of registry.list()) registry.removeAgent(entry.agentId) })
+it('stops only the named conversation and restores its disk history without restarting it', async () => {
+ await stopSharedCodexSession(row, () => true, deps)
+ expect(request.mock.calls.map(([method]) => method)).toEqual(['thread/read', 'thread/goal/get', 'thread/goal/set', 'thread/turns/list', 'turn/interrupt', 'thread/archive', 'thread/unarchive', 'thread/read'])
+ for (const [, params] of request.mock.calls) expect(params).toMatchObject({ threadId: 'conversation' })
+ expect(close).toHaveBeenCalledOnce()
+})
+it.each(['other engine', 'no daemon', 'old pid', 'recycled pid'])('does not contact a server for %s', async mode => {
+ if (mode === 'other engine') row.engine = 'claude'
+ if (mode === 'no daemon') vi.mocked(deps.daemonIdentity).mockResolvedValue(null)
+ if (mode === 'old pid') vi.mocked(deps.rows).mockResolvedValue([])
+ if (mode === 'recycled pid') vi.mocked(deps.rows).mockResolvedValue([{ pid: 78, parentPid: 1, executable: 'codex', args: '', startMarker: 'replacement' }])
+ await stopSharedCodexSession(row, () => true, deps)
+ expect(deps.connect).not.toHaveBeenCalled()
+})
+it('refuses an unreadable process table or an unbound conversation before controlling a server', async () => {
+ vi.mocked(deps.rows).mockResolvedValueOnce(null)
+ await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow('verify')
+ row.sessionId = ''
+ await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow('identify')
+ expect(deps.connect).not.toHaveBeenCalled()
+})
+it('leaves a process-owned conversation and an unrelated shared server untouched', async () => {
+ loaded = false
+ await stopSharedCodexSession(row, () => true, deps)
+ expect(request.mock.calls.map(([method]) => method)).toEqual(['thread/read'])
+ expect(close).toHaveBeenCalledOnce()
+})
+it('does not interrupt a completed turn or pause a completed goal', async () => {
+ const normal = request.getMockImplementation()!
+ request.mockImplementation(async (method: string) => {
+ if (method === 'thread/goal/get') return { goal: null }
+ if (method === 'thread/turns/list') return { data: [{ status: 'completed' }] }
+ return normal(method)
+ })
+ await stopSharedCodexSession(row, () => true, deps)
+ expect(request.mock.calls.some(([method]) => method === 'turn/interrupt' || method === 'thread/goal/set')).toBe(false)
+})
+it.each(['thread/read', 'thread/goal/get', 'thread/goal/set', 'thread/turns/list', 'turn/interrupt'])('honors a cancellation after %s before the next destructive request', async boundary => {
+ let current = true
+ const normal = request.getMockImplementation()!
+ request.mockImplementation(async (method: string) => { const result = await normal(method); if (method === boundary) current = false; return result })
+ await expect(stopSharedCodexSession(row, () => current, deps)).rejects.toThrow('cancelled')
+ expect(request.mock.calls.some(([method]) => method === 'thread/archive')).toBe(false)
+ expect(close).toHaveBeenCalledOnce()
+})
+it('restores the archived history even when reopened while archive was in flight', async () => {
+ let current = true
+ const normal = request.getMockImplementation()!
+ request.mockImplementation(async (method: string) => { const result = await normal(method); if (method === 'thread/archive') current = false; return result })
+ await expect(stopSharedCodexSession(row, () => current, deps)).rejects.toThrow('cancelled')
+ expect(request).toHaveBeenCalledWith('thread/unarchive', { threadId: row.sessionId })
+})
+it.each(['before', 'after'])('rejects the wrong conversation %s archive', async when => {
+ const normal = request.getMockImplementation()!
+ request.mockImplementation(async (method: string) => method === 'thread/read' && (when === 'before' || !loaded)
+ ? { thread: { id: 'somebody-else', status: { type: 'notLoaded' } } } : normal(method))
+ await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow(when === 'before' ? 'different conversation' : 'confirm')
+ expect(close).toHaveBeenCalledOnce()
+})
+it('does not claim a shared thread stopped when it remains loaded', async () => {
+ const normal = request.getMockImplementation()!
+ request.mockImplementation(async (method: string) => { const result = await normal(method); loaded = true; return result })
+ await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow('confirm')
+})
+it('closes the connection and leaves the terminal alone on a failed API request', async () => {
+ request.mockRejectedValueOnce(new Error('disconnected'))
+ await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow('disconnected')
+ expect(close).toHaveBeenCalledOnce()
+})
+
+it('returns history to sessions even if archive times out after being applied', async () => {
+ const normal = request.getMockImplementation()!
+ request.mockImplementation(async (method: string) => {
+ const result = await normal(method)
+ if (method === 'thread/archive') throw new Error('timed out')
+ return result
+ })
+ await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow('timed out')
+ expect(request).toHaveBeenCalledWith('thread/unarchive', { threadId: row.sessionId })
+ expect(close).toHaveBeenCalledOnce()
+})
+
+it.each(['codex --no-daemon resume conversation', '/usr/bin/node /bin/codex.js --no-daemon resume conversation'])('does not contact an unrelated shared server for an owned TUI: %s', async args => {
+ row.processIdentity = { pid: 99, startMarker: 'born', executable: 'codex' }
+ vi.mocked(deps.rows).mockResolvedValue([{ ...row.processIdentity, parentPid: 1, args }])
+ await stopSharedCodexSession(row, () => true, deps)
+ expect(deps.connect).not.toHaveBeenCalled()
+})
+
+it.each(['codex --remote ws://fixture.invalid resume conversation', 'codex resume --remote=ws://fixture.invalid conversation'])('refuses to claim remote work stopped: %s', async args => {
+ row.processIdentity = { pid: 99, startMarker: 'born', executable: 'codex' }
+ vi.mocked(deps.rows).mockResolvedValue([{ ...row.processIdentity, parentPid: 1, args }])
+ vi.mocked(deps.daemonIdentity).mockResolvedValue(null)
+ await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow('remote Codex server')
+ expect(deps.connect).not.toHaveBeenCalled()
+})
diff --git a/cli/src/lib/codexSessionLifecycle.ts b/cli/src/lib/codexSessionLifecycle.ts
new file mode 100644
index 000000000..bad587894
--- /dev/null
+++ b/cli/src/lib/codexSessionLifecycle.ts
@@ -0,0 +1,154 @@
+/** Codex's shared app-server owns work independently of its terminal client.
+ * Never kill that server: unload only the confirmed conversation, leaving its
+ * history available and all other clients running. New Harness launches opt out
+ * of sharing, but sessions opened before an upgrade still need this path. */
+import { spawn } from 'node:child_process'
+import { Duplex } from 'node:stream'
+import { readFile, realpath } from 'node:fs/promises'
+import { basename, join } from 'node:path'
+import WebSocket from 'ws'
+import { env } from '../config/env.js'
+import { engineBin } from './engineBin.js'
+import { argvTokens, processRows, type ProcessRow } from './tmux.js'
+import type { RegisteredSession } from './registry.js'
+
+export interface CodexControl {
+ request(method: string, params: Record<string, unknown>): Promise<any>
+ close(): void
+}
+
+/** The CLI resolves its own socket location. It does not start a server. `proxy`
+ * carries raw WebSocket bytes (not JSONL), as documented by Codex app-server. */
+export async function connectCodexControl(home: string): Promise<CodexControl> {
+ const child = spawn(engineBin('codex'), ['app-server', 'proxy'], {
+ env: { ...process.env, CODEX_HOME: home }, stdio: ['pipe', 'pipe', 'ignore'],
+ })
+ const pipe = Duplex.from({ readable: child.stdout, writable: child.stdin })
+ const ws = new WebSocket('ws://localhost/', { createConnection: () => pipe as any,
+ handshakeTimeout: 3_000, maxPayload: 2 << 20, perMessageDeflate: false })
+ let nextId = 0
+ const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }>()
+ const fail = (error: Error) => {
+ for (const entry of pending.values()) { clearTimeout(entry.timer); entry.reject(error) }
+ pending.clear()
+ }
+ const close = () => { fail(new Error('Codex control connection closed')); ws.terminate(); pipe.destroy(); child.kill() }
+ child.on('error', error => { fail(error); ws.terminate() })
+ child.on('exit', () => { fail(new Error('Codex control proxy exited')); ws.terminate() })
+ pipe.on('error', error => { fail(error); ws.terminate() })
+ ws.on('error', fail)
+ ws.on('close', () => { fail(new Error('Codex control connection closed')); pipe.destroy(); child.kill() })
+ ws.on('message', bytes => {
+ try {
+ const frame = JSON.parse(String(bytes))
+ const entry = pending.get(frame.id)
+ if (!entry) return
+ pending.delete(frame.id); clearTimeout(entry.timer)
+ if (frame.error) entry.reject(new Error(`Codex could not ${String(frame.error.message ?? 'complete the request').slice(0, 300)}`))
+ else entry.resolve(frame.result)
+ } catch { fail(new Error('Invalid Codex control response')); ws.terminate() }
+ })
+ const request: CodexControl['request'] = (method, params) => new Promise((resolve, reject) => {
+ if (ws.readyState !== WebSocket.OPEN) { reject(new Error('Codex control is unavailable')); return }
+ const id = ++nextId
+ const timer = setTimeout(() => { pending.delete(id); reject(new Error('Codex control request timed out')) }, 5_000)
+ pending.set(id, { resolve, reject, timer })
+ ws.send(JSON.stringify({ id, method, params }), error => {
+ if (error) { clearTimeout(timer); pending.delete(id); reject(error) }
+ })
+ })
+ try {
+ await new Promise<void>((resolve, reject) => {
+ ws.once('open', resolve); ws.once('error', reject)
+ ws.once('close', () => reject(new Error('Codex control connection closed')))
+ })
+ const initialized = await request('initialize', { clientInfo: { name: 'harness', version: '1' }, capabilities: { experimentalApi: true } })
+ if (typeof initialized?.codexHome !== 'string' || await realpath(initialized.codexHome) !== await realpath(home)) {
+ throw new Error('Codex returned a different session store')
+ }
+ ws.send(JSON.stringify({ method: 'initialized' }))
+ return { request, close }
+ } catch (error) { close(); throw error }
+}
+
+async function daemonIdentity(home: string): Promise<{ pid: number; processStartTime: string } | null> {
+ try {
+ const value = JSON.parse(await readFile(join(home, 'app-server-daemon', 'daemon.pid'), 'utf8'))
+ if (!Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.processStartTime !== 'string') throw new Error('Invalid Codex server identity')
+ return value
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw error
+ }
+}
+
+export interface CodexStopDeps {
+ daemonIdentity(home: string): Promise<{ pid: number; processStartTime: string } | null>
+ rows(): Promise<ProcessRow[] | null>
+ connect(home: string): Promise<CodexControl>
+}
+
+/** Called AFTER a checkpoint and BEFORE signalling the terminal. There is no
+ * polling, model call, archive deletion or machine-wide daemon shutdown here. */
+export async function stopSharedCodexSession(session: RegisteredSession, current: () => boolean,
+ deps: CodexStopDeps = { daemonIdentity, rows: processRows, connect: connectCodexControl }): Promise<void> {
+ if (session.engine !== 'codex') return
+ const home = session.codexHome || env.CODEX_HOME
+ const rows = await deps.rows()
+ if (!rows) throw new Error('Could not verify the Codex server before stopping')
+ const owner = rows.find(row => row.pid === session.processIdentity?.pid && row.startMarker === session.processIdentity?.startMarker && row.executable === session.processIdentity?.executable)
+ if (owner) {
+ const args = argvTokens(owner.args)
+ // Harness inserts this as the FIRST option, before resume/fork or prompt
+ // text. A prompt merely mentioning --no-daemon is not proof of ownership.
+ const option = /^node(?:\.exe)?$/.test(basename(args[0] ?? '')) && /(?:^|\/)codex(?:\.js)?$/.test(args[1] ?? '') ? 2 : 1
+ // A remote app-server is not controlled by this machine's profile. Do not
+ // report its work stopped merely because its local terminal was closed.
+ if (args.slice(option).some(arg => arg === '--remote' || arg.startsWith('--remote='))) {
+ throw new Error('Stop this conversation on its remote Codex server before closing its terminal')
+ }
+ if (args[option] === '--no-daemon') return
+ }
+ const daemon = await deps.daemonIdentity(home)
+ if (!daemon) return // Older/process-owned Codex has no detached writer.
+ const normalize = (value: string) => value.trim().replace(/\s+/g, ' ')
+ if (!rows.some(row => row.pid === daemon.pid && normalize(row.startMarker) === normalize(daemon.processStartTime))) return
+ if (!session.sessionId) throw new Error('Could not identify the conversation on the Codex server; the session is still open')
+ const control = await deps.connect(home)
+ const guard = () => { if (!current()) throw new Error('The close request was cancelled or the session changed') }
+ try {
+ guard()
+ const read = await control.request('thread/read', { threadId: session.sessionId })
+ if (read?.thread?.id !== session.sessionId) throw new Error('Codex returned a different conversation')
+ if (read.thread.status?.type === 'notLoaded') return
+ // A process-owned session can share its profile with an unrelated daemon;
+ // thread/read reports notLoaded there and none of the calls below occur.
+ const goal = await control.request('thread/goal/get', { threadId: session.sessionId })
+ guard()
+ if (goal?.goal?.status === 'active') {
+ await control.request('thread/goal/set', { threadId: session.sessionId, status: 'paused' })
+ }
+ guard()
+ const turns = await control.request('thread/turns/list', { threadId: session.sessionId, limit: 1, itemsView: 'summary' })
+ guard()
+ const active = turns?.data?.find((turn: any) => turn.status === 'inProgress')
+ if (active) await control.request('turn/interrupt', { threadId: session.sessionId, turnId: active.id })
+ guard()
+ // Archive is the public operation that unloads a thread. Unarchive moves
+ // only its saved history back; it does not restart the thread. Always undo
+ // the archive even if the user reopens while its response is in flight.
+ let archiveError: unknown
+ try { await control.request('thread/archive', { threadId: session.sessionId }) }
+ catch (error) { archiveError = error }
+ // A timed-out reply does not prove the archive failed to happen. Always
+ // attempt to return the history to sessions before reporting the error.
+ try { await control.request('thread/unarchive', { threadId: session.sessionId }) }
+ catch (error) { throw archiveError ?? error }
+ if (archiveError) throw archiveError
+ guard()
+ const after = await control.request('thread/read', { threadId: session.sessionId })
+ if (after?.thread?.id !== session.sessionId || after.thread.status?.type !== 'notLoaded') {
+ throw new Error('Could not confirm the Codex conversation stopped; its pane remains open')
+ }
+ } finally { control.close() }
+}
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index b75b9ad85..910c9f1e4 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -18,7 +18,7 @@ const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'gr
'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])
const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.
-const MACHINE_REQUESTS = new Set(['git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', ...OWNER_COMMAND_TYPES])
+const MACHINE_REQUESTS = new Set(['agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', ...OWNER_COMMAND_TYPES])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
/** The pair brain, machine to machine (daemons/BRAIN.md). A watch carries question text and recaps; the
* writes (answer, send, stop, start, pause, resume) act on a harness through the owning machine's floor
diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.ts
index f16eda851..6a43e8cab 100644
--- a/cli/src/lib/e2ee/manager.test.ts
+++ b/cli/src/lib/e2ee/manager.test.ts
@@ -475,7 +475,8 @@ describe('E2eeManager persistent remote-password pairing', () => {
mgr.handleFrame(conn, joiner.onPake(takeLast('e2e_pw_pake'))!)
expect(mgr.listPaired().find((p) => p.fingerprint === C.fingerprint(joiner.identity.pub))?.label).toBe(shown)
}
- })
+ // Four real password handshakes need the same scrypt budget as the lockout cases.
+ }, PW_SCRYPT_TEST_TIMEOUT_MS)
it('a wrong password fails the confirmation MAC at round 2 and pins nobody', async () => {
const { mgr, takeLast } = machine()
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index ce55afc42..75f1e398a 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -107,24 +107,30 @@ describe('buildEngineLaunchArgv', () => {
expect(result.out).not.toContain('This pane is a shell now')
})
it('a take-over that waits says so, and starts the engine only once the other process is gone', () => {
+ const folder = mkdtempSync(join(tmpdir(), 'harness-wait-engine-'))
+ const binary = join(folder, 'codex')
+ // /bin/sh --help succeeds on macOS but fails with Ubuntu's dash. A
+ // simulated CLI needs its own help contract for the real startup probe.
+ writeFileSync(binary, '#!/bin/sh\nif [ "$1" = "--help" ]; then echo "fixture CLI"; exit 0; fi\necho "engine ran"\n', { mode: 0o755 })
// Not a child of this process, as the terminal's is not: an unreaped child never looks gone.
const pid = Number(execFileSync('/bin/sh', ['-c', 'sleep 1 >/dev/null 2>&1 & echo $!']).toString().trim())
try {
const argv = buildEngineLaunchArgv('codex', { waitForPid: { pid, name: 'Codex' } }, '/bin/sh', undefined, undefined, NO_TMUX)
const started = Date.now()
- const result = run([argv[0], argv[1], argv[2], 'harness-engine', '/bin/sh', '-c', 'printf "%s\\n" "engine ran"'])
+ const result = run([argv[0], argv[1], argv[2], 'harness-engine', binary])
expect(Date.now() - started).toBeGreaterThanOrEqual(800)
expect(result.out).toContain('Waiting for the Codex in your terminal to finish its turn.')
expect(result.out.indexOf('Waiting for')).toBeLessThan(result.out.indexOf('engine ran'))
expect(result.status).toBe(0)
+ // Nothing to wait for: it starts at once.
+ const immediate = buildEngineLaunchArgv('codex', { waitForPid: { pid: 2 ** 22 + 7, name: 'Codex' } }, '/bin/sh', undefined, undefined, NO_TMUX)
+ const immediateStarted = Date.now()
+ expect(run([immediate[0], immediate[1], immediate[2], 'harness-engine', binary]).out).toContain('engine ran')
+ expect(Date.now() - immediateStarted).toBeLessThan(800)
} finally {
try { process.kill(pid) } catch { /* gone */ }
+ rmSync(folder, { recursive: true, force: true })
}
- // Nothing to wait for: it starts at once.
- const argv = buildEngineLaunchArgv('codex', { waitForPid: { pid: 2 ** 22 + 7, name: 'Codex' } }, '/bin/sh', undefined, undefined, NO_TMUX)
- const started = Date.now()
- expect(run([argv[0], argv[1], argv[2], 'harness-engine', '/bin/sh', '-c', 'printf "%s\\n" "engine ran"']).out).toContain('engine ran')
- expect(Date.now() - started).toBeLessThan(800)
})
it('a command that does not exist still ends the pane with 127, so "not installed" stays a launch failure', () => {
const argv = buildEngineLaunchArgv('claude', {}, '/bin/sh', undefined, undefined, NO_TMUX)
@@ -142,6 +148,31 @@ describe('buildEngineLaunchArgv', () => {
})
})
+ describe('Codex writer ownership', () => {
+ it.each(['supported', 'older', 'failed'] as const)('probes %s startup options without changing prompt arguments', mode => {
+ const folder = mkdtempSync(join(tmpdir(), 'harness-codex-launch-'))
+ try {
+ const binary = join(folder, 'codex fixture')
+ writeFileSync(binary, '#!/bin/sh\nif [ "$1" = "--help" ]; then\n'
+ + (mode === 'failed' ? 'exit 2\n' : `printf '%s\\n' '${mode === 'supported' ? ' --no-daemon Run locally' : ' --model Choose a model'}'\nexit 0\n`)
+ + 'fi\nprintf "<%s>\\n" "$@"\n', { mode: 0o755 })
+ const prelude = engineFallbackPrelude('codex', '/bin/sh', null)
+ const args = ['-c', `${prelude}harness_engine "$@"`, 'harness-engine', binary, 'resume', 'same-conversation', 'literal $(nothing) `nothing` and spaces']
+ if (mode === 'failed') {
+ try { execFileSync('/bin/sh', args, { stdio: ['ignore', 'pipe', 'pipe'] }); expect.fail('launch must refuse an unknown startup mode') }
+ catch (error) {
+ expect((error as any).status).toBe(1)
+ expect(String((error as any).stderr)).toContain('could not verify Codex startup options')
+ expect(String((error as any).stdout)).not.toContain('same-conversation')
+ }
+ } else {
+ const output = execFileSync('/bin/sh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
+ expect(output).toBe(`${mode === 'supported' ? '<--no-daemon>\n' : ''}<resume>\n<same-conversation>\n<literal $(nothing) \`nothing\` and spaces>\n`)
+ }
+ } finally { rmSync(folder, { recursive: true, force: true }) }
+ })
+ })
+
describe('a terminal (engine `terminal`)', () => {
it('is the login shell itself behind a non-interactive wrapper that only raises the limit and enters the folder', () => {
expect(buildEngineLaunchArgv('terminal', { cwd: '/work/project' }, '/bin/zsh')).toEqual([
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index e9290c7ab..46f0bd3b3 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -420,6 +420,7 @@ export function buildEngineLaunchArgv(
if (isTerminalEngine(engine)) return buildTerminalLaunchArgv(opts, shell)
const command = buildEngineCommandArgv(engine, opts)
const interactive = interactiveEngineShell(shell)
+ ?? (engine === 'codex' ? { path: '/bin/sh', args: ['-c'], label: 'shell' } : null)
if (!interactive) return command
const enginePrelude = engineFallbackPrelude(engine, interactive.path, tmuxBinary)
// The clear comes FIRST, before the install as well as before the engine. An installer is a child
@@ -491,6 +492,7 @@ export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tm
? ` [ -n "\${TMUX_PANE:-}" ] && ${shellSingleQuote(tmuxBinary)} set-option -p -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1 || true\n`
: ''
return 'harness_engine() {\n'
+ + (engine === 'codex' ? codexOwnedLaunchPrelude() : '')
+ ' harness_status=0\n'
+ ' "$@" || harness_status=$?\n'
+ ' if [ "$harness_status" -eq 127 ]; then exit 127; fi\n'
@@ -503,6 +505,22 @@ export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tm
+ '}\n'
}
+/** Codex 0.157+ otherwise puts the writer outside tmux in a shared server. Keep
+ * Harness-owned launches process-owned so Close, hook attribution, provider env
+ * and RAM accounting describe the same lifetime. Probe the binary AFTER any
+ * install, in the exact pane shell; older versions simply omit the flag. The
+ * probe is bounded and never changes the user's Codex configuration. */
+function codexOwnedLaunchPrelude(): string {
+ const probe = `const {execFileSync}=require('node:child_process');try { const h=execFileSync(process.argv[1],['--help'],{timeout:5000,maxBuffer:1048576,encoding:'utf8',stdio:['ignore','pipe','pipe']});process.exit(/--no-daemon(?:[^A-Za-z0-9-]|$)/.test(h)?0:64); } catch { process.exit(2); }`
+ return ` harness_codex_mode=0\n`
+ + ` ${shellSingleQuote(process.execPath)} -e ${shellSingleQuote(probe)} "$1" || harness_codex_mode=$?\n`
+ + ` case "$harness_codex_mode" in\n`
+ + ` 0) harness_codex_bin="$1"; shift; set -- "$harness_codex_bin" --no-daemon "$@" ;;\n`
+ + ` 64) ;;\n`
+ + ` *) printf '%s\\n' 'harness: could not verify Codex startup options. Please try opening this session again.' >&2; exit 1 ;;\n`
+ + ` esac\n`
+}
+
/**
* The wordmark, as `cli/scripts/install.sh` prints it when an install is done (its `print_logo`);
* `engineLaunch.spec.ts` holds the two to the same five lines. Printed through `printf '%s\n'` with
diff --git a/cli/src/lib/harnessResources.spec.ts b/cli/src/lib/harnessResources.spec.ts
new file mode 100644
index 000000000..3e214a49e
--- /dev/null
+++ b/cli/src/lib/harnessResources.spec.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it, vi } from 'vitest'
+import { createHarnessResourcesReader, parseResourceProcesses, type ResourceProcess } from './harnessResources.js'
+
+const start = 'Wed Sep 30 10:00:00 2026'
+const row = (pid: number, parent = 1, memoryBytes = 100, cpuMs = 10): ResourceProcess => ({ pid, parent, memoryBytes, cpuMs, start })
+const agent = (agentId: string, pid: number) => ({ agentId, processIdentity: { pid, startMarker: start, executable: 'engine' } })
+
+describe('Harness Monitor readings', () => {
+ it('parses macOS and Linux counters, retaining start identities and valid zero', () => {
+ expect(parseResourceProcesses(`1 0 12 0:01.20 Wed Sep 30 10:00:00 2026
+2 1 0 02:03:04 Wed Sep 30 10:00:00 2026
+3 1 200 1-02:03:04 Wed Sep 30 10:00:00 2026
+not a process`)).toEqual([
+ { ...row(1, 0, 12288, 1200) },
+ { ...row(2, 1, 0, 7384000) },
+ { ...row(3, 1, 204800, 93784000) },
+ ])
+ })
+
+ it('counts each process once across helpers, nested agents and unrelated applications', async () => {
+ const sample = vi.fn(async () => [row(10), row(11, 10), row(12, 11), row(13, 12), row(90)])
+ const read = createHarnessResourcesReader(() => [agent('parent', 10), agent('child', 12)], { sample, now: () => 10_000 })
+ expect(sample).not.toHaveBeenCalled()
+ expect((await read()).agents).toEqual([
+ { agentId: 'parent', memoryBytes: 200, processCount: 2, cpuPercent: null },
+ { agentId: 'child', memoryBytes: 200, processCount: 2, cpuPercent: null },
+ ])
+ })
+
+ it('reports interval CPU, including more than one core, with no second sample on demand', async () => {
+ let now = 10_000, cpuMs = 100
+ const read = createHarnessResourcesReader(() => [agent('a', 10)], {
+ sample: async () => [row(10, 1, 0, cpuMs)], now: () => now,
+ })
+ expect((await read()).agents[0].cpuPercent).toBeNull()
+ now += 5000; cpuMs += 12_500
+ expect((await read()).agents[0]).toMatchObject({ cpuPercent: 250, memoryBytes: 0 })
+ now += 5000
+ expect((await read()).agents[0].cpuPercent).toBe(0)
+ now += 61_000
+ expect((await read()).agents[0].cpuPercent).toBeNull()
+ })
+
+ it('never attributes reused PIDs, duplicate roots or missing identities to an agent', async () => {
+ const read = createHarnessResourcesReader(() => [
+ agent('old', 10), agent('duplicate1', 20), agent('duplicate2', 20), { agentId: 'missing' },
+ ], { sample: async () => [{ ...row(10), start: 'new process' }, row(20)], now: () => 10_000 })
+ for (const result of (await read()).agents) {
+ expect(result).toMatchObject({ memoryBytes: null, cpuPercent: null, processCount: null })
+ }
+ })
+
+ it('coalesces concurrent clients, expires cached data and retries failed reads', async () => {
+ let now = 10_000
+ let finish!: (rows: ResourceProcess[]) => void
+ const sample = vi.fn(() => new Promise<ResourceProcess[]>(resolve => { finish = resolve }))
+ const read = createHarnessResourcesReader(() => [agent('a', 10)], { sample, now: () => now })
+ const first = read()
+ expect(read()).toBe(first)
+ finish([row(10)])
+ const value = await first
+ now += 2499
+ expect(await read()).toBe(value)
+ expect(sample).toHaveBeenCalledTimes(1)
+ now++
+ sample.mockRejectedValueOnce(new Error('denied'))
+ await expect(read()).rejects.toThrow('denied')
+ sample.mockResolvedValueOnce([row(10)])
+ expect((await read()).agents[0].memoryBytes).toBe(100)
+ })
+
+ it('does not follow corrupt parent cycles indefinitely or reuse prior samples after exits', async () => {
+ let now = 10_000
+ const sample = vi.fn(async () => [row(10, 11), row(11, 10)])
+ const read = createHarnessResourcesReader(() => [agent('a', 10)], { sample, now: () => now })
+ expect((await read()).agents[0].memoryBytes).toBe(200)
+ now += 3000; sample.mockResolvedValueOnce([])
+ expect((await read()).agents[0].memoryBytes).toBeNull()
+ })
+})
+
+it('counts a detached shared server once, without assigning its whole RAM to every session', async () => {
+ const agents = [agent('a', 10), agent('b', 20)]
+ let time = 10_000
+ const shared = vi.fn(async () => [
+ { pid: 50, start, agentIds: ['a', 'b'] },
+ { pid: 50, start, agentIds: ['a', 'b'] },
+ { pid: 60, start: 'recycled', agentIds: ['a'] },
+ { pid: 11, start, agentIds: ['a'] },
+ ])
+ const read = createHarnessResourcesReader(() => agents, {
+ sample: async () => [row(10), row(11, 10), row(20), row(50), row(51, 50), row(60)],
+ now: () => time,
+ }, shared)
+ const first = await read()
+ expect(first.agents.map(row => row.memoryBytes)).toEqual([200, 100])
+ expect(first.shared).toEqual([{ kind: 'codex', agentIds: ['a', 'b'], memoryBytes: 200, processCount: 2, cpuPercent: null }])
+ time += 3000
+ expect((await read()).shared![0].cpuPercent).toBe(0)
+})
diff --git a/cli/src/lib/harnessResources.ts b/cli/src/lib/harnessResources.ts
new file mode 100644
index 000000000..17f5dfd7d
--- /dev/null
+++ b/cli/src/lib/harnessResources.ts
@@ -0,0 +1,150 @@
+import { execFile } from 'node:child_process'
+import { readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+import { promisify } from 'node:util'
+import type { ProcessIdentity } from './terminalTypes.js'
+
+const exec = promisify(execFile)
+type Agent = { agentId: string; processIdentity?: ProcessIdentity | null; engine?: string; codexHome?: string | null }
+export type SharedResourceRoot = { pid: number; start: string; agentIds: string[] }
+export interface ResourceProcess {
+ pid: number
+ parent: number
+ memoryBytes: number
+ cpuMs: number
+ start: string
+}
+export interface HarnessResource {
+ agentId: string
+ memoryBytes: number | null
+ cpuPercent: number | null
+ processCount: number | null
+}
+export interface HarnessResources {
+ sampledAt: string
+ agents: HarnessResource[]
+ shared?: Array<Omit<HarnessResource, 'agentId'> & { kind: 'codex'; agentIds: string[] }>
+}
+
+// Reuses Harness Monitor's single process-table / subtree approach. The daemon
+// already knows the owning PID, so no tmux probe, executable-name guessing or
+// transcript scan is needed. Cumulative CPU counters give interval use on both
+// macOS and Linux; ps %cpu would be a lifetime average on Linux.
+export function parseResourceProcesses(text: string): ResourceProcess[] {
+ const rows: ResourceProcess[] = []
+ for (const line of text.split('\n')) {
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)\s+(\S+\s+\S+\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s*$/.exec(line)
+ if (!match) continue
+ const cpuMs = (((Number(match[4] ?? 0) * 24 + Number(match[5] ?? 0)) * 60
+ + Number(match[6])) * 60 + Number(match[7])) * 1000
+ const memoryBytes = Number(match[3]) * 1024
+ if (!Number.isFinite(cpuMs) || !Number.isSafeInteger(memoryBytes)) continue
+ rows.push({ pid: Number(match[1]), parent: Number(match[2]), memoryBytes, cpuMs,
+ start: match[8].replace(/\s+/g, ' ') })
+ }
+ return rows
+}
+
+async function sampleProcesses(): Promise<ResourceProcess[]> {
+ const { stdout } = await exec('ps', ['-axo', 'pid=,ppid=,rss=,time=,lstart='], {
+ encoding: 'utf8', timeout: 2000, maxBuffer: 8 * 1024 * 1024,
+ env: { ...process.env, LC_ALL: 'C' },
+ })
+ const rows = parseResourceProcesses(stdout)
+ if (!rows.length) throw new Error('Process readings unavailable')
+ return rows
+}
+
+/** Read one small identity file per active Codex profile. No transcript scan
+ * or server RPC. Its PID must still pass the same birth check as every agent. */
+async function sharedCodexRoots(agents: readonly Agent[]): Promise<SharedResourceRoot[]> {
+ const profiles = new Map<string, string[]>()
+ for (const agent of agents) {
+ if (agent.engine !== 'codex' || !agent.processIdentity) continue
+ const home = agent.codexHome || env.CODEX_HOME
+ profiles.set(home, [...profiles.get(home) ?? [], agent.agentId])
+ }
+ const roots: SharedResourceRoot[] = []
+ for (const [home, agentIds] of profiles) {
+ try {
+ const text = await readFile(join(home, 'app-server-daemon', 'daemon.pid'), 'utf8')
+ if (text.length > 16384) continue
+ const value = JSON.parse(text)
+ if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.processStartTime === 'string') {
+ roots.push({ pid: value.pid, start: value.processStartTime.replace(/\s+/g, ' '), agentIds })
+ }
+ } catch { /* No running shared server, or its identity cannot be read. */ }
+ }
+ return roots
+}
+
+/** No timer, no retained history and no work until an owning client asks. */
+export function createHarnessResourcesReader(agents: () => readonly Agent[], deps = {
+ sample: sampleProcesses, now: Date.now,
+}, sharedRoots: (agents: readonly Agent[]) => Promise<SharedResourceRoot[]> = sharedCodexRoots) {
+ let previous: { at: number; rows: Map<number, ResourceProcess> } | undefined
+ let cached: { at: number; value: HarnessResources } | undefined
+ let pending: Promise<HarnessResources> | undefined
+ async function read(): Promise<HarnessResources> {
+ const snapshot = await deps.sample()
+ const at = deps.now()
+ const byPid = new Map(snapshot.map(row => [row.pid, row]))
+ const children = new Map<number, number[]>()
+ for (const row of snapshot) {
+ const list = children.get(row.parent) ?? []
+ list.push(row.pid)
+ children.set(row.parent, list)
+ }
+ const current = agents()
+ const owners = new Map<number, string[]>()
+ for (const agent of current) {
+ const identity = agent.processIdentity
+ if (!identity || byPid.get(identity.pid)?.start !== identity.startMarker.replace(/\s+/g, ' ')) continue
+ owners.set(identity.pid, [...owners.get(identity.pid) ?? [], agent.agentId])
+ }
+ const elapsed = previous ? at - previous.at : 0
+ const counted = new Set<number>()
+ const measure = (root: number) => {
+ let memoryBytes = 0, cpuMs = 0, processCount = 0
+ let cpuKnown = elapsed > 0 && elapsed <= 60_000
+ const queue = [root], seen = new Set<number>()
+ while (queue.length) {
+ const pid = queue.pop()!
+ if (seen.has(pid) || (pid !== root && owners.has(pid))) continue
+ seen.add(pid); counted.add(pid)
+ const row = byPid.get(pid)
+ if (!row) continue
+ memoryBytes += row.memoryBytes
+ processCount++
+ const before = previous?.rows.get(pid)
+ if (before?.start === row.start && row.cpuMs >= before.cpuMs) cpuMs += row.cpuMs - before.cpuMs
+ else cpuKnown = false
+ queue.push(...children.get(pid) ?? [])
+ }
+ return { memoryBytes, processCount, cpuPercent: cpuKnown ? Math.round(cpuMs / elapsed * 1000) / 10 : null }
+ }
+ const readings = current.map(agent => {
+ const unknown: HarnessResource = { agentId: agent.agentId, memoryBytes: null, cpuPercent: null, processCount: null }
+ const root = agent.processIdentity?.pid
+ // Refuse stale PIDs and duplicate ownership rather than double-counting.
+ if (!root || owners.get(root)?.length !== 1 || owners.get(root)?.[0] !== agent.agentId) return unknown
+ return { agentId: agent.agentId, ...measure(root) }
+ })
+ const shared: NonNullable<HarnessResources['shared']> = []
+ for (const root of await sharedRoots(current)) {
+ if (counted.has(root.pid) || byPid.get(root.pid)?.start !== root.start) continue
+ shared.push({ kind: 'codex', agentIds: root.agentIds, ...measure(root.pid) })
+ }
+ previous = { at, rows: byPid }
+ const value = { sampledAt: new Date(at).toISOString(), agents: readings, ...(shared.length ? { shared } : {}) }
+ cached = { at, value }
+ return value
+ }
+ return (): Promise<HarnessResources> => {
+ if (pending) return pending
+ if (cached && deps.now() - cached.at >= 0 && deps.now() - cached.at < 2500) return Promise.resolve(cached.value)
+ pending = read().finally(() => { pending = undefined })
+ return pending
+ }
+}
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 8beb4b82d..5ca9fb322 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -70,6 +70,8 @@ function modelString(value: unknown): string | null {
}
export interface RegisteredSession {
+ /** An explicit Close-after-task intent. Never inferred from visibility or CPU use. */
+ closePlan?: import('./closeAgentService.js').AgentClosePlan
/** Per-row marker; the top-level array is retained for backward-reader safety. */
schemaVersion: 2
/** Whether the supported engine process is currently identified; terminal liveness is tracked separately. */
@@ -553,10 +555,11 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {
if (new Set(placements).size !== placements.length) return null
// Taken out of the spread and put back only when it is a real moment: the spread would otherwise
// carry a hand-edited string or a negative number straight into the frame's `toISOString()`.
- const { lastOpenedAt: rawOpenedAt, ...rest } = row
+ const { lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, ...rest } = row
const lastOpenedAt = normalizedOpenedAt(rawOpenedAt)
return {
...rest,
+ ...(normalizedClosePlan(rawClosePlan) ? { closePlan: normalizedClosePlan(rawClosePlan)! } : {}),
schemaVersion: 2,
active,
...(launch ? { launch } : {}),
@@ -607,6 +610,17 @@ function normalizedLaunch(value: unknown): AgentLaunch | undefined {
return { state: 'failed', error, ...(detail ? { detail } : {}) }
}
+function normalizedClosePlan(value: unknown): RegisteredSession['closePlan'] {
+ if (!value || typeof value !== 'object') return undefined
+ const plan = value as Partial<NonNullable<RegisteredSession['closePlan']>>
+ if ((plan.state !== 'waiting' && plan.state !== 'failed') || typeof plan.id !== 'string' || !/^[a-f0-9-]{36}$/.test(plan.id)
+ || typeof plan.identity !== 'string'
+ || !plan.identity || plan.identity.length > 8192 || typeof plan.requestedAt !== 'number'
+ || !Number.isFinite(plan.requestedAt) || plan.requestedAt < 0) return undefined
+ return { id: plan.id, state: plan.state, identity: plan.identity, requestedAt: plan.requestedAt,
+ ...(typeof plan.detail === 'string' ? { detail: plan.detail.slice(0, 500) } : {}) }
+}
+
function validatedRows(values: readonly unknown[]): RegisteredSession[] | null {
const rows: RegisteredSession[] = []
const agents = new Set<string>()
@@ -1016,6 +1030,7 @@ class Registry {
// Rehydrated explicitly for the reason the ⚠️ above gives. A reboot keeps it: it is when a
// person last looked, which no reboot changes.
...(normalizedOpenedAt(raw.lastOpenedAt) !== undefined ? { lastOpenedAt: normalizedOpenedAt(raw.lastOpenedAt) } : {}),
+ ...(!rebooted && normalizedClosePlan(raw.closePlan) ? { closePlan: normalizedClosePlan(raw.closePlan)! } : {}),
}
if (
raw.engine !== engine
@@ -1555,6 +1570,7 @@ class Registry {
// the first hook after an open — the next prompt, a `/clear` — erases it from memory, the next
// save writes that to disk, and every app's "last used" order forgets the open ever happened.
...(existing?.lastOpenedAt ? { lastOpenedAt: existing.lastOpenedAt } : {}),
+ ...(existing?.closePlan ? { closePlan: existing.closePlan } : {}),
}
entry.tmuxPane = tmuxProjection(entry.runtimes)
entry.primaryRuntimeKey = selectedRuntimeKey(entry.runtimes, input.primaryRuntimeKey || existing?.primaryRuntimeKey)
@@ -1755,6 +1771,20 @@ class Registry {
return entry
}
+ setClosePlan(agentId: string, plan: RegisteredSession['closePlan'] | null): RegisteredSession | null {
+ const entry = this.agents.get(agentId)
+ if (!entry) return null
+ const previous = entry.closePlan
+ if (plan) entry.closePlan = normalizedClosePlan(plan)
+ else delete entry.closePlan
+ try { this.save(true) } catch (error) {
+ if (previous) entry.closePlan = previous
+ else delete entry.closePlan
+ throw error
+ }
+ return entry
+ }
+
/** Mark whether at least one backend placement was verified by this daemon process. */
setTerminalAvailable(agentId: string, available: boolean): boolean {
if (!this.agents.has(agentId)) return false
@@ -2010,12 +2040,14 @@ class Registry {
this.saveNames()
}
- private save(): void {
+ private save(strict = false): void {
if (this.transactionDepth > 0) {
+ if (strict) throw new Error('Cannot acknowledge a close intent inside an uncommitted registry transaction')
this.savePending = true
return
}
if (this.writeBlocked) {
+ if (strict) throw new Error('The saved session registry is unavailable')
console.error('[registry] save skipped because the loaded registry requires operator repair')
return
}
@@ -2110,6 +2142,7 @@ class Registry {
this.persistedBaseline = new Map(serialized.map((row) => [rowId(row), rowFingerprint(row)]))
})
} catch (err) {
+ if (strict) throw err
console.error('[registry] save failed:', err)
}
}
diff --git a/cli/src/lib/resumeStoppedAgent.spec.ts b/cli/src/lib/resumeStoppedAgent.spec.ts
index 74d067bbf..61adab620 100644
--- a/cli/src/lib/resumeStoppedAgent.spec.ts
+++ b/cli/src/lib/resumeStoppedAgent.spec.ts
@@ -292,3 +292,39 @@ describe('resume refusal and readiness edge cases', () => {
expect(await waitForResumedAgent(saved, { current: () => false, session: () => undefined, process: async () => null, pane: async () => null, sleep: async () => {} })).toMatchObject({ error: 'AGENT_CHANGED' })
})
})
+
+it('reattaches when a startup hook rebuilds metadata for the same running process', async () => {
+ const deps = fixture()
+ const existing = { ...saved, registeredAt: 100, processIdentity: { pid: 42, startMarker: 'born', executable: 'codex' } }
+ const refreshed = { ...existing, title: 'Updated by hook', lastHookAt: 200 }
+ deps.live.mockReturnValue(existing)
+ deps.checkLive.mockImplementation(async () => { deps.live.mockReturnValue(refreshed); return { state: 'alive' } })
+ expect(await resumeStoppedAgent(deps)).toMatchObject({ ok: true, session: refreshed })
+ expect(deps.launch).not.toHaveBeenCalled()
+})
+
+it('honors a failure reported by a hook while the same live process was being checked', async () => {
+ const deps = fixture()
+ const row: RegisteredSession = { ...saved, resumeOnly: true }
+ deps.live.mockReturnValue(row)
+ deps.checkLive.mockImplementation(async () => {
+ deps.live.mockReturnValue({ ...row, launch: { state: 'failed', error: 'WRONG_CONVERSATION', detail: 'Different history', at: Date.now() } } as RegisteredSession)
+ return { state: 'alive' }
+ })
+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: false, error: 'WRONG_CONVERSATION' })
+ expect(deps.launch).not.toHaveBeenCalled()
+})
+it.each(['pid', 'conversation', 'route', 'birth'])('refuses an in-place %s replacement while checking a live session', async change => {
+ const deps = fixture()
+ const existing = { ...saved, registeredAt: 100, tmuxPane: '%1', runtimes: [{ backend: 'tmux' as const, paneId: '%1' }], processIdentity: { pid: 42, startMarker: 'born', executable: 'codex' } }
+ deps.live.mockReturnValue(existing)
+ deps.checkLive.mockImplementation(async () => {
+ if (change === 'pid') existing.processIdentity.pid++
+ if (change === 'conversation') existing.sessionId = 'different'
+ if (change === 'route') existing.runtimes[0].paneId = '%2'
+ if (change === 'birth') existing.registeredAt++
+ return { state: 'alive' }
+ })
+ expect(await resumeStoppedAgent(deps)).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(deps.launch).not.toHaveBeenCalled()
+})
diff --git a/cli/src/lib/resumeStoppedAgent.ts b/cli/src/lib/resumeStoppedAgent.ts
index e6e16d7b6..be4d1feb2 100644
--- a/cli/src/lib/resumeStoppedAgent.ts
+++ b/cli/src/lib/resumeStoppedAgent.ts
@@ -1,3 +1,4 @@
+import { terminalRouteKey } from './terminalRuntime.js'
import { isTerminalEngine } from '../engines/types.js'
import type { RegisteredSession, ProcessIdentity } from './registry.js'
import { resumesConversation } from './resumeCapability.js'
@@ -24,6 +25,12 @@ export const resumeChanged = { ok: false, error: 'AGENT_CHANGED', detail: 'The h
export const resumeUnconfirmed = { ok: false, error: 'RESUME_UNCONFIRMED', detail: 'The saved conversation has not been confirmed yet. Check the terminal, then select the harness again to check its status.' } as const
/** Enter means attach or exact resume. A route, shell or allocated pane alone is not success. */
+const liveIdentity = (row: RegisteredSession | undefined) => row ? JSON.stringify([
+ row.agentId, row.engine, row.sessionId, row.registeredAt, row.codexHome,
+ row.processIdentity?.pid, row.processIdentity?.startMarker, row.processIdentity?.executable,
+ row.runtimes?.map(terminalRouteKey).sort(), row.tmuxPane,
+]) : null
+
export async function resumeStoppedAgent(deps: ResumeStoppedDeps): Promise<RestartAgentReply> {
if (!deps.current()) return resumeChanged
const existing = deps.live()
@@ -35,23 +42,28 @@ export async function resumeStoppedAgent(deps: ResumeStoppedDeps): Promise<Resta
} else if (existing.resumeOnly && existing.launch?.state === 'starting') {
return deps.waitForReady(existing)
} else {
+ // Hooks replace registry objects while retaining the exact same process.
+ // Capture values before awaiting; object identity both rejects harmless
+ // hooks and misses an in-place PID/session replacement.
+ const identity = liveIdentity(existing)
const runtime = await deps.checkLive(existing)
- if (!deps.current() || deps.live() !== existing) return resumeChanged
+ const latest = deps.live()
+ if (!deps.current() || liveIdentity(latest) !== identity) return resumeChanged
if (runtime.state === 'unknown') return resumeUnconfirmed
if (runtime.state === 'alive') {
- if (existing.resumeOnly && existing.launch?.state === 'failed') {
+ if (latest!.resumeOnly && latest!.launch?.state === 'failed') {
// Never confirmed is not the same as disproved: the engine is running, so ask for
// confirmation again rather than repeating the old verdict.
- if (existing.launch.error === 'RESUME_UNCONFIRMED') return deps.waitForReady(existing)
+ if (latest!.launch.error === 'RESUME_UNCONFIRMED') return deps.waitForReady(latest!)
// Any other verdict is reported as ITSELF. Relabelling them all "not confirmed yet" told
// somebody whose resume had reopened the wrong conversation to go and check the terminal,
// and hid the one fact that would have explained what they were looking at.
- return { ok: false, error: existing.launch.error, detail: existing.launch.detail }
+ return { ok: false, error: latest!.launch.error, detail: latest!.launch.detail }
}
- return { ok: true, session: existing, resumed: true }
+ return { ok: true, session: latest!, resumed: true }
}
- saved = { ...existing }
- await deps.retain(existing)
+ saved = { ...latest! }
+ await deps.retain(latest!)
}
}
if (!deps.current()) return resumeChanged
diff --git a/cli/src/lib/sessionCheckpoint.spec.ts b/cli/src/lib/sessionCheckpoint.spec.ts
new file mode 100644
index 000000000..644b254ad
--- /dev/null
+++ b/cli/src/lib/sessionCheckpoint.spec.ts
@@ -0,0 +1,166 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { copyFile, link, mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { SessionCheckpointStore } from './sessionCheckpoint.js'
+import { registry, type RegisteredSession } from './registry.js'
+import { sqliteReadAll } from './sqliteRead.js'
+vi.mock('node:fs/promises', async importOriginal => {
+ const real = await importOriginal<typeof import('node:fs/promises')>()
+ return { ...real, copyFile: vi.fn(real.copyFile), rm: vi.fn(real.rm) }
+})
+vi.mock('./sqliteRead.js', () => ({ sqliteReadAll: vi.fn() }))
+let root: string
+let history: string
+let directory: string
+let row: RegisteredSession
+let store: SessionCheckpointStore
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'harness-close-checkpoint-'))
+ const home = join(root, 'profile')
+ await mkdir(join(home, 'sessions'), { recursive: true, mode: 0o700 })
+ history = join(home, 'sessions', 'conversation.jsonl')
+ await writeFile(history, '{"history":"retained conversation"}\n', { mode: 0o600 })
+ row = registry.openPendingAgent({ engine: 'codex', cwd: '/tmp', codexHome: home, runtimes: [{ backend: 'tmux', paneId: '%777' }] })!
+ Object.assign(row, { sessionId: 'conversation', transcriptPath: history })
+ directory = join(root, 'checkpoints')
+ store = new SessionCheckpointStore(directory)
+})
+afterEach(async () => { vi.restoreAllMocks(); for (const s of registry.list()) registry.removeAgent(s.agentId); await rm(root, { recursive: true, force: true }) })
+const manifest = async () => JSON.parse(await readFile(join(directory, (await readdir(directory)).find(f => /^[a-f0-9]{64}\.json$/.test(f))!), 'utf8'))
+
+it('preserves a newly typed draft even when native history has not changed', async () => {
+ await store.save(row, { screen: 'first draft' })
+ const first = await manifest()
+ await store.save(row, { screen: 'new unsent draft' })
+ expect(await manifest()).toEqual(first)
+ const screen = (await readdir(directory)).find(f => f.endsWith('.screen.json'))!
+ expect(JSON.parse(await readFile(join(directory, screen), 'utf8')).screen).toBe('new unsent draft')
+ expect((await stat(join(directory, screen))).mode & 0o777).toBe(0o600)
+ await store.save(row)
+ expect(JSON.parse(await readFile(join(directory, screen), 'utf8')).screen).toBe('new unsent draft')
+})
+
+it.each(['terminal', 'codex'] as const)('requires explicit consent and a durable screen for unbound %s', async engine => {
+ row.engine = engine; row.sessionId = ''; row.transcriptPath = null
+ await expect(store.save(row, { screen: 'unsent work' })).rejects.toThrow()
+ await expect(store.save(row, { explicitlyStopped: true })).rejects.toThrow()
+ await store.save(row, { explicitlyStopped: true, screen: 'unsent work' })
+ const before = await manifest()
+ await store.save(row, { explicitlyStopped: true })
+ expect(await manifest()).toEqual(before)
+ expect(JSON.parse(await readFile(join(directory, before.file), 'utf8')).screen).toBe('unsent work')
+})
+
+it('retains the full native transcript with private permissions, independently of the original', async () => {
+ await store.save(row)
+ const saved = await manifest()
+ const backup = join(directory, saved.file)
+ expect(saved).toMatchObject({ version: 1, agentId: row.agentId, sessionId: row.sessionId, source: history })
+ expect(await readFile(backup, 'utf8')).toBe(await readFile(history, 'utf8'))
+ expect((await stat(backup)).mode & 0o777).toBe(0o600)
+ expect((await stat(directory)).mode & 0o777).toBe(0o700)
+ await rm(history)
+ expect(await readFile(backup, 'utf8')).toContain('retained conversation')
+})
+it('reuses an unchanged checkpoint and replaces it only after a complete new save', async () => {
+ await store.save(row)
+ const first = await manifest()
+ await store.save(row)
+ expect(await manifest()).toEqual(first)
+ await writeFile(history, '{"history":"last flushed response"}\n')
+ await store.save(row)
+ const last = await manifest()
+ expect(last.file).not.toBe(first.file)
+ expect(await readFile(join(directory, last.file), 'utf8')).toContain('last flushed response')
+ expect((await readdir(directory)).filter(f => f.endsWith('.history'))).toEqual([last.file])
+})
+it.each(['missing', 'empty', 'outside profile', 'unbound'])('refuses %s history without destroying an earlier checkpoint', async mode => {
+ await store.save(row)
+ const saved = await manifest()
+ if (mode === 'missing') await rm(history)
+ if (mode === 'empty') await writeFile(history, '')
+ if (mode === 'outside profile') row.transcriptPath = join(root, 'unrelated')
+ if (mode === 'unbound') row.sessionId = ''
+ await expect(store.save(row)).rejects.toThrow()
+ expect(await manifest()).toEqual(saved)
+ expect(await readFile(join(directory, saved.file), 'utf8')).toContain('retained conversation')
+})
+it('does not hide a corrupt manifest by discarding the last known checkpoint', async () => {
+ await store.save(row)
+ const saved = await manifest()
+ const file = (await readdir(directory)).find(f => f.endsWith('.json'))!
+ await writeFile(join(directory, file), '{incomplete')
+ await expect(store.save(row)).rejects.toThrow('Could not back up')
+ expect(await readFile(join(directory, saved.file), 'utf8')).toContain('retained conversation')
+})
+it.each(['opencode', 'kilo', 'hermes', 'devin'] as const)('exports %s through read-only SQLite, keeping the shared database intact', async engine => {
+ row.engine = engine
+ row.transcriptPath = null
+ const sql = vi.mocked(sqliteReadAll).mockReset().mockResolvedValue({ ok: true, via: 'builtin', rows: [{ id: 'conversation', message: 'Stored in WAL' }] })
+ await store.save(row)
+ const saved = await manifest()
+ expect(await readFile(join(directory, saved.file), 'utf8')).toContain('Stored in WAL')
+ for (const [, query, params] of sql.mock.calls) {
+ expect(query).toMatch(/^SELECT \* FROM /)
+ expect(params).toEqual(['conversation'])
+ }
+})
+it('treats a locked or missing database as a save failure, never an empty successful backup', async () => {
+ row.engine = 'hermes'
+ vi.mocked(sqliteReadAll).mockResolvedValue({ ok: false, reason: 'transient' })
+ await expect(store.save(row)).rejects.toThrow('Could not read')
+ expect(await readdir(directory)).toEqual([])
+})
+
+it('rebuilds a missing backup and refuses a missing terminal snapshot', async () => {
+ await store.save(row)
+ await rm(join(directory, (await manifest()).file))
+ await store.save(row)
+ expect(await readFile(join(directory, (await manifest()).file), 'utf8')).toContain('retained conversation')
+ row.engine = 'terminal'; row.sessionId = ''
+ await store.save(row, { explicitlyStopped: true, screen: 'draft' })
+ for (const file of await readdir(directory)) if (file.endsWith('.history')) await rm(join(directory, file))
+ await expect(store.save(row, { explicitlyStopped: true })).rejects.toThrow('Could not save this terminal')
+})
+it('refuses an unset conversation path instead of inventing an empty checkpoint', async () => {
+ row.transcriptPath = null
+ await expect(store.save(row)).rejects.toThrow('conversation file is unavailable')
+})
+it('rejects a transcript changed during copy and retains the last committed backup', async () => {
+ await store.save(row)
+ const previous = await manifest()
+ await writeFile(history, 'new turn\n')
+ const real = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
+ vi.mocked(copyFile).mockImplementationOnce(async (source, target, flags) => {
+ await real.copyFile(source, target, flags)
+ await writeFile(history, 'a response arrived while copying\n')
+ })
+ await expect(store.save(row)).rejects.toThrow('changed while saving')
+ expect(await manifest()).toEqual(previous)
+ expect(await readFile(join(directory, previous.file), 'utf8')).toContain('retained conversation')
+})
+it('rejects a checkpoint that gained an unexpected hard link before commit', async () => {
+ const real = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
+ vi.mocked(copyFile).mockImplementationOnce(async (source, target, flags) => {
+ await real.copyFile(source, target, flags)
+ await link(target, join(root, 'unexpected-link'))
+ })
+ await expect(store.save(row)).rejects.toThrow('Could not back up')
+ expect((await readdir(directory)).some(file => file.endsWith('.json'))).toBe(false)
+})
+it('keeps a successful new checkpoint when cleanup of the older copy fails', async () => {
+ await store.save(row)
+ const before = await manifest()
+ await writeFile(history, 'new conversation state\n')
+ vi.mocked(rm).mockRejectedValueOnce(new Error('file busy'))
+ await store.save(row)
+ const after = await manifest()
+ expect(after.file).not.toBe(before.file)
+ expect(await readFile(join(directory, after.file), 'utf8')).toContain('new conversation state')
+})
+it('reports the save failure even if cleanup also fails', async () => {
+ row.transcriptPath = null
+ vi.mocked(rm).mockRejectedValueOnce(new Error('temporary busy')).mockRejectedValueOnce(new Error('destination busy'))
+ await expect(store.save(row)).rejects.toThrow('conversation file is unavailable')
+})
diff --git a/cli/src/lib/sessionCheckpoint.sqlite.spec.ts b/cli/src/lib/sessionCheckpoint.sqlite.spec.ts
new file mode 100644
index 000000000..a561b5fcb
--- /dev/null
+++ b/cli/src/lib/sessionCheckpoint.sqlite.spec.ts
@@ -0,0 +1,48 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import type { RegisteredSession } from './registry.js'
+
+let root: string
+const databases: Array<{ close(): void }> = []
+beforeEach(() => {
+ vi.resetModules()
+ root = mkdtempSync(join(tmpdir(), 'harness-checkpoint-wal-'))
+ for (const key of ['OPENCODE_DATA_DIR', 'KILO_DATA_DIR', 'HERMES_HOME', 'DEVIN_HOME']) vi.stubEnv(key, root)
+})
+afterEach(async () => {
+ const { closeSqliteHandles } = await import('./sqliteRead.js')
+ closeSqliteHandles()
+ for (const database of databases.splice(0)) database.close()
+ vi.unstubAllEnvs()
+ rmSync(root, { recursive: true, force: true })
+})
+
+it.each(['opencode', 'kilo', 'hermes', 'devin'] as const)('backs up only the selected %s conversation while its real database has a live WAL', async engine => {
+ const { DatabaseSync } = process.getBuiltinModule('node:sqlite') as any
+ const path = join(root, engine === 'opencode' ? 'opencode.db' : engine === 'kilo' ? 'kilo.db' : engine === 'hermes' ? 'state.db' : 'sessions.db')
+ const database = new DatabaseSync(path)
+ databases.push(database)
+ database.exec('PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0;')
+ if (engine === 'opencode' || engine === 'kilo') {
+ database.exec(`CREATE TABLE session (id TEXT PRIMARY KEY); CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, body TEXT);
+ CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, body TEXT);
+ INSERT INTO session VALUES ('wanted'), ('other'); INSERT INTO message VALUES ('m1', 'wanted', 'history in WAL'), ('m2', 'other', 'unrelated private text');
+ INSERT INTO part VALUES ('p1', 'm1', 'wanted attachment'), ('p2', 'm2', 'unrelated private text');`)
+ } else {
+ const table = engine === 'hermes' ? 'messages' : 'message_nodes'
+ database.exec(`CREATE TABLE sessions (id TEXT PRIMARY KEY); CREATE TABLE ${table} (id TEXT PRIMARY KEY, session_id TEXT, body TEXT);
+ INSERT INTO sessions VALUES ('wanted'), ('other'); INSERT INTO ${table} VALUES ('m1', 'wanted', 'history in WAL'), ('m2', 'other', 'unrelated private text');`)
+ }
+ expect(readdirSync(root)).toContain(`${path.split('/').at(-1)}-wal`)
+ const { SessionCheckpointStore } = await import('./sessionCheckpoint.js')
+ const directory = join(root, 'backups')
+ mkdirSync(directory, { mode: 0o700 })
+ await new SessionCheckpointStore(directory).save({ agentId: 'fixture', sessionId: 'wanted', engine, hermesHome: root } as RegisteredSession)
+ const manifest = JSON.parse(readFileSync(join(directory, readdirSync(directory).find(f => f.endsWith('.json'))!), 'utf8'))
+ const backup = readFileSync(join(directory, manifest.file), 'utf8')
+ expect(backup).toContain('history in WAL')
+ expect(backup).not.toContain('unrelated private text')
+ expect(database.prepare(`SELECT count(*) AS n FROM ${engine === 'opencode' || engine === 'kilo' ? 'session' : 'sessions'}`).get().n).toBe(2)
+})
diff --git a/cli/src/lib/sessionCheckpoint.ts b/cli/src/lib/sessionCheckpoint.ts
new file mode 100644
index 000000000..cd3456267
--- /dev/null
+++ b/cli/src/lib/sessionCheckpoint.ts
@@ -0,0 +1,157 @@
+/** Disk checkpoints made only when closing a session, never by a resource sampler. */
+import { constants } from 'node:fs'
+import { chmod, copyFile, lstat, open, rename, rm, stat } from 'node:fs/promises'
+import { createHash, randomUUID } from 'node:crypto'
+import { dirname, join } from 'node:path'
+import { env } from '../config/env.js'
+import { atomicWriteJson, engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'
+import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
+import { sqliteReadAll } from './sqliteRead.js'
+import { hermesDbPath } from '../engines/hermes/home.js'
+
+export class SessionCheckpointError extends Error {
+ readonly code = 'HISTORY_NOT_SAVED'
+}
+
+/** Native SQLite files can have live WAL writers. Export this conversation's rows through a
+ * read-only connection; never copy an incomplete .db or replace an engine's shared store. */
+async function databaseHistory(s: RegisteredSession): Promise<Record<string, unknown>> {
+ let database: string
+ let selections: [string, string][]
+ switch (s.engine) {
+ case 'opencode': case 'kilo':
+ database = s.engine === 'opencode' ? join(env.OPENCODE_DATA_DIR, 'opencode.db') : join(env.KILO_DATA_DIR, 'kilo.db')
+ selections = [['session', 'id = ?'], ['message', 'session_id = ?'],
+ ['part', 'message_id IN (SELECT id FROM message WHERE session_id = ?)']]
+ break
+ case 'hermes':
+ database = hermesDbPath(s.hermesHome ?? env.HERMES_HOME)
+ selections = [['sessions', 'id = ?'], ['messages', 'session_id = ?']]
+ break
+ case 'devin':
+ database = join(env.DEVIN_HOME, 'sessions.db')
+ selections = [['sessions', 'id = ?'], ['message_nodes', 'session_id = ?']]
+ break
+ default: throw new SessionCheckpointError('This engine has no supported history checkpoint yet. The session is still open.')
+ }
+ const tables: Record<string, unknown[]> = {}
+ for (const [table, where] of selections) {
+ const result = await sqliteReadAll(database, `SELECT * FROM ${table} WHERE ${where};`, [s.sessionId])
+ if (!result.ok || (table === selections[0][0] && result.rows.length !== 1)) {
+ throw new SessionCheckpointError('Could not read the saved conversation. The session has not been closed.')
+ }
+ tables[table] = result.rows
+ }
+ return { database, tables }
+}
+
+type Checkpoint = {
+ version: 1
+ agentId: string
+ sessionId: string
+ engine: string
+ codexHome: string | null
+ savedAt: number
+ source: string | null
+ sourceSize?: number
+ sourceMtime?: number
+ sourceInode?: number
+ file: string
+ bytes: number
+}
+
+export class SessionCheckpointStore {
+ constructor(private readonly directory = join(env.ADAPTER_DATA_DIR, 'session-checkpoints')) {}
+
+ private key(s: RegisteredSession): string {
+ return createHash('sha256').update(JSON.stringify([s.agentId, s.engine, s.codexHome ?? null, s.sessionId])).digest('hex')
+ }
+
+ async save(s: RegisteredSession, options: { explicitlyStopped?: boolean; screen?: string | null } = {}): Promise<void> {
+ if (!s.sessionId && !options.explicitlyStopped) throw new SessionCheckpointError('A saved conversation is not available yet. Keep this session open and try again after its first response.')
+ secureStateDirectory(dirname(this.directory))
+ secureStateDirectory(this.directory)
+ const key = this.key(s)
+ const manifest = join(this.directory, `${key}.json`)
+ const file = `${key}-${randomUUID()}.history`
+ const temporary = join(this.directory, `${file}.tmp`)
+ const destination = join(this.directory, file)
+ let committed = false
+ let previous: Checkpoint | null = null
+ try {
+ try { previous = JSON.parse(readPrivateStateFile(manifest, 16384)) as Checkpoint } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e
+ }
+ if (options.screen != null && s.sessionId) {
+ // Save even when the native transcript is unchanged: a newly typed draft
+ // belongs to the terminal, not to that transcript. Never submit it.
+ atomicWriteJson(join(this.directory, `${key}.screen.json`), { version: 1, agentId: s.agentId,
+ sessionId: s.sessionId, savedAt: Date.now(), screen: options.screen })
+ }
+ const checkpoint: Checkpoint = { version: 1, agentId: s.agentId, sessionId: s.sessionId,
+ engine: s.engine, codexHome: s.codexHome ?? null, savedAt: Date.now(), source: null, file, bytes: 0 }
+ if (!s.sessionId || s.engine === 'terminal') {
+ // A shell/fresh composer has no native conversation. Only an explicit Stop
+ // may retire it, with its terminal contents retained separately on disk.
+ if (options.screen == null) {
+ if (previous?.version === 1 && previous.sessionId === s.sessionId && previousFileSafe(previous.file)
+ && (await lstat(join(this.directory, previous.file)).catch(() => null))?.isFile()) return
+ throw new SessionCheckpointError('Could not save this terminal before closing it. Keep it open and try again.')
+ }
+ atomicWriteJson(temporary, { version: 1, agentId: s.agentId, engine: s.engine, cwd: s.cwd,
+ savedAt: checkpoint.savedAt, screen: options.screen })
+ } else if (engineKeepsTranscriptFile(s.engine)) {
+ const source = s.transcriptPath
+ if (!source || !validTranscriptPath(s.engine, source, s.codexHome ?? undefined)) {
+ throw new SessionCheckpointError('The conversation file is unavailable. The session has not been closed.')
+ }
+ const before = await stat(source)
+ if (before.size === 0) throw new SessionCheckpointError('This conversation is still being saved. Keep it open and try again shortly.')
+ const previousFile = previous?.file && previousFileSafe(previous.file)
+ ? await lstat(join(this.directory, previous.file)).catch(() => null) : null
+ // A second checkpoint after a quiet exit need not copy the same history twice.
+ if (previous?.version === 1 && previous.source === source && previous.sourceInode === before.ino
+ && previous.sourceSize === before.size && previous.sourceMtime === before.mtimeMs
+ && previousFile?.isFile() && previousFile.nlink === 1 && (previousFile.mode & 0o777) === 0o600
+ && previousFile.size === before.size) return
+ // APFS/reflink when available, ordinary file copy otherwise. No transcript-sized JS buffer.
+ await copyFile(source, temporary, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE)
+ await chmod(temporary, 0o600)
+ const after = await stat(source)
+ if (before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) {
+ throw new SessionCheckpointError('The conversation changed while saving. Please try closing it again.')
+ }
+ Object.assign(checkpoint, { source, sourceSize: after.size, sourceMtime: after.mtimeMs, sourceInode: after.ino })
+ } else {
+ const history = await databaseHistory(s)
+ const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try { await handle.writeFile(JSON.stringify({ version: 1, sessionId: s.sessionId, engine: s.engine, ...history })) }
+ finally { await handle.close() }
+ }
+ const handle = await open(temporary, constants.O_RDWR | constants.O_NOFOLLOW)
+ try {
+ const copied = await handle.stat()
+ if (!copied.isFile() || copied.nlink !== 1) throw new Error('unsafe checkpoint')
+ checkpoint.bytes = copied.size
+ await handle.sync()
+ } finally { await handle.close() }
+ await rename(temporary, destination)
+ // Publish only after data is durable. A failed save keeps the preceding checkpoint intact.
+ atomicWriteJson(manifest, checkpoint)
+ committed = true
+ if (previous?.file && previous.file !== file && previousFileSafe(previous.file)) {
+ await rm(join(this.directory, previous.file), { force: true }).catch(() => {})
+ }
+ } catch (error) {
+ if (error instanceof SessionCheckpointError) throw error
+ throw new SessionCheckpointError('Could not back up this conversation to disk. Check free space and try again; its existing history is kept.')
+ } finally {
+ await rm(temporary, { force: true }).catch(() => {})
+ if (!committed) await rm(destination, { force: true }).catch(() => {})
+ }
+ }
+}
+
+const previousFileSafe = (file: string): boolean => /^[a-f0-9]{64}-[a-f0-9-]{36}\.history$/.test(file)
+
+export const sessionCheckpoints = new SessionCheckpointStore()
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
index ce1e8e56e..8f64f33f9 100644
--- a/cli/src/lib/stopAgentService.spec.ts
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -1,10 +1,12 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { stopSharedCodexSession } from './codexSessionLifecycle.js'
import { captureResumeIdentity } from './captureResumeIdentity.js'
import { createStopAgentService, type StopAgentServiceDeps } from './stopAgentService.js'
import { registry, type RegisteredSession } from './registry.js'
import { stoppedAgents } from './stoppedAgents.js'
import { AgentRestartCoordinator } from './restartAgent.js'
import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.js'
+vi.mock('./codexSessionLifecycle.js', () => ({ stopSharedCodexSession: vi.fn(async () => {}) }))
vi.mock('./captureResumeIdentity.js', () => ({ captureResumeIdentity: vi.fn(async session => session) }))
vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))
let row: RegisteredSession
@@ -40,6 +42,23 @@ it('storage failure leaves the live process and registry untouched', async () =>
await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('disk full')
expect(registry.byAgent(row.agentId)).toBe(row); expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled(); expect(deps.markDeleted).not.toHaveBeenCalled()
})
+it.each(['before', 'after'] as const)('honors cancellation at the %s checkpoint before retiring the terminal', async phase => {
+ let current = true
+ await expect(createStopAgentService(deps)(row.agentId, {
+ current: () => current,
+ checkpoint: async (_, at) => { if (at === phase) current = false },
+ })).rejects.toThrow('changed')
+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+ if (phase === 'before') expect(terminateDeletedAgent).not.toHaveBeenCalled()
+})
+it('backs up final flushed history after graceful exit and before closing the pane', async () => {
+ const order: string[] = []
+ vi.mocked(terminateDeletedAgent).mockImplementation(async () => { order.push('exit'); return 'terminated' })
+ vi.mocked(deps.tmuxBackend!.kill).mockImplementation(async () => { order.push('pane'); return { state: 'succeeded', dispatch: 'executed' } })
+ await createStopAgentService(deps)(row.agentId, { checkpoint: async (_, phase) => { order.push(phase) } })
+ expect(order).toEqual(['before', 'exit', 'after', 'pane'])
+})
it.each(['terminal', 'without tmux', 'failed process', 'failed tmux'] as const)('retains work when stopping %s', async mode => {
stoppedAgents.beginResume(row.agentId)
if (mode === 'terminal') Object.assign(row, { engine: 'terminal', sessionId: '', processIdentity: null })
@@ -67,11 +86,12 @@ it('does not publish a stopped row until the exact process and terminal have bot
await vi.waitFor(() => expect(finishProcess).toBeTypeOf('function'))
expect(registry.byAgent(row.agentId)).toBe(row)
expect(deps.forgetSession).not.toHaveBeenCalled()
- finishPane()
- await Promise.resolve()
+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
+ finishProcess()
+ await vi.waitFor(() => expect(finishPane).toBeTypeOf('function'))
expect(deps.forgetSession).not.toHaveBeenCalled()
expect(stop(row.agentId)).toBe(stopping)
- finishProcess()
+ finishPane()
await stopping
expect(deps.forgetSession).toHaveBeenCalledOnce()
expect(deps.agentReconciler.holdRoute).toHaveBeenCalledOnce()
@@ -108,6 +128,7 @@ it.each(['removed', 'replaced', 'conversation', 'route'] as const)('does not rem
return 'terminated'
})
await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('changed while pausing')
+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
expect(deps.forgetSession).not.toHaveBeenCalled()
})
it.each(['capture', 'termination'] as const)('accepts a hook rebuilding the same process during %s', async stage => {
@@ -166,3 +187,32 @@ it('keeps the newer hook binding that arrives during capture', async () => {
await createStopAgentService(deps)(row.agentId)
expect(stoppedAgents.get(row.agentId)?.sessionId).toBe('latest')
})
+
+it('checks cancellation at the shared-server boundary and never signals after a failure there', async () => {
+ let current = true
+ vi.mocked(stopSharedCodexSession).mockImplementationOnce(async (_row, guard) => {
+ expect(guard()).toBe(true); current = false; expect(guard()).toBe(false)
+ throw new Error('shared server could not stop')
+ })
+ await expect(createStopAgentService(deps)(row.agentId, { current: () => current })).rejects.toThrow('shared server')
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
+ expect(deps.clearDeleted).toHaveBeenCalledWith(row.agentId)
+})
+it('does not signal a process replaced at the actual kill boundary', async () => {
+ vi.mocked(terminateDeletedAgent).mockImplementationOnce(async (_row, actions) => {
+ row.processIdentity!.startMarker = 'replacement'
+ actions.kill(77, 'SIGTERM')
+ return 'gone'
+ })
+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('Could not confirm')
+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
+})
+it('does not forget a new agent published while its old pane was being retired', async () => {
+ vi.mocked(deps.tmuxBackend!.kill).mockImplementationOnce(async () => {
+ row.processIdentity!.startMarker = 'replacement'
+ return { state: 'succeeded', dispatch: 'executed' }
+ })
+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('changed while pausing')
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+})
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index 64dd444da..fb3e4e34b 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -1,4 +1,5 @@
/** Stop retains the logical session before retiring its process and terminal. */
+import { stopSharedCodexSession } from './codexSessionLifecycle.js'
import { captureResumeIdentity } from './captureResumeIdentity.js'
import { isTerminalEngine } from '../engines/types.js'
import type { registry as liveRegistry, RegisteredSession } from './registry.js'
@@ -29,6 +30,15 @@ export class AgentStopError extends Error {
readonly code = 'STOP_UNCONFIRMED'
}
+export interface StopAgentOptions {
+ /** Synchronous cancellation/identity fence at the actual signal boundary. */
+ current?(): boolean
+ /** A Close must earn its permission again after saving, immediately before signalling. */
+ beforeStop?(session: RegisteredSession): Promise<void>
+ /** Retain native history before exit, then include anything the engine flushed while exiting. */
+ checkpoint?(session: RegisteredSession, phase: 'before' | 'after'): Promise<void>
+}
+
// Hooks rebuild registry objects. Compare stable values, never JavaScript object
// identity or property ordering, while retaining the exact PID-reuse guard.
const runtimeIdentity = (entry: RegisteredSession | undefined) => entry ? JSON.stringify([
@@ -40,7 +50,7 @@ const runtimeIdentity = (entry: RegisteredSession | undefined) => entry ? JSON.s
export function createStopAgentService(deps: StopAgentServiceDeps) {
const { registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,
forgetSession, markDeleted, clearDeleted } = deps
- return (target: string) => {
+ return (target: string, options: StopAgentOptions = {}) => {
const sessionId = registry.resolve(target)?.agentId ?? target
const existing = stopJobs.get(sessionId)
if (existing) return existing
@@ -57,7 +67,7 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
const captured = await captureResumeIdentity({ ...live })
// Discovery or a hook may have updated this row while reading the native store.
// A replacement process must never be stopped using an older snapshot.
- if (!sameTarget()) {
+ if (!sameTarget() || options.current?.() === false) {
throw new AgentStopError('Harness changed while saving its conversation. Try pausing again.')
}
const current = registry.resolve(sessionId)!
@@ -65,31 +75,47 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
transcriptPath: captured.transcriptPath, boundAt: captured.boundAt, source: captured.source }
// Saving precedes every mutation. A storage failure leaves the live agent alone.
stoppedAgents.save(s)
+ await options.checkpoint?.(s, 'before')
+ await options.beforeStop?.(s)
+ if (!sameTarget() || options.current?.() === false) {
+ throw new AgentStopError('Harness changed while saving its conversation. Try pausing again.')
+ }
const routes = s.runtimes.map(terminalRouteKey)
for (const route of routes) agentReconciler.holdRoute(route)
try {
markDeleted(sessionId)
if (s.sessionId) markDeleted(s.sessionId)
- const paneStop = tmuxBackend
- ? Promise.all(s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
- .map(runtime => tmuxBackend!.kill(runtime)))
- : Promise.resolve([])
- const processStop = isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
+ await stopSharedCodexSession(s, () => sameTarget() && options.current?.() !== false)
+ // Keep the terminal alive while the engine handles SIGTERM and flushes
+ // its native store. Killing tmux in parallel can deliver SIGHUP first.
+ const termination = await (isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
: terminateDeletedAgent(s, {
checkRuntime: checkPidRuntime,
- kill: (pid, signal) => process.kill(pid, signal),
+ kill: (pid, signal) => {
+ if (!sameTarget() || options.current?.() === false) throw new AgentStopError('The close request was cancelled or changed.')
+ process.kill(pid, signal)
+ },
sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
log: message => console.log(message),
- }, 0)
- // Both checks must settle before releasing the route or permitting a retry.
- const [panes, termination] = await Promise.allSettled([paneStop, processStop])
- if (panes.status !== 'fulfilled' || termination.status !== 'fulfilled'
- || termination.value === 'failed'
- || panes.value.some(result => result.state !== 'succeeded')
- || (isTerminalEngine(s.engine) && (!tmuxBackend || !panes.value.length))) {
+ }, 0)).catch(() => 'failed' as const)
+ if (termination === 'failed' || termination === 'not-ours') {
+ throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try pausing again.')
+ }
+ // Never close a replacement's pane, even when our old process exited.
+ if (!sameTarget() || options.current?.() === false) {
+ throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')
+ }
+ await options.checkpoint?.(s, 'after')
+ if (!sameTarget() || options.current?.() === false) {
+ throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')
+ }
+ const panes = await Promise.allSettled(tmuxBackend
+ ? s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
+ .map(runtime => tmuxBackend.kill(runtime)) : [])
+ if (panes.some(result => result.status !== 'fulfilled' || result.value.state !== 'succeeded')
+ || (isTerminalEngine(s.engine) && !panes.length)) {
throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try pausing again.')
}
- // Never remove a replacement discovered while the process checks were awaiting.
if (!sameTarget()) {
throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')
}
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index b5b9c27cc..a1b13972a 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -68,6 +68,8 @@ export class StoppedAgentStore {
defaultName: projectDisplayName(session),
touchedAt: Date.now(),
}
+ // A later Resume is an explicit new visit, never an instruction to close it again.
+ delete snapshot.closePlan
// A snapshot without a tmux pane omits the legacy alias just like registry persistence.
if (!snapshot.tmuxPane) delete (snapshot as Partial<RegisteredSession>).tmuxPane
atomicWriteJson(join(this.directory, `${session.agentId}.json`), { version: 1, session: snapshot })
diff --git a/cli/src/lib/terminalAgentDiscovery.spec.ts b/cli/src/lib/terminalAgentDiscovery.spec.ts
index 2c3362a5a..60a543fb3 100644
--- a/cli/src/lib/terminalAgentDiscovery.spec.ts
+++ b/cli/src/lib/terminalAgentDiscovery.spec.ts
@@ -37,4 +37,52 @@ describe('process discovery', () => {
)
expect(result.agents[0].primaryRuntimeKey).toBe(terminalRouteKey(tmux.runtime))
})
+
+ it('keeps independent, nested, ambiguous and daemon-owned panes separate in one scan', () => {
+ const root = (pid: number): TerminalRootObservation => ({
+ runtime: { backend: 'tmux', paneId: `%${pid}` }, rootPid: pid, cwd: `/work/${pid}`,
+ })
+ const result = discoverTerminalAgentsFromSnapshot(
+ [root(10), root(20), root(21), root(30), root(40)],
+ [
+ shell(10, 1), claude(11, 10),
+ shell(20, 1), shell(21, 20), claude(22, 21),
+ shell(30, 1), shell(999, 30), claude(1000, 999),
+ shell(40, 1), claude(41, 40), claude(42, 40),
+ ],
+ 999,
+ ['tmux'],
+ )
+
+ expect(result.agents.map(agent => ({
+ pid: agent.processIdentity.pid,
+ cwd: agent.cwd,
+ runtimes: agent.runtimes,
+ }))).toEqual([
+ { pid: 11, cwd: '/work/10', runtimes: [root(10).runtime] },
+ { pid: 22, cwd: '/work/21', runtimes: [root(21).runtime, root(20).runtime] },
+ ])
+ expect(result.ambiguousPlacements).toEqual(new Set([terminalRouteKey(root(40).runtime)]))
+ })
+
+ it('sees exits and reused PIDs on the next snapshot', () => {
+ const roots = [tmux, nested]
+ const before = discoverTerminalAgentsFromSnapshot(
+ roots, [shell(10, 1), claude(11, 10), shell(20, 1), claude(21, 20)], 999, ['tmux'],
+ )
+ const replacement: ProcessRow = {
+ pid: 11, parentPid: 20, executable: 'codex', args: 'codex', startMarker: 'Sat Aug 15 11:00:00 2026',
+ }
+ const after = discoverTerminalAgentsFromSnapshot(
+ roots, [shell(10, 1), shell(20, 1), replacement], 999, ['tmux'],
+ )
+
+ expect(before.agents.map(agent => agent.processIdentity.pid)).toEqual([11, 21])
+ expect(after.agents).toHaveLength(1)
+ expect(after.agents[0]).toMatchObject({
+ engine: 'codex',
+ processIdentity: { pid: 11, startMarker: replacement.startMarker },
+ runtimes: [nested.runtime],
+ })
+ })
})
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
index 018886197..0fa099d75 100644
--- a/cli/src/lib/terminalAgentDiscovery.ts
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -104,8 +104,7 @@ function childrenByParent(rows: readonly ProcessRow[]): Map<number, ProcessRow[]
return children
}
-function daemonDescendants(rows: readonly ProcessRow[], daemonPid: number): Set<number> {
- const children = childrenByParent(rows)
+function daemonDescendants(children: ReadonlyMap<number, readonly ProcessRow[]>, daemonPid: number): Set<number> {
const excluded = new Set<number>()
const queue = [daemonPid]
while (queue.length) {
@@ -119,13 +118,12 @@ function daemonDescendants(rows: readonly ProcessRow[], daemonPid: number): Set<
function rootOwner(
root: TerminalRootObservation,
- rows: readonly ProcessRow[],
+ byPid: ReadonlyMap<number, ProcessRow>,
+ children: ReadonlyMap<number, readonly ProcessRow[]>,
excluded: ReadonlySet<number>,
ownership: AgentCommandOwnershipSnapshot,
hintedEngine?: AgentEngine,
): RootOwner {
- const byPid = new Map(rows.map((row) => [row.pid, row]))
- const children = childrenByParent(rows)
const queue: Array<{ pid: number; depth: number }> = [{ pid: root.rootPid, depth: 0 }]
const matches: Array<{ row: ProcessRow; engine: AgentEngine; depth: number; score: number }> = []
let unresolvedAliasDepth = Number.POSITIVE_INFINITY
@@ -187,7 +185,12 @@ export function discoverTerminalAgentsFromSnapshot(
hints: ReadonlyMap<string, AgentEngine> = new Map(),
ownership = agentCommandOwnershipSnapshot(),
): { agents: DiscoveredTerminalAgent[]; ambiguousPlacements: Set<string> } {
- const excluded = daemonDescendants(rows, daemonPid)
+ // Every pane belongs to this same snapshot. Build the process indexes once per scan, rather
+ // than copying the whole machine's process table for every persistent pane. Keep them local:
+ // the next scan must see exits, execs and PID reuse without retaining stale process identities.
+ const byPid = new Map(rows.map((row) => [row.pid, row]))
+ const children = childrenByParent(rows)
+ const excluded = daemonDescendants(children, daemonPid)
const grouped = new Map<string, {
agent: Omit<DiscoveredTerminalAgent, 'runtimes' | 'primaryRuntimeKey'>
observations: Array<{ runtime: TerminalRuntimeRef; depth: number; cwd: string }>
@@ -195,7 +198,7 @@ export function discoverTerminalAgentsFromSnapshot(
const ambiguousPlacements = new Set<string>()
for (const root of roots) {
- const owner = rootOwner(root, rows, excluded, ownership, hints.get(terminalRouteKey(root.runtime)))
+ const owner = rootOwner(root, byPid, children, excluded, ownership, hints.get(terminalRouteKey(root.runtime)))
if (owner.ambiguous) {
ambiguousPlacements.add(terminalPlacementKey(root.runtime))
continue
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index 4ccd20eca..267c5cd32 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -113,6 +113,18 @@ describe('TerminalStreamManager', () => {
vi.useRealTimers()
})
+ it('reports other windows until their views actually close, including watchers', async () => {
+ const payload = { agentId: 'agent-1', viewId: 'v', requestId: 'r', protocolVersion: 3, cols: 120, rows: 40 }
+ await manager.handleFrame('web-1', 'terminal_open', payload)
+ expect(manager.hasOtherViews('agent-1', 'web-1')).toBe(false)
+ expect(manager.hasOtherViews('agent-1', 'web-2')).toBe(true)
+ await manager.handleFrame('web-2', 'terminal_open', { ...payload, requestId: 'r2' })
+ expect(manager.hasOtherViews('agent-1', 'web-1')).toBe(true)
+ expect(manager.hasOtherViews('unrelated', 'web-1')).toBe(false)
+ await manager.closeConnection('web-2')
+ expect(manager.hasOtherViews('agent-1', 'web-1')).toBe(false)
+ })
+
it('publishes the complete engine catalog without a client whitelist', async () => {
await manager.handleFrame('web-1', 'terminal_capabilities', { requestId: 'r1' })
const result = sent.at(-1)!
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 1775db305..260bb38e7 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -227,6 +227,12 @@ export class TerminalStreamManager {
this.expiryTimer.unref?.()
}
+ /** Closing a quiet pane must not silently stop a session open in another window/device. */
+ hasOtherViews(agentId: string, connId: string): boolean {
+ return [...this.streams.values()].some(stream =>
+ stream.agentId === agentId && stream.connId !== connId && !stream.closing)
+ }
+
private async withLeaseLock<T>(key: string, operation: () => Promise<T>): Promise<T> {
const previous = this.leaseLocks.get(key) ?? Promise.resolve()
let release!: () => void
diff --git a/cli/src/lib/tmuxAgentDiscovery.real.spec.ts b/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
index 7a493a12d..54e646eba 100644
--- a/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
@@ -15,6 +15,7 @@ import {
} from './engineBin.js'
import { TmuxBackend } from './tmuxBackend.js'
import { probeTmuxAgents } from './tmuxAgentDiscovery.js'
+import { probeTerminalAgents } from './terminalAgentDiscovery.js'
import { HARNESS_SESSION_PREFIX } from './harnessSessionLabel.js'
// Discovery only sees sessions named like agent_create's; a session outside the prefix is
@@ -113,6 +114,19 @@ realDescribe.sequential('real installed CLI process discovery', () => {
const capture = await tmux(['capture-pane', '-p', '-t', pane]).catch(() => '')
expect(discovered, `${bin} was not discovered in ${pane}\n${capture}`).not.toBeNull()
+ // The daemon uses the backend-neutral scan. Exercise it against the same real process,
+ // not only the older tmux-specific reader, before checking that stop preserves the pane.
+ const current = await probeTerminalAgents([new TmuxBackend()], ['tmux'])
+ expect(current.processTableAvailable).toBe(true)
+ const matches = current.agents.filter(agent => agent.runtimes.some(runtime => runtime.paneId === pane))
+ expect(matches).toHaveLength(1)
+ // Node engines may change their process title between these snapshots.
+ // The PID and birth stamp prove this is still the same launched process.
+ expect(matches[0]).toMatchObject({ engine, processIdentity: {
+ pid: discovered!.processIdentity.pid,
+ startMarker: discovered!.processIdentity.startMarker,
+ } })
+
const pid = discovered!.processIdentity.pid
process.kill(pid, 'SIGTERM')
const gone = await eventually(async () => {
diff --git a/cli/src/memory/retention.spec.ts b/cli/src/memory/retention.spec.ts
index be3e7b9dc..f027a40d4 100644
--- a/cli/src/memory/retention.spec.ts
+++ b/cli/src/memory/retention.spec.ts
@@ -99,7 +99,7 @@ it('applies backpressure without acknowledging or saving a new episode when the
const fullCursor = store.learning.cursor('stream')
expect(() => capture(event('still_blocked'))).toThrow('memory_backlog_full')
expect(store.learning.cursor('stream')).toBe(fullCursor)
-})
+}, 30_000) // Hundreds of durable writes; this is a backpressure check, not a five-second benchmark.
it('expires unreviewed input as an explicit gap, rejects late results and eventually prunes job metadata', () => {
const source = event('expired')
diff --git a/cli/src/memory/store.spec.ts b/cli/src/memory/store.spec.ts
index 4be1432fd..a42360759 100644
--- a/cli/src/memory/store.spec.ts
+++ b/cli/src/memory/store.spec.ts
@@ -138,7 +138,7 @@ describe('session privacy', () => {
store.setSessionIncluded('claude', 'session_a', false)
expect(store.list(access, 1).map(record => record.id)).toEqual([publicRecord.id])
expect(store.recall({ query: 'bug', conditions: { taskType: 'debugging' } }, access).items.map(record => record.id)).toEqual([publicRecord.id])
- })
+ }, 30_000) // Keep all 125 durable fixtures even on a busy shared CI disk.
it('does not consult a private statement when admitting a new conflicting public statement', () => {
const hidden = learn()
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 48ba58208..2bbe06366 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -251,6 +251,19 @@ Window-only preview collections are test/render fixtures, not a user setting.
Per-machine runtime state is `MachineState` (connection status, transport mode, agents, `nodeOnline`
from `node_status` pushes — distinct from our own socket status, pending offline agent, turn activity).
+Explicit pane/tab Close uses `requestClosePane` / `requestCloseSwarm`. Closing the last local view
+of an owned idle session saves its native conversation and terminal snapshot before releasing its
+process. Working, unknown, draft, or other-device sessions require a reviewed decision; Cancel is
+the default. Stop after finishing persists a daemon-owned plan, and reopening cancels it. Layout
+cleanup, moving panes, switching tabs, and sign-out retain their view-only behavior. A failed save
+or unconfirmed close keeps the pane. Older daemons retain their existing behavior until updated.
+
+`HarnessMonitor` drives the bottom-left resource summary and existing session manager. It samples
+connected owned sessions every 15 seconds, every 3 seconds while expanded, and never while the app
+is hidden. RAM is process-tree RSS; CPU is interval use, with 100% representing one core. Unknown
+readings remain unknown. Shared Codex servers are listed separately and included once in totals;
+token counts reuse existing agent data. The monitor never resumes sessions or scans transcripts.
+
### Command dock
For app UI outside terminal panes, follow the [desktop design system](design/desktop-design-system.md).
diff --git a/desktop/design/review/2026-10-01-harness-monitor.png b/desktop/design/review/2026-10-01-harness-monitor.png
new file mode 100644
index 000000000..0d2bef1e7
Binary files /dev/null and b/desktop/design/review/2026-10-01-harness-monitor.png differ
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index 090eb6287..1558bd34e 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -14,11 +14,32 @@ api ? web ⠹ blender ✓ + Search Bell (✿ Harness
panes
-Claude 0% Codex 50% M2 > openharness > branch-name > #439
+10 live · 1.4 GB · 12% CPU M2 > openharness > branch-name > #439
```
The context follows the focused pane. The branch stays clickable in the
-footer; pane headers do not repeat it. Empty New Tabs have no footer.
+footer; pane headers do not repeat it. An empty New Tab keeps the footer when
+there are live sessions to inspect.
+
+Harness Monitor sits at the bottom left. Its counter opens the existing session
+manager above it, filtered to live sessions. RAM and CPU can be sorted highest
+first; tokens use the counts already carried by agent updates. Include live
+sessions on connected owned machines even when none of this window's tabs show
+them. Discovery must not open panes or start an engine. Saved history remains
+in the All and Saved views.
+
+Each owning daemon takes one process snapshot for the whole list. Count nested
+registered engines once, retain process birth identities, and report missing
+readings as unknown. RAM is estimated resident memory including child processes;
+CPU measures the interval, with 100% representing one core. A `+` after a total
+means some session readings are unavailable. The tooltip explains these limits.
+Do not show GPU use, disk activity or token cost inferred from unrelated totals.
+
+The footer samples every 15 seconds while the app is foreground; an open monitor
+uses three seconds. Requests coalesce in the daemon. Hidden apps run no monitor
+polling, and inspecting tokens never starts another transcript scan. The native
+and Flutter controls share labels and behavior. Subscription usage remains
+beside the monitor in wide windows and accessible through Models at every size.
The optional Experimental creature sits after Store in a fixed 44pt slot.
Tim and eggs use bundled bitmap art; hovering opens a full-size preview without
diff --git a/desktop/integration_test/native_resume_e2e_test.dart b/desktop/integration_test/native_resume_e2e_test.dart
index 5721bd278..f818b21e3 100644
--- a/desktop/integration_test/native_resume_e2e_test.dart
+++ b/desktop/integration_test/native_resume_e2e_test.dart
@@ -17,6 +17,7 @@ import 'package:harness/widgets/harness_session_manager.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/ws/ws_conn.dart';
+import '../test/support/workspace_tools.dart' show openWorkspaceManagement;
import '../test/swarm_interactions_test.dart' show chord;
import '../test/swarm_screen_test.dart' show mount;
import '../test/swarm_state_test.dart' show createApp;
@@ -210,7 +211,7 @@ void main() {
app.stateOf('m')!.agents.any((a) => a.id == id && a.isStopped),
'$engine saved row before manager cycle $cycle',
);
- await tester.tap(find.byTooltip('Harnesses'));
+ await openWorkspaceManagement(tester, 'harnesses');
await tester.pump();
await tester.tap(toggle);
await tester.tap(toggle);
@@ -263,10 +264,28 @@ void main() {
);
expect(app.allPanes.any((p) => p.agentId == anchorId), isTrue);
expect(find.byType(HarnessSessionManager), findsNothing);
- await tester.tap(find.byTooltip('Harnesses'));
+ await tester.tap(
+ find.byKey(const ValueKey('workspace-harness-monitor')),
+ );
await tester.pump();
await tester.tap(toggle);
- await tester.tap(toggle);
+ await tester.pump();
+ // A working engine must ask; an idle one can close directly.
+ await until(
+ () =>
+ find
+ .byKey(const Key('session-close-now'))
+ .evaluate()
+ .isNotEmpty ||
+ app.stateOf('m')!.agents.any((a) => a.id == id && a.isStopped),
+ '$engine close review',
+ );
+ if (find
+ .byKey(const Key('session-close-now'))
+ .evaluate()
+ .isNotEmpty) {
+ await tester.tap(find.byKey(const Key('session-close-now')));
+ }
await until(
() =>
app
@@ -279,9 +298,10 @@ void main() {
expect((await get('/verify?id=$id'))['stopped'], true);
expect(app.allPanes.any((p) => p.agentId == id), isFalse);
expect(app.allPanes.any((p) => p.agentId == anchorId), isTrue);
- expect(find.byType(HarnessSessionManager), findsOneWidget);
- await tester.tap(find.byTooltip('Close harnesses'));
- await tester.pump();
+ if (find.byType(HarnessSessionManager).evaluate().isNotEmpty) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ }
}
}
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/lib/core/harness_resources.dart b/desktop/lib/core/harness_resources.dart
new file mode 100644
index 000000000..0859acd94
--- /dev/null
+++ b/desktop/lib/core/harness_resources.dart
@@ -0,0 +1,83 @@
+/// Optional process readings from the session's owning machine. Unknown is
+/// never zero; memory is resident bytes including child processes, not private
+/// physical RAM. CPU is interval use, with 100% representing one core.
+class HarnessResources {
+ const HarnessResources({
+ this.memoryBytes,
+ this.cpuPercent,
+ this.processCount,
+ });
+ final double? memoryBytes, cpuPercent;
+ final int? processCount;
+
+ factory HarnessResources.fromJson(Map<String, dynamic> json) {
+ double? number(String key) {
+ final value = json[key];
+ return value is num && value.isFinite && value >= 0
+ ? value.toDouble()
+ : null;
+ }
+
+ final count = json['processCount'];
+ return HarnessResources(
+ memoryBytes: number('memoryBytes'),
+ cpuPercent: number('cpuPercent'),
+ processCount: count is int && count >= 0 ? count : null,
+ );
+ }
+
+ String get label =>
+ '${formatHarnessMemory(memoryBytes)} RAM · ${cpuPercent == null ? '—' : cpuPercent!.toStringAsFixed(1)}% CPU';
+ static const explanation =
+ 'RAM includes child processes and may include shared memory. CPU: 100% is one core. Unavailable readings show —.';
+}
+
+class MachineHarnessResources {
+ const MachineHarnessResources({
+ required this.sampledAt,
+ required this.agents,
+ this.shared = const [],
+ });
+ final DateTime sampledAt;
+ final Map<String, HarnessResources> agents;
+ final List<(Set<String>, HarnessResources)> shared;
+
+ static MachineHarnessResources? parse(Object? value) {
+ if (value is! Map ||
+ value['sampledAt'] is! String ||
+ value['agents'] is! List) {
+ return null;
+ }
+ final time = DateTime.tryParse(value['sampledAt'] as String);
+ if (time == null) return null;
+ final rows = <String, HarnessResources>{};
+ for (final row in value['agents'] as List) {
+ if (row is Map<String, dynamic> && row['agentId'] is String) {
+ rows[row['agentId'] as String] = HarnessResources.fromJson(row);
+ }
+ }
+ return MachineHarnessResources(
+ sampledAt: time,
+ agents: Map.unmodifiable(rows),
+ shared: List.unmodifiable([
+ if (value['shared'] is List)
+ for (final row in value['shared'] as List)
+ if (row is Map<String, dynamic> &&
+ row['kind'] == 'codex' &&
+ row['agentIds'] is List)
+ (
+ (row['agentIds'] as List).whereType<String>().toSet(),
+ HarnessResources.fromJson(row),
+ ),
+ ]),
+ );
+ }
+}
+
+String formatHarnessMemory(double? bytes) {
+ if (bytes == null) return '—';
+ // Decimal units match the GB and MB labels (not GiB / MiB).
+ return bytes >= 1e9
+ ? '${(bytes / 1e9).toStringAsFixed(1)} GB'
+ : '${(bytes / 1e6).toStringAsFixed(0)} MB';
+}
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index e5ee9bcf5..58e92e64a 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -340,6 +340,10 @@ class Agent {
/// The CLI's transcript/hook activity time, not its registry refresh time.
final DateTime? lastActivityAt;
+ final DateTime? createdAt;
+ final bool closeSupported;
+ final String? closePlanState;
+ final String? closePlanDetail;
/// When a person last opened or focused this harness in ANY client, as the
/// owning daemon recorded it (`lastOpenedAt`, stamped by `agent_update
@@ -447,6 +451,10 @@ class Agent {
this.project,
this.gitContext,
this.lastActivityAt,
+ this.createdAt,
+ this.closeSupported = false,
+ this.closePlanState,
+ this.closePlanDetail,
this.lastOpenedAt,
this.tokensUsed,
this.tokensUpdatedAt,
@@ -585,6 +593,18 @@ class Agent {
lastActivityAt: j['updatedAt'] is String
? DateTime.tryParse(j['updatedAt'] as String)
: null,
+ createdAt: j['createdAt'] is String
+ ? DateTime.tryParse(j['createdAt'] as String)
+ : null,
+ closeSupported: j['closeSupported'] == true,
+ closePlanState:
+ j['closePlan'] is Map &&
+ const {'waiting', 'failed'}.contains(j['closePlan']['state'])
+ ? j['closePlan']['state'] as String
+ : null,
+ closePlanDetail: j['closePlan'] is Map
+ ? _safeDetail(j['closePlan']['detail'])
+ : null,
lastOpenedAt: j['lastOpenedAt'] is String
? DateTime.tryParse(j['lastOpenedAt'] as String)
: null,
@@ -628,6 +648,7 @@ class Agent {
String? status,
bool? terminalAvailable,
DateTime? lastOpenedAt,
+ bool clearClosePlan = false,
}) => Agent(
id: id,
sessionId: sessionId,
@@ -648,6 +669,10 @@ class Agent {
project: project,
gitContext: gitContext ?? this.gitContext,
lastActivityAt: lastActivityAt,
+ createdAt: createdAt,
+ closeSupported: closeSupported,
+ closePlanState: clearClosePlan ? null : closePlanState,
+ closePlanDetail: clearClosePlan ? null : closePlanDetail,
lastOpenedAt: lastOpenedAt ?? this.lastOpenedAt,
tokensUsed: tokensUsed,
tokensUpdatedAt: tokensUpdatedAt,
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 67be3b5d0..7f3d7861b 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -27,6 +27,7 @@ const Set<String> encryptedDownTypes = {
'grid_fleet_run',
'grid_fleet_cancel',
'machine_resources',
+ 'agent_close',
'phone_pair',
'viewer_surface',
'api_connections',
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 781af8a8e..78531f81a 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -24,6 +24,7 @@ import '../models/api_connections_controller.dart' show agentOnApiModel;
import '../models/models_panel.dart';
import '../models/model_search_catalog.dart';
import '../widgets/resting_section.dart' show confirmSwitchAnyway;
+import '../widgets/session_close_dialog.dart';
import '../notify/system_notifications.dart';
import '../settings/sections/account_device_detail.dart';
import '../settings/settings_screen.dart';
@@ -50,6 +51,7 @@ import '../widgets/linux_menu_bar.dart'
import '../widgets/notification_inbox.dart';
import '../widgets/workspace_notifications_button.dart';
import '../state/harness_sessions.dart';
+import '../state/harness_monitor.dart';
import '../state/harness_activity.dart';
import '../state/harness_attachments.dart';
import '../state/harness_placement.dart';
@@ -573,6 +575,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.deviceNavigationAllowed = _allowDeviceNavigation;
app.deviceFormCommand = _deviceFormCommand;
_pullRequest = WorkspacePullRequest(app)..addListener(_statusPrefsChanged);
+ _harnessMonitor = HarnessMonitor(app)..addListener(_monitorChanged);
+ app.reviewSessionClose = _reviewSessionClose;
_keymap.addListener(_keymapChanged);
app.hasNavigationRail = false;
app.railFocused = false;
@@ -712,6 +716,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.modelManager.start();
// Subscription usage is read ahead, so opening a menu shows it without waiting.
_modelsMenu!.start();
+ _harnessMonitor.start();
});
}
if (_menuHost) {
@@ -773,6 +778,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
@override
void dispose() {
+ _harnessMonitor.dispose();
+ if (app.reviewSessionClose == _reviewSessionClose) {
+ app.reviewSessionClose = null;
+ }
linuxTitleBarActions.detach(this);
_closeDaemonHint();
app.foreground.removeListener(_daemonEnvironmentChanged);
@@ -1477,6 +1486,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
}
+ late final HarnessMonitor _harnessMonitor;
+ void _monitorChanged() {
+ if (!mounted) return;
+ if (_menuHost) _syncNative();
+ }
+
WorkspaceSubscriptionUsage get _subscriptionUsage =>
WorkspaceSubscriptionUsage.fromRows(_modelsMenu?.rows ?? const []);
@@ -1789,6 +1804,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
.toList(),
'interactive': _shortcutsEnabled,
},
+ 'harnessMonitor': {
+ 'text': _harnessMonitor.label,
+ 'label': _harnessMonitor.detail,
+ 'detail': _harnessMonitor.detail,
+ 'segments': [
+ {'text': _harnessMonitor.label},
+ ],
+ 'interactive': _shortcutsEnabled,
+ },
'footerCovered':
!_showWorkspaceFooter ||
(!_routeIsCurrent && !_footerPreviewCurrent) ||
@@ -2109,8 +2133,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
return;
}
- if (call.method == 'harnessControls') {
- _toggleHarnessControls();
+ if (call.method == 'harnessControls' || call.method == 'resourceMonitor') {
+ _toggleHarnessControls(liveOnly: call.method == 'resourceMonitor');
await WidgetsBinding.instance.endOfFrame;
return;
}
@@ -2262,9 +2286,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'select':
if (args['id'] is String) app.selectSwarm(args['id']);
case 'close':
- if (args['id'] is String) await app.closeSwarm(args['id']);
+ if (args['id'] is String) await app.requestCloseSwarm(args['id']);
case 'closeActive':
- await app.closeSwarm(app.activeSwarmId);
+ await app.requestCloseSwarm(app.activeSwarmId);
case 'rename':
// Acknowledge after the form opens so the titlebar can hand its native
// keyboard focus to Flutter while the user edits the name.
@@ -2385,7 +2409,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
case 'closePane':
- if (app.focusedPane case final pane?) unawaited(app.closePane(pane.id));
+ if (app.focusedPane case final pane?) {
+ unawaited(app.requestClosePane(pane.id));
+ }
case 'findTerminal':
app.focusedPane?.session?.find(TerminalFindAction.open);
case 'findNext':
@@ -2475,6 +2501,77 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (restoreEntry) await _ensureEmptyEntry();
}
+ Future<bool> _reviewSessionClose(List<(String, Agent)> targets) async {
+ final choices =
+ <(Agent, Future<Map<String, dynamic>> Function(String), String)>[];
+ Future<String?> choose(
+ Agent agent,
+ String activity, {
+ String? error,
+ }) async {
+ String? result;
+ _closeHarnessControls(restoreFocus: false);
+ await _dialog(() async {
+ result = await showSessionCloseDialog(
+ context,
+ agent,
+ activity,
+ keymap: _keymap,
+ error: error,
+ );
+ }, restoreEntry: false);
+ return result;
+ }
+
+ // Review every working session before stopping any member of a whole tab.
+ for (final (machine, agent) in targets) {
+ if (!mounted) return false;
+ final request = app.prepareSessionClose(machine, agent);
+ final state = await request('inspect');
+ if (!mounted) return false;
+ if (state['error'] != null) {
+ await choose(
+ agent,
+ 'unknown',
+ error:
+ state['detail'] as String? ??
+ 'Could not check this session. It has been kept open.',
+ );
+ return false;
+ }
+ final activity = state['activity'] as String? ?? 'unknown';
+ final mode = activity == 'idle' ? 'idle' : await choose(agent, activity);
+ if (mode == null) return false;
+ choices.add((agent, request, mode));
+ }
+ for (final (agent, request, mode) in choices) {
+ if (!mounted) return false;
+ var result = await request(mode);
+ if (!mounted) return false;
+ // Work may have begun while the person was reviewing another session.
+ if (result['error'] == 'SESSION_NOT_IDLE') {
+ final next = await choose(
+ agent,
+ result['activity'] as String? ?? 'unknown',
+ );
+ if (next == null) return false;
+ result = await request(next);
+ }
+ if (!mounted) return false;
+ if (result['closed'] != true && result['deferred'] != true) {
+ await choose(
+ agent,
+ 'unknown',
+ error:
+ result['detail'] as String? ??
+ 'Could not close this session safely. Its saved history is kept.',
+ );
+ return false;
+ }
+ }
+ return true;
+ }
+
Future<void> _rename(String id) => _dialog(() async {
final swarm = app.swarms.where((s) => s.id == id).firstOrNull;
if (swarm == null) return;
@@ -4930,7 +5027,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
}
- void _toggleHarnessControls() {
+ void _toggleHarnessControls({bool liveOnly = false}) {
if (_harnessesOverlay != null) {
_closeHarnessControls();
return;
@@ -4956,8 +5053,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
Positioned(
- top: (_native ? 0.0 : _tabBarHeight) + 8,
- right: 10,
+ bottom: _statusBarHeight + 8,
+ left: 10,
width: (constraints.maxWidth - 20).clamp(0, 640),
child: ConstrainedBox(
constraints: BoxConstraints(
@@ -4971,6 +5068,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
keymap: _keymap,
child: HarnessSessionManager(
app: app,
+ monitor: _harnessMonitor,
+ initialFilter: liveOnly
+ ? SessionFilter.running
+ : SessionFilter.all,
introduction: _onboarding.next == OnboardingStep.harnesses
? OnboardingCard(
title: 'Run your first harness',
@@ -5008,6 +5109,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
);
overlay.insert(_harnessesOverlay!);
+ _harnessMonitor.setExpanded(true);
_unregisterHarnesses = registerTransientMenu(
() => _closeHarnessControls(restoreFocus: false),
);
@@ -5022,6 +5124,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_harnessesOverlay?.remove();
_harnessesOverlay?.dispose();
_harnessesOverlay = null;
+ _harnessMonitor.setExpanded(false);
if (!mounted) return;
if (_menuHost) _syncNative();
setState(() {});
@@ -5947,7 +6050,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
late final Map<ShortcutAction, VoidCallback> _actionHandlers = {
ShortcutAction.newSwarm: _newTab,
ShortcutAction.reopenClosedSwarm: app.reopenClosed,
- ShortcutAction.closeSwarm: () => app.closeSwarm(app.activeSwarmId),
+ ShortcutAction.closeSwarm: () => app.requestCloseSwarm(app.activeSwarmId),
ShortcutAction.renameSwarm: () => _rename(app.activeSwarmId),
ShortcutAction.nextSwarm: () => app.stepSwarm(1),
ShortcutAction.previousSwarm: () => app.stepSwarm(-1),
@@ -5975,7 +6078,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
ShortcutAction.addAgent: _addAgent,
ShortcutAction.closePane: () {
if (app.focusedPane case final pane?) {
- unawaited(app.closePane(pane.id));
+ unawaited(app.requestClosePane(pane.id));
}
},
ShortcutAction.newAgent: _newAgent,
@@ -6887,6 +6990,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
// halfway between the pane edge and window bottom. Pane height is unchanged.
bool get _showWorkspaceFooter =>
!newHarnessOpensInBox ||
+ _harnessMonitor.live.isNotEmpty ||
app.panes.isNotEmpty ||
app.activeSwarm.isStore ||
app.activeSwarm.isOrchestrator ||
@@ -6994,16 +7098,26 @@ class _SwarmScreenState extends State<SwarmScreen> {
final download = kIsWeb && !_compact(context);
final downloadWidth = download ? available * .16 : 0.0;
final usage = _subscriptionUsage;
- final usageWidth =
- math.max(
- 0.0,
- available -
- shareWidth -
- downloadWidth -
- (!kIsWeb && _slotShown ? 44 : 0) -
- cell.width * 5,
- ) *
- .45;
+ final resourceBudget = math.max(
+ 0.0,
+ available -
+ shareWidth -
+ downloadWidth -
+ (!kIsWeb && _slotShown ? 44 : 0) -
+ cell.width * 5,
+ );
+ final monitorWidth = resourceBudget * .55;
+ final usageWidth = constraints.maxWidth < 1050
+ ? 0.0
+ : math.max(
+ 0.0,
+ available -
+ shareWidth -
+ downloadWidth -
+ (!kIsWeb && _slotShown ? 44 : 0) -
+ cell.width * 5,
+ ) *
+ .22;
final paneContext = Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
@@ -7051,38 +7165,29 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: Row(
children: [
ConstrainedBox(
- constraints: BoxConstraints(maxWidth: usageWidth),
- child: WorkspaceBarControl(
- key: const ValueKey('workspace-subscription-usage'),
- label: usage.detail,
- tooltip: usage.detail,
- onPressed: _shortcutsEnabled
- ? () =>
- _toggleModels(initialTab: ModelsTab.subscriptions)
- : null,
- builder: (context, emphasized) => Padding(
- padding: EdgeInsets.symmetric(horizontal: cell.width),
- child: SizedBox(
- height: workspaceBarControlHeight(context),
- child: Center(
- widthFactor: 1,
- child: Text.rich(
- TextSpan(
- children: [
- for (final part in usage.paintSegments(
- foreground: theme.foreground,
- surface: grid.AppPalette.swarmField,
- ))
- TextSpan(
- text: part.text,
- style: TextStyle(color: part.foreground),
- ),
- ],
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: workspaceBarTextStyle(
- emphasized: emphasized,
+ constraints: BoxConstraints(maxWidth: monitorWidth),
+ child: ListenableBuilder(
+ listenable: _harnessMonitor,
+ builder: (context, _) => WorkspaceBarControl(
+ key: const ValueKey('workspace-harness-monitor'),
+ label: _harnessMonitor.detail,
+ tooltip: _harnessMonitor.detail,
+ onPressed: _shortcutsEnabled
+ ? () => _toggleHarnessControls(liveOnly: true)
+ : null,
+ builder: (context, emphasized) => Padding(
+ padding: EdgeInsets.symmetric(horizontal: cell.width),
+ child: SizedBox(
+ height: workspaceBarControlHeight(context),
+ child: Center(
+ widthFactor: 1,
+ child: Text(
+ _harnessMonitor.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: workspaceBarTextStyle(
+ emphasized: emphasized,
+ ),
),
),
),
@@ -7090,6 +7195,48 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
),
+ if (usageWidth > 0)
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: usageWidth),
+ child: WorkspaceBarControl(
+ key: const ValueKey('workspace-subscription-usage'),
+ label: usage.detail,
+ tooltip: usage.detail,
+ onPressed: _shortcutsEnabled
+ ? () => _toggleModels(
+ initialTab: ModelsTab.subscriptions,
+ )
+ : null,
+ builder: (context, emphasized) => Padding(
+ padding: EdgeInsets.symmetric(horizontal: cell.width),
+ child: SizedBox(
+ height: workspaceBarControlHeight(context),
+ child: Center(
+ widthFactor: 1,
+ child: Text.rich(
+ TextSpan(
+ children: [
+ for (final part in usage.paintSegments(
+ foreground: theme.foreground,
+ surface: grid.AppPalette.swarmField,
+ ))
+ TextSpan(
+ text: part.text,
+ style: TextStyle(color: part.foreground),
+ ),
+ ],
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: workspaceBarTextStyle(
+ emphasized: emphasized,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
SizedBox(width: cell.width * 2),
if (!kIsWeb && _slotShown) _daemonTabButton(),
if (download) ...[
@@ -7256,7 +7403,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
final armed = _middleDownTab;
_middleDownTab = null;
if (armed == swarm.id) {
- unawaited(app.closeSwarm(swarm.id));
+ unawaited(app.requestCloseSwarm(swarm.id));
}
},
child: DesktopWorkspaceTab(
@@ -7278,7 +7425,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
? () => app.selectSwarm(swarm.id)
: null,
onClose: _shortcutsEnabled
- ? () => unawaited(app.closeSwarm(swarm.id))
+ ? () =>
+ unawaited(app.requestCloseSwarm(swarm.id))
: null,
activity: activity == null || activity.mark.isEmpty
? null
diff --git a/desktop/lib/shortcuts/keyboard_practice.dart b/desktop/lib/shortcuts/keyboard_practice.dart
index 366d80e2b..e120edb4d 100644
--- a/desktop/lib/shortcuts/keyboard_practice.dart
+++ b/desktop/lib/shortcuts/keyboard_practice.dart
@@ -43,10 +43,8 @@ class KeyboardLesson {
'agent.add' => '[harness 1] │ [harness 2]\nBoth harnesses share this tab.',
'agent.new' => 'Codex · This Mac · payments\nHarness anything (optional)\nNew harness is selected. Return starts with these settings; Tab reaches each control. Model, approvals, and Codex profile are below the message.',
'pane.zoom' => '[harness 2 — full workspace]\nPress the same key to restore the other panes.',
- 'pane.close' =>
- '[harness 1]\nThe second view closes. Its harness keeps running.',
- 'swarm.close' =>
- '[previous tab]\nThe view closes. Its harnesses keep running.',
+ 'pane.close' => '[harness 1]\nClosing the last view saves idle work to disk. Working sessions ask when to stop.',
+ 'swarm.close' => '[previous tab]\nIdle sessions are saved and closed. Working sessions ask when to stop.',
'navigation.commands' => '>rename\nRename Harness\nRename Tab',
'terminal.find' => 'find > timeout\n1/3 matches in this terminal’s output',
'picker.complete' => 'project ~/work/payments\nTab completes the current argument; Enter accepts it.',
@@ -75,7 +73,7 @@ class KeyboardLesson {
'picker.more_options' => 'New harness\nOpen the composer from search. In the composer, choose a model; Terminal opens the Repo list.',
'picker.toggle_preview' =>
'results │ preview\nToggle again to hide the preview.',
- 'agent.stop' => 'Stop Harness?\n> Cancel Stop\nStopping ends the running harness; its saved conversation is kept. Closing a pane only closes a view.',
+ 'agent.stop' => 'Stop Harness?\n> Cancel Stop\nStopping ends the running harness; its saved conversation is kept. Switching tabs keeps work running.',
'agent.restart' => 'Restart Harness\nRestarts the harness in the same pane and tries to resume its conversation.',
'agent.fork' =>
'Fork Harness\nChoose a name and first task. The source stays open.',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index fc47dedef..a08af3105 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -43,6 +43,7 @@ import '../core/local_hostname.dart';
import '../core/local_git_projects.dart';
import '../core/test_run.dart';
import '../core/models.dart';
+import '../core/harness_resources.dart';
import '../core/machine_resources.dart';
import '../core/project_folder.dart';
import '../core/git_worktree.dart';
@@ -581,6 +582,11 @@ class AppNotifier extends ChangeNotifier {
final _agentRenames = <(String, String), _AgentRename>{};
final _agentStops = <(String, String), _AgentStop>{};
final _agentPauses = <(String, String), Future<String?>>{};
+
+ /// The workspace supplies presentation; the model owns target identity and completion.
+ Future<bool> Function(List<(String, Agent)>)? reviewSessionClose;
+ final _viewCloseRequests = <String, Future<void>>{};
+ final _closingViewAgents = <(String, String), int>{};
final _agentForks = <(String, String), AgentForkAttempt>{};
final _agentRestarts = <(String, String), AgentRestartAttempt>{};
int _machineEditRevision = 0;
@@ -1719,6 +1725,210 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Explicit user Close. Layout cleanup, tab switching, sign-out and moving a
+ /// tile continue using their existing view-only operations.
+ Future<void> requestCloseSwarm(String id) {
+ final tab = swarms.where((s) => s.id == id).firstOrNull;
+ if (tab == null) return Future.value();
+ final captured = tab.panes.toList();
+ return _requestViewClose('tab:$id', tab, captured, () async {
+ if (tab.panes.length != captured.length ||
+ !captured.every(tab.panes.contains)) {
+ return;
+ }
+ await closeSwarm(id);
+ });
+ }
+
+ Future<void> requestClosePane(int paneId) {
+ final tab = activeSwarm;
+ final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;
+ if (pane == null) return Future.value();
+ if (tab.isCompanions) return requestCloseSwarm(tab.id);
+ final captured = tab.panes
+ .where(
+ (p) =>
+ identical(p, pane) ||
+ (!pane.isWeb &&
+ p.isWeb &&
+ p.machineId == pane.machineId &&
+ p.ownerAgentId == pane.agentId),
+ )
+ .toList();
+ return _requestViewClose('pane:${tab.id}:$paneId', tab, captured, () async {
+ if (tab.panes.contains(pane)) await closePane(paneId, swarmId: tab.id);
+ });
+ }
+
+ Future<void> _requestViewClose(
+ String key,
+ Swarm tab,
+ List<TerminalPane> closing,
+ Future<void> Function() finish,
+ ) {
+ if (_disposed) return Future.value();
+ if (_viewCloseRequests[key] case final pending?) return pending;
+ final targets = <(String, Agent)>[];
+ final seen = <(String, String)>{};
+ for (final pane in closing) {
+ final id = pane.agentId;
+ if (pane.isWeb || id == null || !seen.add((pane.machineId, id))) continue;
+ // The same pane object may belong to several tabs. Only its last view
+ // closes the underlying session, even when another tab is hidden.
+ final remains = swarms.any(
+ (other) => other.panes.any(
+ (p) =>
+ !p.isWeb &&
+ p.machineId == pane.machineId &&
+ p.agentId == id &&
+ (!identical(other, tab) || !closing.contains(p)),
+ ),
+ );
+ if (remains) continue;
+ final machine = stateOf(pane.machineId);
+ final agent = machine?.agents.where((a) => a.id == id).firstOrNull;
+ if (machine?.machine.isShared == true ||
+ agent == null ||
+ agent.isStopped ||
+ !agent.terminalAvailable ||
+ !agent.closeSupported) {
+ continue;
+ }
+ targets.add((pane.machineId, agent));
+ }
+ final revision = _authRevision;
+ for (final (machine, agent) in targets) {
+ final target = (machine, agent.id);
+ _closingViewAgents[target] = (_closingViewAgents[target] ?? 0) + 1;
+ }
+ final completion = Completer<void>();
+ final request = completion.future;
+ _viewCloseRequests[key] = request;
+ unawaited(
+ (() async {
+ try {
+ if (targets.isNotEmpty &&
+ (reviewSessionClose == null ||
+ !await reviewSessionClose!(targets))) {
+ return;
+ }
+ if (!_authWorkCurrent(revision) || !swarms.contains(tab)) return;
+ await finish();
+ } catch (_) {
+ if (_authWorkCurrent(revision)) {
+ _lastError = 'Could not close this session safely. Check its state and try again.';
+ _lastErrorRetryable = true;
+ notifyListeners();
+ }
+ } finally {
+ for (final (machine, agent) in targets) {
+ final target = (machine, agent.id);
+ final remaining = (_closingViewAgents[target] ?? 1) - 1;
+ if (remaining == 0) {
+ _closingViewAgents.remove(target);
+ } else {
+ _closingViewAgents[target] = remaining;
+ }
+ }
+ if (identical(_viewCloseRequests[key], request)) {
+ _viewCloseRequests.remove(key);
+ }
+ completion.complete();
+ }
+ })(),
+ );
+ return request;
+ }
+
+ /// Capture once before showing a prompt. Old/replaced targets cannot inherit its answer.
+ Future<Map<String, dynamic>> Function(String) prepareSessionClose(
+ String machineId,
+ Agent agent,
+ ) {
+ final machine = stateOf(machineId);
+ final revision = _authRevision;
+ final removal = machine?._agentRemovals[agent.id];
+ return (mode) async {
+ bool sameAgent(Agent? current) =>
+ current != null &&
+ current.createdAt == agent.createdAt &&
+ current.sessionId == agent.sessionId;
+ final current = machine?.agents
+ .where((a) => a.id == agent.id)
+ .firstOrNull;
+ if (machine == null ||
+ machine.machine.isShared ||
+ !_machineWorkCurrent(machine, revision) ||
+ machine._agentRemovals[agent.id] != removal ||
+ !sameAgent(current)) {
+ return {
+ 'error': 'AGENT_CHANGED',
+ 'detail': 'The session changed. Check it before closing.',
+ };
+ }
+ if (agent.createdAt == null || !agent.closeSupported) {
+ return {
+ 'error': 'UNSUPPORTED',
+ 'detail': 'Update the Harness CLI on this machine to close saved sessions safely.',
+ };
+ }
+ Map<String, dynamic> result;
+ try {
+ result = await _conn(machineId).request(
+ 'agent_close',
+ payload: {
+ 'agentId': agent.id,
+ 'sessionId': agent.sessionId ?? '',
+ 'createdAt': agent.createdAt!.toUtc().toIso8601String(),
+ 'mode': mode,
+ },
+ );
+ } catch (_) {
+ // A lost reply never causes a second Stop. Authoritative saved inventory
+ // can confirm it; otherwise keep the pane and report uncertainty.
+ await reloadMachineData(machineId);
+ final observed = machine.agents
+ .where((a) => a.id == agent.id)
+ .firstOrNull;
+ if (_machineWorkCurrent(machine, revision) &&
+ sameAgent(observed) &&
+ observed!.isStopped) {
+ return {'closed': true};
+ }
+ return {
+ 'error': 'CLOSE_UNCONFIRMED',
+ 'detail': 'Could not confirm the close. Check the machine connection and try again.',
+ };
+ }
+ if (!_machineWorkCurrent(machine, revision)) {
+ return {'error': 'AGENT_CHANGED'};
+ }
+ final observed = machine.agents
+ .where((a) => a.id == agent.id)
+ .firstOrNull;
+ if (observed != null && !sameAgent(observed)) {
+ return {'error': 'AGENT_CHANGED'};
+ }
+ if (result['closed'] == true &&
+ (observed == null || !observed.isStopped)) {
+ _upsertAgent(
+ machine,
+ agent.copyWith(
+ status: 'stopped',
+ terminalAvailable: false,
+ clearClosePlan: true,
+ ),
+ );
+ notifyListeners();
+ }
+ if (result['cancelled'] == true && observed != null) {
+ _upsertAgent(machine, observed.copyWith(clearClosePlan: true));
+ notifyListeners();
+ }
+ return result;
+ };
+ }
+
void reopenClosedSwarm({String? historyId}) {
if (_disposed) return;
final index = _closedHistory.lastIndexWhere(
@@ -3690,7 +3900,9 @@ class AppNotifier extends ChangeNotifier {
// the log existed), and every machine it names is trusted with no password.
if (signedIn) {
if (_deviceLog case final log?) {
- unawaited(log.register(freshSignIn: viewer?.auth.consumeFreshSignIn() ?? false));
+ unawaited(
+ log.register(freshSignIn: viewer?.auth.consumeFreshSignIn() ?? false),
+ );
}
}
try {
@@ -5645,6 +5857,10 @@ class AppNotifier extends ChangeNotifier {
prev.project != agent.project ||
prev.gitContext != agent.gitContext ||
prev.lastActivityAt != agent.lastActivityAt ||
+ prev.createdAt != agent.createdAt ||
+ prev.closeSupported != agent.closeSupported ||
+ prev.closePlanState != agent.closePlanState ||
+ prev.closePlanDetail != agent.closePlanDetail ||
prev.lastOpenedAt != agent.lastOpenedAt ||
prev.tokensUsed != agent.tokensUsed ||
prev.outputStats != agent.outputStats ||
@@ -5806,7 +6022,10 @@ class AppNotifier extends ChangeNotifier {
final log = _deviceLog;
if (log == null) return;
final now = DateTime.now();
- if (_deviceLogReadAt case final last? when now.difference(last) < const Duration(seconds: 30)) return;
+ if (_deviceLogReadAt case final last?
+ when now.difference(last) < const Duration(seconds: 30)) {
+ return;
+ }
_deviceLogReadAt = now;
unawaited(log.refresh());
}
@@ -5857,7 +6076,9 @@ class AppNotifier extends ChangeNotifier {
/// Take [pub] out of the account on every device. Null when done, else why not.
Future<String?> removeDevice(String pub) async {
- final error = _deviceLog != null ? await _deviceLog!.remove(pub) : await api.daemonRemoveDevice(pub);
+ final error = _deviceLog != null
+ ? await _deviceLog!.remove(pub)
+ : await api.daemonRemoveDevice(pub);
if (error == null) newDevices.removeWhere((d) => d.pub == pub);
devicesRevision++;
notifyListeners();
@@ -5872,7 +6093,9 @@ class AppNotifier extends ChangeNotifier {
final r = await log.rebaseline(confirm: confirm);
result = r == null ? null : DevicesRebaseline.fromViewer(r);
} else {
- result = DevicesRebaseline.fromDaemon(await api.daemonRebaselineDevices(confirm: confirm));
+ result = DevicesRebaseline.fromDaemon(
+ await api.daemonRebaselineDevices(confirm: confirm),
+ );
}
if (confirm) {
devicesRevision++;
@@ -6743,6 +6966,21 @@ class AppNotifier extends ChangeNotifier {
/// A visible Machines panel uses the existing connection; it never dials a
/// disconnected/unlinked host just to obtain optional system readings.
Future<MachineResources?> readMachineResources(String machineId) async {
+ final reply = await _readResourceSnapshot(machineId);
+ return reply == null ? null : MachineResources.fromJson(reply);
+ }
+
+ Future<MachineHarnessResources?> readHarnessResources(
+ String machineId,
+ ) async {
+ final reply = await _readResourceSnapshot(machineId, harnesses: true);
+ return MachineHarnessResources.parse(reply?['harnesses']);
+ }
+
+ Future<Map<String, dynamic>?> _readResourceSnapshot(
+ String machineId, {
+ bool harnesses = false,
+ }) async {
final machine = machineStates[machineId];
if (_disposed ||
machine == null ||
@@ -6760,6 +6998,7 @@ class AppNotifier extends ChangeNotifier {
if (!connection.isReady) return null;
final reply = await connection.request(
'machine_resources',
+ payload: harnesses ? const {'harnesses': true} : const {},
timeout: const Duration(seconds: 3),
);
if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision) ||
@@ -6769,7 +7008,7 @@ class AppNotifier extends ChangeNotifier {
reply['error'] != null) {
return null;
}
- return MachineResources.fromJson(reply);
+ return reply;
} catch (_) {
// Older daemons and temporarily unavailable readings leave the stats blank.
return null;
@@ -7690,6 +7929,17 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> _removeAgent(MachineState machine, String agentId) async {
+ // Repeated retained-stop events must not invalidate the history refresh
+ // already in flight. There is no newer removal when nothing changed.
+ if (machine._agentRemovals.containsKey(agentId) &&
+ !machine.agents.any((agent) => agent.id == agentId) &&
+ !allPanes.any(
+ (pane) =>
+ pane.machineId == machine.machine.machineId &&
+ (pane.agentId == agentId || pane.ownerAgentId == agentId),
+ )) {
+ return;
+ }
final stop = _agentStops[(machine.machine.machineId, agentId)];
final confirmedStop = stop != null && _agentStopCurrent(stop) ? stop : null;
confirmedStop?.confirmed = true;
@@ -7721,6 +7971,9 @@ class AppNotifier extends ChangeNotifier {
(pane.agentId == agentId ||
(pane.isWeb && pane.ownerAgentId == agentId));
if (!owned) continue;
+ // The explicit Close owns these panes until its disk-safe acknowledgement,
+ // so it can preserve recently-closed layout and composer history normally.
+ if (_closingViewAgents.containsKey((machineId, agentId))) continue;
for (final swarm in swarms) {
if (swarm.panes.contains(pane)) {
affected.add(swarm);
@@ -7800,7 +8053,9 @@ class AppNotifier extends ChangeNotifier {
// place rather than reopening a tile.
for (final pane in viewers) {
changed =
- changed || pane.url != url || pane.viewerError != agent.viewerError;
+ changed ||
+ pane.url != url ||
+ pane.viewerError != agent.viewerError;
pane.url = url;
pane.viewerError = agent.viewerError;
}
@@ -9534,7 +9789,12 @@ class AppNotifier extends ChangeNotifier {
}
final now = DateTime.now();
final last = _lastAgentTouch;
- if (last != null &&
+ final queuedClose = machine.agents.any(
+ (a) => a.id == agentId && a.closePlanState != null,
+ );
+ if (!queuedClose &&
+ !_closingViewAgents.containsKey((machineId, agentId)) &&
+ last != null &&
last.machineId == machineId &&
last.agentId == agentId &&
now.difference(last.at) < agentTouchDebounce) {
@@ -11696,16 +11956,20 @@ class AppNotifier extends ChangeNotifier {
/// A pin past the end of a shrunken grid is HELD, not dropped: the tiles that
/// closed can come back, and forgetting the pin the moment the grid got small
/// would quietly undo a choice the user never revisited.
- void _settlePins() {
- final pinned = panes.where(isPanePinned).toList()
- ..sort((a, b) => pinnedSlotFor(a)!.compareTo(pinnedSlotFor(b)!));
+ void _settlePins([Swarm? target]) {
+ final tab = target ?? activeSwarm;
+ final members = tab.panes;
+ int? slot(TerminalPane pane) =>
+ hasNavigationRail ? pane.pinnedSlot : tab.pinnedSlots[pane.id];
+ final pinned = members.where((pane) => slot(pane) != null).toList()
+ ..sort((a, b) => slot(a)!.compareTo(slot(b)!));
for (final pane in pinned) {
- final want = pinnedSlotFor(pane)!;
- if (want >= panes.length) continue;
- final at = panes.indexOf(pane);
+ final want = slot(pane)!;
+ if (want >= members.length) continue;
+ final at = members.indexOf(pane);
if (at == want) continue;
- panes.removeAt(at);
- panes.insert(want, pane);
+ members.removeAt(at);
+ members.insert(want, pane);
}
}
@@ -11829,11 +12093,19 @@ class AppNotifier extends ChangeNotifier {
return true;
}
- Future<void> closePane(int paneId, {bool persist = true}) async {
- final pane = panes.where((p) => p.id == paneId).firstOrNull;
+ Future<void> closePane(
+ int paneId, {
+ bool persist = true,
+ String? swarmId,
+ }) async {
+ final tab = swarmId == null
+ ? activeSwarm
+ : swarms.where((s) => s.id == swarmId).firstOrNull;
+ if (tab == null) return;
+ final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;
if (pane == null) return;
- if (activeSwarm.isCompanions) {
- await closeSwarm(activeSwarmId, persist: persist);
+ if (tab.isCompanions) {
+ await closeSwarm(tab.id, persist: persist);
return;
}
if (pane.isWeb) {
@@ -11846,7 +12118,6 @@ class AppNotifier extends ChangeNotifier {
_dismissedViewers[_viewerKey(pane.machineId, owner)] = viewerState;
}
}
- final tab = activeSwarm;
bool closesWithPane(TerminalPane candidate) =>
candidate == pane ||
(!pane.isWeb &&
@@ -11873,7 +12144,7 @@ class AppNotifier extends ChangeNotifier {
_rememberClosed(
ClosedAgent(
pane,
- activeSwarm,
+ tab,
historyId: 'closed-${_nextClosedHistoryId++}',
name: agent?.name ?? pane.session?.agentName ?? pane.agentId!,
machineName: machine?.machine.displayName ?? pane.machineId,
@@ -11883,21 +12154,21 @@ class AppNotifier extends ChangeNotifier {
}
// Only a close that moves the focus is worth telling the daemon about: a
// background tile going away changes nothing the dial can see.
- final wasFocused = focusedPaneId == paneId;
- activeSwarm.remove(pane);
+ final wasFocused = identical(activeSwarm, tab) && focusedPaneId == paneId;
+ tab.remove(pane);
// A harness's viewer lives beside its terminal and nowhere else: closing
// the terminal in this tab takes the viewer in this tab with it. The
// viewer's own close above is different — it is a choice about the page.
if (!pane.isWeb && pane.agentId != null) {
- for (final viewer in activeSwarm.panes.toList()) {
+ for (final viewer in tab.panes.toList()) {
if (viewer.isWeb &&
viewer.machineId == pane.machineId &&
viewer.ownerAgentId == pane.agentId) {
- activeSwarm.remove(viewer);
+ tab.remove(viewer);
}
}
}
- _settlePins();
+ _settlePins(tab);
if (persist) _persistLayout();
selectedMachineId = focusedPane?.machineId;
if (wasFocused) _announceAppFocus();
@@ -13441,10 +13712,19 @@ class AppNotifier extends ChangeNotifier {
// Only this computer's own daemon says this (a viewer build has no daemon, and a machine's
// frame must not be able to raise a notice here).
if (viewer == null) {
- final pub = payload['pub'], label = payload['label'], kind = payload['kind'];
+ final pub = payload['pub'],
+ label = payload['label'],
+ kind = payload['kind'];
if (pub is String && kind is String) {
final fp = payload['fingerprint'];
- _announceDevice(NewDeviceNotice(pub: pub, label: label is String ? label : '', kind: kind, frameFingerprint: fp is String ? fp : null));
+ _announceDevice(
+ NewDeviceNotice(
+ pub: pub,
+ label: label is String ? label : '',
+ kind: kind,
+ frameFingerprint: fp is String ? fp : null,
+ ),
+ );
}
}
break;
diff --git a/desktop/lib/state/harness_monitor.dart b/desktop/lib/state/harness_monitor.dart
new file mode 100644
index 000000000..30d154206
--- /dev/null
+++ b/desktop/lib/state/harness_monitor.dart
@@ -0,0 +1,174 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import '../core/harness_resources.dart';
+import '../core/models.dart';
+import 'app_state.dart';
+import 'harness_sessions.dart';
+
+/// A single, demand-driven sampler shared by the footer and its open panel.
+/// It never starts an agent, opens a connection, or scans conversation files.
+class HarnessMonitor extends ChangeNotifier {
+ HarnessMonitor(this.app);
+ final AppNotifier app;
+ final _samples = <String, (MachineState, MachineHarnessResources)>{};
+ Timer? _timer;
+ bool _started = false, _disposed = false, _busy = false, _expanded = false;
+ int _revision = 0;
+
+ List<HarnessSession> get sessions => harnessSessions(app, includeLive: true);
+ List<HarnessSession> get live => sessions
+ .where((row) => row.running && !row.machine.machine.isShared)
+ .toList();
+
+ HarnessResources? reading(HarnessSession row) {
+ final snapshot = _samples[row.machineId];
+ return row.running && identical(snapshot?.$1, row.machine)
+ ? snapshot?.$2.agents[row.agent.id]
+ : null;
+ }
+
+ /// Shared-server RSS belongs to the server, not to each conversation.
+ /// Count it once per machine/profile and label it separately in the panel.
+ List<HarnessResources> get sharedReadings {
+ final rows = live;
+ return [
+ for (final entry in _samples.entries)
+ if (identical(app.stateOf(entry.key), entry.value.$1))
+ for (final shared in entry.value.$2.shared)
+ if (rows.any(
+ (row) =>
+ row.machineId == entry.key &&
+ shared.$1.contains(row.agent.id),
+ ))
+ shared.$2,
+ ];
+ }
+
+ String? get sharedLabel {
+ final rows = sharedReadings;
+ if (rows.isEmpty) return null;
+ final known = rows.where((r) => r.memoryBytes != null).toList();
+ final memory = known.fold<double>(0, (sum, r) => sum + r.memoryBytes!);
+ return 'Shared Codex servers · ${formatHarnessMemory(known.isEmpty ? null : memory)}${known.isNotEmpty && known.length < rows.length ? '+' : ''} RAM';
+ }
+
+ String get label {
+ final rows = live;
+ if (rows.isEmpty) return '0 live';
+ (double?, bool) sum(double? Function(HarnessResources) value) {
+ double total = 0;
+ int known = 0;
+ for (final row in rows) {
+ final sample = reading(row);
+ final n = sample == null ? null : value(sample);
+ if (n != null) {
+ total += n;
+ known++;
+ }
+ }
+ final shared = sharedReadings;
+ for (final sample in shared) {
+ final n = value(sample);
+ if (n != null) {
+ total += n;
+ known++;
+ }
+ }
+ return (
+ known == 0 ? null : total,
+ known > 0 && known < rows.length + shared.length,
+ );
+ }
+
+ final memory = sum((r) => r.memoryBytes), cpu = sum((r) => r.cpuPercent);
+ return '${rows.length} live · ${formatHarnessMemory(memory.$1)}${memory.$2 ? '+' : ''} · ${cpu.$1 == null ? '—' : cpu.$1!.toStringAsFixed(0)}%${cpu.$2 ? '+' : ''} CPU';
+ }
+
+ String get detail =>
+ 'Harness Monitor — $label\nLive sessions on connected machines. + means some readings are unavailable. ${HarnessResources.explanation}${sharedLabel == null ? '' : '\n$sharedLabel, included once in the total. These servers may also serve sessions outside Harness.'}';
+
+ void start() {
+ if (_started || _disposed) return;
+ _started = true;
+ app.foreground.addListener(_environmentChanged);
+ app.addListener(_inventoryChanged);
+ _environmentChanged();
+ }
+
+ void setExpanded(bool value) {
+ if (_expanded == value) return;
+ _expanded = value;
+ _timer?.cancel();
+ if (_started && app.foreground.value) unawaited(refresh());
+ }
+
+ void _inventoryChanged() {
+ // Remove credentials' old scope immediately; late responses carry a revision
+ // and AppNotifier independently rejects a replaced account or connection.
+ final removed = _samples.keys.where((id) {
+ final machine = app.stateOf(id);
+ return !identical(machine, _samples[id]?.$1) ||
+ machine?.connectionStatus != ConnectionStatus.connected;
+ }).toList();
+ for (final id in removed) {
+ _samples.remove(id);
+ }
+ if (removed.isNotEmpty) {
+ _revision++;
+ notifyListeners();
+ }
+ }
+
+ void _environmentChanged() {
+ _revision++;
+ _timer?.cancel();
+ if (app.foreground.value) unawaited(refresh());
+ }
+
+ Future<void> refresh() async {
+ if (_disposed || _busy || !app.foreground.value) return;
+ _timer?.cancel();
+ _busy = true;
+ final revision = _revision;
+ final machines = {for (final row in live) row.machineId: row.machine};
+ try {
+ final readings = await Future.wait(
+ machines.entries.map(
+ (entry) async => (
+ entry.key,
+ entry.value,
+ await app.readHarnessResources(entry.key),
+ ),
+ ),
+ );
+ if (_disposed || revision != _revision || !app.foreground.value) return;
+ _samples.clear();
+ for (final (id, machine, result) in readings) {
+ if (result != null && identical(machine, app.stateOf(id))) {
+ _samples[id] = (machine, result);
+ }
+ }
+ notifyListeners();
+ } finally {
+ _busy = false;
+ if (!_disposed && _started && app.foreground.value) {
+ _timer = Timer(Duration(seconds: _expanded ? 3 : 15), refresh);
+ }
+ }
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _revision++;
+ _timer?.cancel();
+ if (_started) {
+ app.foreground.removeListener(_environmentChanged);
+ app.removeListener(_inventoryChanged);
+ }
+ _samples.clear();
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/state/harness_sessions.dart b/desktop/lib/state/harness_sessions.dart
index 1ffdc054a..dfb5f3892 100644
--- a/desktop/lib/state/harness_sessions.dart
+++ b/desktop/lib/state/harness_sessions.dart
@@ -11,7 +11,9 @@ enum SessionSort {
recent('Recently used'),
name('Name'),
machine('Machine'),
- project('Project');
+ project('Project'),
+ memory('RAM: highest first'),
+ cpu('CPU: highest first');
const SessionSort(this.label);
final String label;
@@ -88,13 +90,17 @@ class HarnessSession {
: machine.machine.isShared
? 'View only'
: agent.isStopped
- ? (agent.canPauseAndResume ? 'Paused' : 'Resume unavailable')
+ ? (agent.canPauseAndResume ? 'Saved' : 'Resume unavailable')
: agent.launchState == 'failed'
? 'Start failed'
: agent.launchState == 'starting'
? 'Starting'
: needsInput
? 'Needs input'
+ : agent.closePlanState == 'failed'
+ ? 'Could not close'
+ : agent.closePlanState == 'waiting'
+ ? 'Stops after finishing'
: working
? 'Working'
: agent.terminalAvailable
@@ -117,7 +123,10 @@ class HarnessSession {
: null;
}
-List<HarnessSession> harnessSessions(AppNotifier app) {
+List<HarnessSession> harnessSessions(
+ AppNotifier app, {
+ bool includeLive = false,
+}) {
final open = {
for (final pane in app.allPanes)
if (pane.agentId != null) (pane.machineId, pane.agentId),
@@ -127,7 +136,11 @@ List<HarnessSession> harnessSessions(AppNotifier app) {
return [
for (final machine in app.machineStates.values)
for (final agent in machine.agents)
- if (known(machine.machine.machineId, agent.id))
+ if (known(machine.machine.machineId, agent.id) ||
+ (includeLive &&
+ !machine.machine.isShared &&
+ !agent.isStopped &&
+ agent.terminalAvailable))
HarnessSession(
machine: machine,
agent: agent,
@@ -157,6 +170,8 @@ List<HarnessSession> visibleHarnessSessions(
SessionFilter filter = SessionFilter.all,
SessionSort sort = SessionSort.recent,
List<String> recent = const [],
+ Map<String, double> memory = const {},
+ Map<String, double> cpu = const {},
}) {
final terms = query.toLowerCase().trim().split(RegExp(r'\s+'));
final result = sessions.where((row) {
@@ -194,6 +209,8 @@ List<HarnessSession> visibleHarnessSessions(
(a.project?.label ?? '').toLowerCase(),
(b.project?.label ?? '').toLowerCase(),
),
+ SessionSort.memory => (memory[b.id] ?? -1).compareTo(memory[a.id] ?? -1),
+ SessionSort.cpu => (cpu[b.id] ?? -1).compareTo(cpu[a.id] ?? -1),
};
if (comparison != 0) return comparison;
final name = compareNatural(
diff --git a/desktop/lib/web/tabs/web_tab_switcher.dart b/desktop/lib/web/tabs/web_tab_switcher.dart
index 99efbefe0..d65f248d1 100644
--- a/desktop/lib/web/tabs/web_tab_switcher.dart
+++ b/desktop/lib/web/tabs/web_tab_switcher.dart
@@ -104,11 +104,11 @@ class WebTabSwitcher extends StatelessWidget {
case WebFocusPane(:final paneId):
app.focusPane(paneId, reveal: true);
case WebClosePane(:final paneId):
- unawaited(app.closePane(paneId));
+ unawaited(app.requestClosePane(paneId));
case WebSelectTab(:final id):
app.selectSwarm(id);
case WebCloseTab(:final id):
- unawaited(app.closeSwarm(id));
+ unawaited(app.requestCloseSwarm(id));
case WebRunCommand(:final command):
commands.run(command);
case null:
diff --git a/desktop/lib/widgets/delete_agent_dialog.dart b/desktop/lib/widgets/delete_agent_dialog.dart
index 803bb6220..02b06b463 100644
--- a/desktop/lib/widgets/delete_agent_dialog.dart
+++ b/desktop/lib/widgets/delete_agent_dialog.dart
@@ -11,7 +11,7 @@ import 'box_chrome.dart' show BoxAnnouncer;
import 'engine_identity.dart';
import 'terminal_prompt.dart';
-/// Stopping ends the running process; closing a pane only removes its view.
+/// Explicit Stop ends the running process across its views.
/// Requests remain with the model if this prompt is dismissed.
Future<void> confirmDeleteAgent(
BuildContext context,
@@ -174,7 +174,7 @@ class _StopAgentPromptState extends State<_StopAgentPrompt> {
),
const SizedBox(height: 8),
Text(
- 'Its panes close across tabs. Close Pane keeps it running.',
+ 'Its panes close across tabs. Switching tabs keeps it running.',
style: DesktopChrome.text(size: 13, color: DesktopChrome.muted),
),
if (_stopping) ...[
diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dart
index 97717057a..fe26f6595 100644
--- a/desktop/lib/widgets/harness_session_manager.dart
+++ b/desktop/lib/widgets/harness_session_manager.dart
@@ -9,6 +9,8 @@ import '../shared/theme/app_theme.dart';
import '../shared/widgets/app_menu.dart';
import '../state/app_state.dart';
import '../state/harness_sessions.dart';
+import '../state/harness_monitor.dart';
+import '../core/harness_resources.dart';
import '../state/swarm_navigation.dart';
import '../core/models.dart';
import '../usage/ledger/usage_overview.dart' show formatTokens;
@@ -27,6 +29,7 @@ class HarnessSessionManager extends StatefulWidget {
required this.onOpen,
this.initialFilter = SessionFilter.all,
this.introduction,
+ this.monitor,
});
final AppNotifier app;
final List<String> recent;
@@ -34,6 +37,7 @@ class HarnessSessionManager extends StatefulWidget {
final Future<bool> Function(HarnessSession) onOpen;
final SessionFilter initialFilter;
final Widget? introduction;
+ final HarnessMonitor? monitor;
@override
State<HarnessSessionManager> createState() => _HarnessSessionManagerState();
@@ -60,6 +64,7 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
_filter = widget.initialFilter;
_clock = Timer.periodic(const Duration(minutes: 1), (_) => _changed());
widget.app.addListener(_changed);
+ widget.monitor?.addListener(_changed);
// Its own notifier — marking one agent must not rebuild the workspace — so
// this list asks for its own redraw while it is open.
widget.app.agentUnread.addListener(_changed);
@@ -72,6 +77,7 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
@override
void dispose() {
widget.app.removeListener(_changed);
+ widget.monitor?.removeListener(_changed);
widget.app.agentUnread.removeListener(_changed);
_clock?.cancel();
_search.dispose();
@@ -81,7 +87,10 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
}
List<HarnessSession> get _sessions {
- final rows = {for (final row in harnessSessions(widget.app)) row.id: row};
+ final rows = {
+ for (final row in widget.monitor?.sessions ?? harnessSessions(widget.app))
+ row.id: row,
+ };
// Keep the row steady while a confirmed pause refreshes the saved roster.
for (final row in _pending.values) {
rows.putIfAbsent(row.id, () => row);
@@ -113,6 +122,23 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
row.machineId,
row.agent.id,
)).error;
+ } else if (row.agent.closePlanState != null) {
+ final result = await widget.app.prepareSessionClose(
+ row.machineId,
+ row.agent,
+ )('cancel');
+ if (result['cancelled'] != true) {
+ error =
+ result['detail'] as String? ??
+ 'Could not cancel the scheduled close.';
+ }
+ } else if (row.agent.closeSupported) {
+ final review = widget.app.reviewSessionClose;
+ if (review == null) {
+ error = 'Open this session to close it safely.';
+ } else {
+ await review([(row.machineId, row.agent)]);
+ }
} else {
error = await widget.app.pauseAgent(row.machineId, row.agent.id);
}
@@ -150,6 +176,22 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
_errors.remove(row.id);
});
try {
+ if (row.agent.closePlanState != null) {
+ final result = await widget.app.prepareSessionClose(
+ row.machineId,
+ row.agent,
+ )('cancel');
+ if (result['cancelled'] != true) {
+ if (mounted) {
+ setState(
+ () => _errors[row.id] =
+ result['detail'] as String? ??
+ 'Could not keep this session open. Try again.',
+ );
+ }
+ return;
+ }
+ }
final opened = await widget.onOpen(row);
if (mounted && opened) widget.onClose();
} on SwarmResumeFailure catch (failure) {
@@ -175,6 +217,14 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
filter: _filter,
sort: _sort,
recent: widget.recent,
+ memory: {
+ for (final row in all)
+ row.id: ?widget.monitor?.reading(row)?.memoryBytes,
+ },
+ cpu: {
+ for (final row in all)
+ row.id: ?widget.monitor?.reading(row)?.cpuPercent,
+ },
);
final running = all.where((row) => row.running).length;
final paused = all.where((row) => row.agent.isStopped).length;
@@ -206,6 +256,9 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
double heightFor(HarnessSession row) =>
rowHeight +
(row.agent.hasMonitorStats
+ ? (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() + 6
+ : 0) +
+ (widget.monitor != null
? (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() + 6
: 0);
return FocusScope(
@@ -278,10 +331,23 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
mainAxisSize: MainAxisSize.min,
children: [
DesktopDialogHeader(
- title: 'Harnesses',
+ title: widget.monitor == null
+ ? 'Harnesses'
+ : 'Harness Monitor',
onClose: widget.onClose,
),
if (widget.introduction != null) widget.introduction!,
+ if (widget.monitor?.sharedLabel case final String shared)
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppDesktop.panelPadding,
+ vertical: 6,
+ ),
+ child: Tooltip(
+ message: 'Included once in the total. May also serve sessions outside Harness. Per-session readings exclude these shared servers.',
+ child: Text(shared, style: AppType.body(), maxLines: 2),
+ ),
+ ),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppDesktop.panelPadding,
@@ -373,7 +439,7 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
'Needs input $needsInput',
SessionFilter.running =>
'Running $running',
- SessionFilter.paused => 'Paused $paused',
+ SessionFilter.paused => 'Saved $paused',
},
),
),
@@ -387,7 +453,12 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
onOpen: () => setState(() {}),
onClose: () => setState(() {}),
menuChildren: [
- for (final sort in SessionSort.values)
+ for (final sort in SessionSort.values.where(
+ (sort) =>
+ widget.monitor != null ||
+ (sort != SessionSort.memory &&
+ sort != SessionSort.cpu),
+ ))
AppMenuItem(
label: sort.label,
selected: _sort == sort,
@@ -493,6 +564,9 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
() => GlobalKey(),
),
row: row,
+ resourceLabel: widget.monitor == null
+ ? null
+ : '${row.status} · ${widget.monitor!.reading(row)?.label ?? const HarnessResources().label}',
height: heightFor(row),
now: now,
showQuestion: showingQuestions,
@@ -518,8 +592,12 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
? 'Pausing…'
: row.agent.isStopped
? 'Resuming…'
+ : row.agent.closeSupported
+ ? 'Closing…'
: 'Pausing…',
- error: _errors[row.id],
+ error:
+ _errors[row.id] ??
+ row.agent.closePlanDetail,
onOpen: () =>
_open(row, answering: row.needsInput),
onAnswer: () => _open(row, answering: true),
@@ -554,6 +632,7 @@ class _SessionRow extends StatelessWidget {
required this.onToggle,
required this.onAnswer,
this.error,
+ this.resourceLabel,
});
final HarnessSession row;
final double height;
@@ -567,6 +646,7 @@ class _SessionRow extends StatelessWidget {
final VoidCallback onOpen, onSelect, onToggle, onAnswer;
final String? error;
+ final String? resourceLabel;
@override
Widget build(BuildContext context) {
@@ -604,7 +684,7 @@ class _SessionRow extends StatelessWidget {
row.agent.launchState == 'starting'));
// Play/pause carries normal state; only exceptions need another label.
final attention = switch (row.status) {
- 'Ready' || 'Paused' || 'Working' || 'Needs input' => null,
+ 'Ready' || 'Saved' || 'Working' || 'Needs input' => null,
final status => status,
};
// The time the panel sorts by (Recently used), so the ages read in order.
@@ -680,6 +760,7 @@ class _SessionRow extends StatelessWidget {
row.project?.shownBranch,
row.question?.prompt,
activity,
+ resourceLabel,
if (row.agent.tokensUsed case final count?)
'$count tokens used',
if (row.agent.outputStats case final stats?) ...[
@@ -801,6 +882,24 @@ class _SessionRow extends StatelessWidget {
);
},
),
+ if (resourceLabel != null) ...[
+ const SizedBox(height: 6),
+ Tooltip(
+ message: HarnessResources.explanation,
+ child: Text(
+ resourceLabel!,
+ key: ValueKey(
+ 'session-resources:${row.id}',
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.caption(
+ color: secondary,
+ height: 1.35,
+ ),
+ ),
+ ),
+ ],
if (row.agent.hasMonitorStats) ...[
const SizedBox(height: 6),
_MonitorStats(
@@ -928,10 +1027,20 @@ class _SessionRow extends StatelessWidget {
icon: Icon(
row.agent.isStopped
? AppIcons.play
+ : row.agent.closePlanState != null
+ ? AppIcons.play
+ : row.agent.closeSupported
+ ? AppIcons.close
: AppIcons.pause,
size: 20,
semanticLabel:
- '${row.agent.isStopped ? 'Resume' : 'Pause'} ${row.agent.displayName}',
+ '${row.agent.isStopped
+ ? 'Resume'
+ : row.agent.closePlanState != null
+ ? 'Keep running'
+ : row.agent.closeSupported
+ ? 'Close'
+ : 'Pause'} ${row.agent.displayName}',
),
padding: const EdgeInsets.all(6),
style: actionStyle(primary),
@@ -1065,6 +1174,10 @@ class _MonitorStats extends StatelessWidget {
/// three things can come back: the same shell, the same conversation, or the
/// harness with a new one (`resumeMode` on the agent frame).
String _toggleLabel(HarnessSession row) {
+ if (!row.agent.isStopped && row.agent.closePlanState != null) {
+ return 'Keep running';
+ }
+ if (!row.agent.isStopped && row.agent.closeSupported) return 'Close session';
if (isTerminalEngine(row.agent.engine)) {
return row.agent.isStopped
? 'Open a fresh shell here'
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 675fdb350..6931e6e3d 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -1368,7 +1368,7 @@ class _PaneContent extends StatelessWidget {
TerminalFontScope.watch(context);
final machine = notifier.stateOf(pane.machineId);
void close() {
- notifier.closePane(pane.id);
+ notifier.requestClosePane(pane.id);
}
VoidCallback? split(PaneResizeAxis axis) =>
diff --git a/desktop/lib/widgets/session_close_dialog.dart b/desktop/lib/widgets/session_close_dialog.dart
new file mode 100644
index 000000000..cd7e678ac
--- /dev/null
+++ b/desktop/lib/widgets/session_close_dialog.dart
@@ -0,0 +1,137 @@
+import 'package:flutter/material.dart';
+
+import '../core/models.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
+import 'terminal_prompt.dart';
+
+/// A close decision names its consequence. Cancel is the default, never Stop.
+Future<String?> showSessionCloseDialog(
+ BuildContext context,
+ Agent agent,
+ String activity, {
+ AppKeymap? keymap,
+ String? error,
+}) => showTerminalPrompt<String>(
+ context,
+ keymap: keymap,
+ builder: (_) =>
+ _SessionClosePrompt(agent: agent, activity: activity, error: error),
+);
+
+class _SessionClosePrompt extends StatefulWidget {
+ const _SessionClosePrompt({
+ required this.agent,
+ required this.activity,
+ this.error,
+ });
+ final Agent agent;
+ final String activity;
+ final String? error;
+ @override
+ State<_SessionClosePrompt> createState() => _SessionClosePromptState();
+}
+
+class _SessionClosePromptState extends State<_SessionClosePrompt> {
+ final _cancel = FocusNode(debugLabel: 'Cancel session close');
+ final _keys = FocusNode(debugLabel: 'Session close');
+ final _scroll = ScrollController();
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _cancel.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ _cancel.dispose();
+ _keys.dispose();
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ void _choose([String? choice]) => Navigator.pop(context, choice);
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final hasConversation =
+ widget.agent.sessionId?.isNotEmpty == true &&
+ widget.agent.resumeMode != 'fresh' &&
+ widget.agent.resumeMode != 'shell';
+ final description = switch (widget.activity) {
+ 'working' => 'This session is still working. Stop now, or let it finish in the background and close afterward.',
+ 'needs_input' => 'This session is waiting for input. If you close after finishing, it stays available in Harness Monitor until you answer and its work finishes.',
+ 'draft' => 'There is unsent text in this session. Stop now saves a terminal snapshot without sending it. Your saved conversation is kept.',
+ 'in_use' => 'This session is open in another window or device. Stopping it ends the running session there too. Switching tabs keeps it running.',
+ _ => 'Harness could not confirm that this session is idle. You can stop it now, or keep it running until its work finishes.',
+ };
+ return TerminalPromptKeys(
+ focusNode: _keys,
+ cancel: _choose,
+ child: DesktopPromptSurface(
+ body: DesktopPromptScrollBody(
+ controller: _scroll,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ widget.error == null
+ ? 'Close session'
+ : 'Could not close session',
+ style: DesktopChrome.heading(),
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ widget.agent.displayName,
+ style: DesktopChrome.text(size: 14, medium: true),
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ widget.error ?? description,
+ style: DesktopChrome.text(size: 13),
+ ),
+ if (widget.error == null) ...[
+ const SizedBox(height: 8),
+ Text(
+ hasConversation
+ ? 'Saved history stays on disk. Reopen it from Open Harness or Harness Monitor.'
+ : 'This session has not saved a conversation yet. A terminal snapshot is kept; reopening starts a new conversation.',
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ focusNode: _cancel,
+ onPressed: _choose,
+ child: Text(widget.error == null ? 'Cancel' : 'OK'),
+ ),
+ if (widget.error == null) ...[
+ FilledButton(
+ key: const Key('session-close-now'),
+ style: grid.dangerButtonStyle(),
+ onPressed: () => _choose('now'),
+ child: const Text('Stop now'),
+ ),
+ if (hasConversation)
+ FilledButton(
+ key: const Key('session-close-after'),
+ onPressed: () => _choose('after_task'),
+ child: const Text('Stop after finishing'),
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 4bf79556a..2b726bdc4 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -1756,6 +1756,7 @@ private final class SwarmTabStrip: NSView {
fileprivate let newButton = SwarmPlainIconButton()
fileprivate let contextButton = SwarmContextButton()
fileprivate let subscriptionUsageButton = SwarmContextButton()
+ fileprivate let harnessMonitorButton = SwarmContextButton()
private var subscriptionUsageState: [String: Any]?
fileprivate let pullRequestButton = SwarmContextButton()
fileprivate let shareButton = SwarmShareButton()
@@ -1824,6 +1825,13 @@ private final class SwarmTabStrip: NSView {
subscriptionUsageButton.setAccessibilityLabel("Remaining subscription usage")
subscriptionUsageButton.isHidden = true
statusBar.addSubview(subscriptionUsageButton)
+ harnessMonitorButton.isBordered = false
+ harnessMonitorButton.textAlignment = .center
+ harnessMonitorButton.target = self
+ harnessMonitorButton.action = #selector(openHarnessMonitor)
+ harnessMonitorButton.setAccessibilityLabel("Harness Monitor")
+ harnessMonitorButton.isHidden = true
+ statusBar.addSubview(harnessMonitorButton)
pullRequestButton.isBordered = false
pullRequestButton.target = self
pullRequestButton.action = #selector(openFocusedPullRequest)
@@ -1888,7 +1896,7 @@ private final class SwarmTabStrip: NSView {
statusBar.setAccessibilityLabel("Focused pane status")
statusBar.setAccessibilityParent(self)
setAccessibilityChildren([scroll, newButton, searchButton, storeButton, statusBar])
- statusBar.setAccessibilityChildren([subscriptionUsageButton, daemonButton, shareButton, voiceLabel, contextButton, pullRequestButton])
+ statusBar.setAccessibilityChildren([harnessMonitorButton, subscriptionUsageButton, daemonButton, shareButton, voiceLabel, contextButton, pullRequestButton])
registerForDraggedTypes([swarmPasteboardType])
scroll.contentView.postsBoundsChangedNotifications = true
for name in [NSApplication.didBecomeActiveNotification, NSApplication.didResignActiveNotification,
@@ -2036,6 +2044,11 @@ private final class SwarmTabStrip: NSView {
subscriptionUsageState = state["subscriptionUsage"] as? [String: Any]
subscriptionUsageButton.update(subscriptionUsageState, enabled: actionsEnabled)
hasSubscriptionUsage = subscriptionUsageState != nil
+ harnessMonitorButton.font = barFont
+ harnessMonitorButton.foreground = terminalForeground
+ harnessMonitorButton.contentPadding = ("m" as NSString).size(withAttributes: [.font: barFont]).width
+ harnessMonitorButton.update(state["harnessMonitor"] as? [String: Any], enabled: actionsEnabled)
+ harnessMonitorButton.isHidden = state["harnessMonitor"] == nil
contextButton.font = barFont
contextButton.foreground = terminalForeground
contextButton.update(state["focusedContext"] as? [String: Any], enabled: actionsEnabled)
@@ -2274,8 +2287,12 @@ private final class SwarmTabStrip: NSView {
let daemonWidth = daemonButton.isHidden ? 0 : min(daemonButton.preferredWidth, available * 0.5)
let shareWidth = shareButton.isHidden ? 0 : min(shareButton.preferredWidth, available * 0.3)
let usageBudget = max(0, available - daemonWidth - shareWidth - cell * 4)
- let usageWidth = hasSubscriptionUsage ? min(subscriptionUsageButton.preferredWidth, usageBudget * 0.45) : 0
- subscriptionUsageButton.frame = NSRect(x: cell,
+ let monitorWidth = harnessMonitorButton.isHidden ? 0 : min(harnessMonitorButton.preferredWidth, usageBudget * 0.55)
+ harnessMonitorButton.frame = NSRect(x: cell, y: y, width: monitorWidth, height: height)
+ let usageWidth = hasSubscriptionUsage && (monitorWidth == 0 || statusBar.bounds.width >= 1050)
+ ? min(subscriptionUsageButton.preferredWidth, usageBudget * (monitorWidth == 0 ? 0.45 : 0.22)) : 0
+ subscriptionUsageButton.isHidden = usageWidth == 0
+ subscriptionUsageButton.frame = NSRect(x: cell + monitorWidth,
y: y, width: usageWidth, height: height)
let daemonLeft = subscriptionUsageButton.frame.maxX + (usageWidth > 0 ? cell * 2 : 0)
daemonButton.frame = NSRect(x: daemonLeft, y: y, width: daemonWidth, height: height)
@@ -2299,6 +2316,7 @@ private final class SwarmTabStrip: NSView {
contextButton.layoutSubtreeIfNeeded()
pullRequestButton.layoutSubtreeIfNeeded()
subscriptionUsageButton.layoutSubtreeIfNeeded()
+ harnessMonitorButton.layoutSubtreeIfNeeded()
}
override func draw(_ dirtyRect: NSRect) {
// A fine rule joins the active tab's outward shoulders to the workspace.
@@ -2330,6 +2348,10 @@ private final class SwarmTabStrip: NSView {
guard actionsEnabled, subscriptionUsageButton.isEnabled else { return }
emit?("subscriptions", nil)
}
+ @objc private func openHarnessMonitor() {
+ guard actionsEnabled, harnessMonitorButton.isEnabled else { return }
+ emit?("resourceMonitor", nil)
+ }
@objc private func openDaemon() {
setDaemonHover(false)
if actionsEnabled && daemonButton.isEnabled { emit?("daemon", nil) }
diff --git a/desktop/test/desktop_welcome_composer_test.dart b/desktop/test/desktop_welcome_composer_test.dart
index 4cfa9b9e3..d96946edc 100644
--- a/desktop/test/desktop_welcome_composer_test.dart
+++ b/desktop/test/desktop_welcome_composer_test.dart
@@ -163,7 +163,11 @@ void main() {
await setup(tester);
expect(tester.widget<NewHarnessForm>(form).embedded, isTrue);
expect(find.byKey(const ValueKey('welcome-sessions')), findsNothing);
- expect(find.byKey(const ValueKey('workspace-status-bar')), findsNothing);
+ // An empty tab still exposes live sessions running elsewhere in the account.
+ expect(
+ find.byKey(const ValueKey('workspace-harness-monitor')),
+ findsOneWidget,
+ );
expect(find.byKey(const ValueKey('new-harness-close')), findsNothing);
expect(find.byKey(const ValueKey('new-harness-dismiss')), findsNothing);
expect(tester.widget<TextField>(task).focusNode!.hasFocus, isTrue);
@@ -416,7 +420,9 @@ void main() {
);
expect(connection.starts, isEmpty);
if (scale == 1) {
- app.machineStates['m']!.agents = [];
+ for (final machine in app.machineStates.values) {
+ machine.agents = [];
+ }
await tester.pumpWidget(const SizedBox());
await tester.pumpWidget(preview);
await tester.pumpAndSettle();
@@ -433,11 +439,17 @@ void main() {
}
testWidgets(
- 'native footer stays hidden on an empty tab and returns with work',
+ 'native footer exposes live sessions on an empty tab and hides with no work',
(tester) async {
await setup(tester, mac: true);
+ expect(updates.last['footerCovered'], isFalse);
+ expect(updates.last['harnessMonitor']['text'], startsWith('2 live'));
+ for (final machine in app.machineStates.values) {
+ machine.agents = [];
+ }
+ app.notifyListeners();
+ await tester.pumpAndSettle();
expect(updates.last['footerCovered'], isTrue);
- expect(find.byKey(const ValueKey('workspace-status-bar')), findsNothing);
app.adoptSessionForTest(terminal('a0', []));
app.notifyListeners();
await tester.pumpAndSettle();
diff --git a/desktop/test/harness_resources_test.dart b/desktop/test/harness_resources_test.dart
new file mode 100644
index 000000000..c8d50eebe
--- /dev/null
+++ b/desktop/test/harness_resources_test.dart
@@ -0,0 +1,281 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/harness_resources.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/harness_monitor.dart';
+import 'package:harness/state/app_state.dart' show MachineState;
+import 'package:harness/widgets/harness_session_manager.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final calls = <Map<String, dynamic>>[];
+ Completer<Map<String, dynamic>>? pending;
+ Map<String, dynamic> reply = {
+ 'harnesses': {
+ 'sampledAt': '2026-09-30T12:00:00Z',
+ 'agents': [
+ {
+ 'agentId': 'a0',
+ 'memoryBytes': 1400000000,
+ 'cpuPercent': 125.5,
+ 'processCount': 3,
+ },
+ ],
+ },
+ };
+ @override
+ bool get isReady => true;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ calls.add({'type': type, ...payload});
+ return pending?.future ?? reply;
+ }
+}
+
+void main() {
+ test('readings preserve unknown, zero, and multi-core CPU without guessing GPU or disk', () {
+ final empty = HarnessResources.fromJson({});
+ expect(empty.memoryBytes, isNull);
+ expect(empty.cpuPercent, isNull);
+ expect(
+ HarnessResources.fromJson({'cpuPercent': 125, 'memoryBytes': 0})
+ .cpuPercent,
+ 125,
+ );
+ expect(formatHarnessMemory(0), '0 MB');
+ expect(formatHarnessMemory(1400000000), '1.4 GB');
+ for (final invalid in [-1, double.nan, double.infinity, '100']) {
+ expect(
+ HarnessResources.fromJson({
+ 'cpuPercent': invalid,
+ 'memoryBytes': invalid,
+ }).memoryBytes,
+ isNull,
+ );
+ expect(
+ HarnessResources.fromJson({'cpuPercent': invalid}).cpuPercent,
+ isNull,
+ );
+ }
+ expect(MachineHarnessResources.parse({}), isNull);
+ expect(
+ MachineHarnessResources.parse({'sampledAt': 'bad', 'agents': []}),
+ isNull,
+ );
+ });
+
+ test('shared-server resources contribute once to totals and disappear with their last live session', () async {
+ final connection = _Connection();
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ final monitor = HarnessMonitor(app);
+ addTearDown(monitor.dispose);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ const Agent(id: 'a0', name: 'Work', terminalAvailable: true),
+ ];
+ (connection.reply['harnesses'] as Map)['shared'] = [
+ {
+ 'kind': 'codex',
+ 'agentIds': ['a0', 'another-session'],
+ 'memoryBytes': 600000000,
+ 'cpuPercent': 4.5,
+ 'processCount': 2,
+ },
+ ];
+ await monitor.refresh();
+ expect(monitor.label, '1 live · 2.0 GB · 130% CPU');
+ expect(monitor.sharedLabel, 'Shared Codex servers · 600 MB RAM');
+ expect(monitor.detail, contains('included once'));
+ ((connection.reply['harnesses'] as Map)['shared'] as List).first.remove(
+ 'memoryBytes',
+ );
+ await monitor.refresh();
+ expect(monitor.sharedLabel, 'Shared Codex servers · — RAM');
+ expect(monitor.label, '1 live · 1.4 GB+ · 130% CPU');
+ app.machineStates['m']!.agents = [];
+ expect(monitor.label, '0 live');
+ expect(monitor.sharedLabel, isNull);
+ });
+
+ testWidgets(
+ 'uses one machine request for every session; tokens are existing data',
+ (tester) async {
+ final connection = _Connection();
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ final monitor = HarnessMonitor(app);
+ addTearDown(monitor.dispose);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Known work',
+ terminalAvailable: true,
+ tokensUsed: 9200,
+ ),
+ const Agent(
+ id: 'hidden',
+ name: 'Background work',
+ terminalAvailable: true,
+ ),
+ ];
+ expect(connection.calls, isEmpty);
+ expect(
+ monitor.live.length,
+ 2,
+ ); // Inventory appears without starting or opening anything.
+ await monitor.refresh();
+ expect(connection.calls, [
+ {'type': 'machine_resources', 'harnesses': true},
+ ]);
+ expect(monitor.label, '2 live · 1.4 GB+ · 126%+ CPU');
+ expect(monitor.reading(monitor.live.first)!.processCount, 3);
+ expect(app.allPanes, isEmpty);
+ connection.reply = {};
+ await monitor.refresh();
+ expect(monitor.label, '2 live · — · —% CPU');
+ },
+ );
+
+ testWidgets(
+ 'polls slowly in the footer, faster only while open, and never while hidden',
+ (tester) async {
+ final connection = _Connection();
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ final monitor = HarnessMonitor(app);
+ app.machineStates['m']!.agents = [
+ const Agent(id: 'a0', name: 'Work', terminalAvailable: true),
+ ];
+ monitor.start();
+ await tester.pump();
+ expect(connection.calls, hasLength(1));
+ await tester.pump(const Duration(seconds: 14));
+ expect(connection.calls, hasLength(1));
+ await tester.pump(const Duration(seconds: 1));
+ expect(connection.calls, hasLength(2));
+ monitor.setExpanded(true);
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 3));
+ expect(connection.calls, hasLength(4));
+ app.appLifecycleChanged(AppLifecycleState.hidden);
+ await tester.pump(const Duration(minutes: 2));
+ expect(connection.calls, hasLength(4));
+ app.appLifecycleChanged(AppLifecycleState.resumed);
+ await tester.pump();
+ expect(connection.calls, hasLength(5));
+ monitor.dispose();
+ await tester.pump(const Duration(minutes: 2));
+ expect(connection.calls, hasLength(5));
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'late readings cannot populate a replacement or disconnected machine',
+ (tester) async {
+ final connection = _Connection()..pending = Completer();
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ final monitor = HarnessMonitor(app);
+ addTearDown(monitor.dispose);
+ addTearDown(app.dispose);
+ final original = app.machineStates['m']!;
+ original.agents = [
+ const Agent(id: 'a0', name: 'Old', terminalAvailable: true),
+ ];
+ final pending = monitor.refresh();
+ app.machineStates['m'] = MachineState(original.machine)
+ ..connectionStatus = ConnectionStatus.connected
+ ..agents = [
+ const Agent(id: 'a0', name: 'New', terminalAvailable: true),
+ ];
+ connection.pending!.complete(connection.reply);
+ await pending;
+ expect(monitor.label, '1 live · — · —% CPU');
+ app.machineStates['m']!.connectionStatus = ConnectionStatus.disconnected;
+ final before = connection.calls.length;
+ await monitor.refresh();
+ expect(connection.calls.length, before);
+ expect(monitor.label, '0 live');
+ },
+ );
+
+ testWidgets(
+ 'compact monitor shows status, RAM, CPU and cached tokens at enlarged text',
+ (tester) async {
+ final connection = _Connection();
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ final monitor = HarnessMonitor(app);
+ addTearDown(monitor.dispose);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Review',
+ engine: 'codex',
+ terminalAvailable: true,
+ tokensUsed: 9200,
+ ),
+ ];
+ await monitor.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: MediaQuery(
+ data: const MediaQueryData(textScaler: TextScaler.linear(1.4)),
+ child: Scaffold(
+ body: SizedBox(
+ width: 500,
+ height: 600,
+ child: HarnessSessionManager(
+ app: app,
+ monitor: monitor,
+ recent: const [],
+ onClose: () {},
+ onOpen: (_) async => true,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(find.text('Harness Monitor'), findsOneWidget);
+ expect(find.textContaining('1.4 GB RAM'), findsOneWidget);
+ expect(find.textContaining('125.5% CPU'), findsOneWidget);
+ expect(find.textContaining('tokens'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+}
diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dart
index 74da227a4..5cd2780f0 100644
--- a/desktop/test/harness_session_manager_test.dart
+++ b/desktop/test/harness_session_manager_test.dart
@@ -471,11 +471,11 @@ void main() {
(tester) async {
await open(tester);
expect(find.byType(HarnessSessionManager), findsOneWidget);
- expect(find.text('Harnesses'), findsOneWidget);
+ expect(find.text('Harness Monitor'), findsOneWidget);
expect(find.text('Running 1'), findsOneWidget);
- expect(find.text('Paused 1'), findsOneWidget);
+ expect(find.text('Saved 1'), findsOneWidget);
expect(find.text('Ready'), findsNothing);
- expect(find.text('Paused'), findsNothing);
+ expect(find.text('Saved'), findsNothing);
expect(find.textContaining('Pause keeps'), findsNothing);
expect(
tester
@@ -547,7 +547,7 @@ void main() {
await tester.pumpAndSettle();
expect(app.stateOf('m')!.agents.first.isStopped, isTrue);
expect(find.text('Running 0'), findsOneWidget);
- expect(find.text('Paused 2'), findsOneWidget);
+ expect(find.text('Saved 2'), findsOneWidget);
await tester.tap(toggle('a0'));
await tester.pump();
expect(connection.types, ['agent_resume']);
@@ -619,7 +619,7 @@ void main() {
connection.inventory!.completeError(StateError('refresh failed'));
await tester.pumpAndSettle();
expect(find.text(_running.name), findsOneWidget);
- expect(find.text('Paused 2'), findsOneWidget);
+ expect(find.text('Saved 2'), findsOneWidget);
expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNotNull);
expect(connection.stops, ['a0']);
},
@@ -674,8 +674,8 @@ void main() {
await tester.pumpAndSettle();
expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
// Paused, not "Resume unavailable": it can come back.
- expect(harnessSessions(app).single.status, 'Paused');
- expect(find.text('Paused 1'), findsOneWidget);
+ expect(harnessSessions(app).single.status, 'Saved');
+ expect(find.text('Saved 1'), findsOneWidget);
expect(
tester.widget<IconButton>(toggle('shell')).onPressed,
isNotNull,
@@ -1327,6 +1327,8 @@ void main() {
'engine': agent.engine,
'sessionId': agent.sessionId,
'status': agent.status,
+ 'closeSupported': true,
+ 'createdAt': now.toIso8601String(),
'terminal': {'available': agent.terminalAvailable},
'project': {
'name': agent.project?.name,
diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dart
new file mode 100644
index 000000000..290e44233
--- /dev/null
+++ b/desktop/test/session_close_test.dart
@@ -0,0 +1,231 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+class _CloseConnection extends WsConn {
+ _CloseConnection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ late AppNotifier app;
+ final closes = <Map<String, dynamic>>[];
+ final activities = <String, String>{};
+ Completer<Map<String, dynamic>>? inspecting;
+ Map<String, dynamic>? failure;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type != 'agent_close') return {};
+ closes.add(Map.of(payload));
+ final mode = payload['mode'];
+ if (mode == 'inspect') {
+ return inspecting?.future ??
+ Future.value({'activity': activities[payload['agentId']] ?? 'idle'});
+ }
+ if (failure != null) return failure!;
+ if (mode == 'after_task') return {'deferred': true};
+ if (mode == 'cancel') return {'cancelled': true};
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': payload['agentId']},
+ });
+ return {'closed': true};
+ }
+}
+
+void main() {
+ late AppNotifier app;
+ late _CloseConnection connection;
+ Agent agent(String id) => Agent(
+ id: id,
+ name: 'Work $id',
+ engine: 'codex',
+ sessionId: 'conversation-$id',
+ createdAt: DateTime.utc(2026, 9, 30, 12),
+ closeSupported: true,
+ terminalAvailable: true,
+ resumeMode: 'conversation',
+ );
+ setUp(() {
+ connection = _CloseConnection();
+ app = createApp(connected: true, connectionForTest: (_) => connection);
+ connection.app = app;
+ app.stateOf('m')!.agents = [agent('a0'), agent('a1')];
+ });
+ tearDown(() => app.dispose());
+ List<Object?> modes() => connection.closes.map((r) => r['mode']).toList();
+
+ test(
+ 'without a close presenter an unsupported decision keeps its pane intact',
+ () async {
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await app.requestClosePane(pane.id);
+ expect(app.panes, [pane]);
+ expect(connection.closes, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'idle Close saves the recently closed layout despite an early deleted event',
+ (tester) async {
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ unawaited(app.requestClosePane(pane.id));
+ await tester.pumpAndSettle();
+ expect(modes(), ['inspect', 'idle']);
+ expect(app.allPanes, isEmpty);
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,
+ isTrue,
+ );
+ expect(app.closedHistory, hasLength(1));
+ expect(app.canReopenLastClosed, isTrue);
+ expect(find.text('Close session'), findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'working Close starts with Cancel focused and Enter keeps work alive',
+ (tester) async {
+ connection.activities['a0'] = 'working';
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ unawaited(app.requestClosePane(pane.id));
+ await tester.pumpAndSettle();
+ expect(find.text('Stop now'), findsOneWidget);
+ expect(find.text('Stop after finishing'), findsOneWidget);
+ expect(
+ tester
+ .widget<TextButton>(find.widgetWithText(TextButton, 'Cancel'))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.panes, [pane]);
+ expect(modes(), ['inspect']);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final choice in ['now', 'after']) {
+ testWidgets('working Close $choice sends only the reviewed action', (
+ tester,
+ ) async {
+ connection.activities['a0'] = 'working';
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ unawaited(app.requestClosePane(pane.id));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(Key('session-close-$choice')));
+ await tester.pumpAndSettle();
+ expect(modes(), ['inspect', choice == 'now' ? 'now' : 'after_task']);
+ expect(app.allPanes, isEmpty);
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,
+ choice == 'now',
+ );
+ expect(app.closedHistory, hasLength(1));
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
+ testWidgets('a failed disk checkpoint leaves the pane and explains why', (
+ tester,
+ ) async {
+ connection.failure = {
+ 'error': 'HISTORY_NOT_SAVED',
+ 'detail': 'Not enough free disk space.',
+ };
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ unawaited(app.requestClosePane(pane.id));
+ await tester.pumpAndSettle();
+ expect(find.text('Not enough free disk space.'), findsOneWidget);
+ await tester.tap(find.text('OK'));
+ await tester.pumpAndSettle();
+ expect(app.panes, [pane]);
+ expect(app.closedHistory, isEmpty);
+ expect(modes(), ['inspect', 'idle']);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'a tab switch during an idle check cannot close the newly selected tab',
+ (tester) async {
+ final first = app.adoptSessionForTest(terminal('a0', []));
+ final original = app.activeSwarm;
+ connection.inspecting = Completer();
+ await mount(tester, app);
+ final closing = app.requestClosePane(first.id);
+ await tester.pump();
+ app.newSwarm();
+ final next = app.activeSwarm;
+ final second = app.adoptSessionForTest(terminal('a1', []));
+ connection.inspecting!.complete({'activity': 'idle'});
+ await tester.pumpAndSettle();
+ await closing;
+ expect(app.activeSwarm, same(next));
+ expect(app.panes, [second]);
+ expect(app.swarms, isNot(contains(original)));
+ expect(connection.closes.every((r) => r['agentId'] == 'a0'), isTrue);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('another hidden tab showing the same session keeps it live', (
+ tester,
+ ) async {
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final original = app.activeSwarm;
+ app.newSwarm();
+ app.activeSwarm.panes.add(pane);
+ app.activeSwarm.focusedPaneId = pane.id;
+ await mount(tester, app);
+ await app.requestClosePane(pane.id);
+ await tester.pumpAndSettle();
+ expect(connection.closes, isEmpty);
+ expect(original.panes, [pane]);
+ expect(app.stateOf('m')!.agents.first.terminalAvailable, isTrue);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'Cancel on a later tab member does not stop an earlier approved member',
+ (tester) async {
+ connection.activities.addAll({'a0': 'working', 'a1': 'working'});
+ app.adoptSessionForTest(terminal('a0', []));
+ app.adoptSessionForTest(terminal('a1', []));
+ await mount(tester, app);
+ unawaited(app.requestCloseSwarm(app.activeSwarmId));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('session-close-now')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(app.panes, hasLength(2));
+ expect(modes(), ['inspect', 'inspect']);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+}
diff --git a/desktop/test/stop_keyboard_test.dart b/desktop/test/stop_keyboard_test.dart
index e013b4b08..637c9f44d 100644
--- a/desktop/test/stop_keyboard_test.dart
+++ b/desktop/test/stop_keyboard_test.dart
@@ -90,7 +90,7 @@ void main() {
await open(tester);
expect(find.text('Stop Harness'), findsOneWidget);
expect(
- find.textContaining('Close Pane keeps it running.'),
+ find.textContaining('Switching tabs keeps it running.'),
findsOneWidget,
);
// The default action must leave the agent running.
@@ -231,7 +231,7 @@ void main() {
var i = 0;
i < 12 &&
find
- .textContaining('Close Pane keeps it running.')
+ .textContaining('Switching tabs keeps it running.')
.hitTestable()
.evaluate()
.isEmpty;
@@ -240,7 +240,7 @@ void main() {
await key(tester, LogicalKeyboardKey.pageDown);
}
expect(
- find.textContaining('Close Pane keeps it running.').hitTestable(),
+ find.textContaining('Switching tabs keeps it running.').hitTestable(),
findsOneWidget,
);
for (var i = 0; i < 12 && body.controller!.offset > 0; i++) {
diff --git a/desktop/test/stopped_harness_test.dart b/desktop/test/stopped_harness_test.dart
index f78f58d38..bbdc43432 100644
--- a/desktop/test/stopped_harness_test.dart
+++ b/desktop/test/stopped_harness_test.dart
@@ -166,6 +166,31 @@ void main() {
},
);
+ test('duplicate retained-stop events cannot erase an in-flight saved-history refresh', () async {
+ connection.inventory = Completer<Map<String, dynamic>>();
+ for (var event = 0; event < 2; event++) {
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'a0', 'retained': true},
+ });
+ }
+ connection.inventory!.complete({
+ 'agents': [
+ {
+ 'id': 'a0',
+ 'name': 'Retained work',
+ 'engine': 'codex',
+ 'sessionId': 'original-conversation',
+ 'status': 'stopped',
+ 'terminal': {'available': false},
+ },
+ ],
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
+ expect(swarmDestinations(app).any((row) => row.agentId == 'a0'), isTrue);
+ });
+
for (final placement in HarnessPlacement.values) {
test('Enter resumes directly before opening ${placement.name}', () async {
final target = app.activeSwarmId;
diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dart
index 71ec0cd5f..2fe2caf32 100644
--- a/desktop/test/workspace_status_test.dart
+++ b/desktop/test/workspace_status_test.dart
@@ -513,8 +513,12 @@ void main() {
tester.view.physicalSize = Size(width, 800);
await tester.pump();
expect(tester.takeException(), isNull);
+ expect(usage, findsNothing);
+ final monitor = find.byKey(
+ const ValueKey('workspace-harness-monitor'),
+ );
expect(
- tester.getRect(usage).right,
+ tester.getRect(monitor).right,
lessThan(tester.getRect(context).left),
);
}
@@ -606,6 +610,8 @@ void main() {
expect(app.allPanes, isNot(contains(first)));
expect(second.session!.agentId, 'a1');
await mouse.removePointer();
+ // Closing a tile resizes the remaining terminal through its 50 ms debounce.
+ await tester.pump(const Duration(milliseconds: 60));
await tester.pumpWidget(const SizedBox());
});
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index e4f97a856..d3924bffe 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -1542,7 +1542,7 @@ private extension SwarmTabStrip {
newButton.frame.maxX < searchButton.frame.minX, "Tabs precede the search and Store controls")
try checkTitlebar(tabs[0].frame.width < 136 && tabs[0].displayLabel == "code",
"Overflow tabs keep readable names without persistent number prefixes")
- try checkTitlebar(subviews.count == 4 && statusBar.subviews.count == 6 && pullRequestButton.isHidden && subscriptionUsageButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,
+ try checkTitlebar(subviews.count == 4 && statusBar.subviews.count == 7 && pullRequestButton.isHidden && subscriptionUsageButton.isHidden && harnessMonitorButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,
"Navigation lives in the titlebar and focused context lives in the footer")
let controls = [newButton]
for control in controls {
@@ -2462,6 +2462,7 @@ do {
try strip.checkAgentIdentity()
try strip.checkSharedTypography()
try strip.checkShareAction()
+ try strip.checkHarnessMonitor()
try strip.checkTopActions()
try checkIconTooltipTracking()
try strip.checkActivityMarks()
@@ -2503,3 +2504,36 @@ do {
FileHandle.standardError.write(Data("AppKit Tab titlebar failed: \(message)\n".utf8))
exit(1)
}
+
+private extension SwarmTabStrip {
+ func checkHarnessMonitor() throws {
+ var state: [String: Any] = ["enabled": true,
+ "harnessMonitor": ["text": "10 live · 1.4 GB · 12% CPU", "segments": [["text": "10 live · 1.4 GB · 12% CPU"]], "label": "Harness Monitor", "detail": "RAM includes child processes", "interactive": true],
+ "subscriptionUsage": ["text": "Claude 12% Codex 30%", "interactive": true],
+ "focusedContext": ["text": "Computer > project > branch", "interactive": true],
+ "tabs": [["id": "work", "name": "Work"]], "activeId": "work"]
+ var calls: [String] = []
+ emit = { method, _ in calls.append(method) }
+ for width in [CGFloat(360), CGFloat(520), CGFloat(1280)] {
+ setFrameSize(NSSize(width: width, height: 40))
+ update(state)
+ try checkTitlebar(!harnessMonitorButton.isHidden && harnessMonitorButton.isEnabled &&
+ harnessMonitorButton.frame.minX > 0 && harnessMonitorButton.frame.width > 0 &&
+ harnessMonitorButton.frame.maxX <= contextButton.frame.minX,
+ "Resource monitor stays at bottom left without overlapping context at width \(width)")
+ try checkTitlebar(harnessMonitorButton.accessibilityLabel() == "Harness Monitor",
+ "The resource counter names its action for VoiceOver")
+ try checkTitlebar(subscriptionUsageButton.isHidden == (width < 1050),
+ "Narrow footers retain the monitor while subscriptions remain accessible through Models")
+ }
+ harnessMonitorButton.performClick(nil)
+ try checkTitlebar(calls == ["resourceMonitor"], "The footer opens the session monitor, never a new agent")
+ state["enabled"] = false
+ update(state)
+ harnessMonitorButton.performClick(nil)
+ try checkTitlebar(calls.count == 1, "A covered or modal footer cannot open its monitor")
+ update([:])
+ try checkTitlebar(harnessMonitorButton.isHidden && !harnessMonitorButton.isEnabled,
+ "Clearing workspace state clears the counter and action")
+ }
+}