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.

Close ready unused companion chats without confirmation (#545)

Dee068dfd1e93b7
diff --git a/cli/scripts/resume-native-e2e.ts b/cli/scripts/resume-native-e2e.ts
index 6c8112ad6..1cf6d25a2 100644
--- a/cli/scripts/resume-native-e2e.ts
+++ b/cli/scripts/resume-native-e2e.ts
@@ -167,10 +167,10 @@ try {
for (const line of raw) lineToEvents(line, state)
if (raw.length) turnOpen = state.turnOpen
}
- return inspectCloseActivity(row.engine, screen, turnOpen, false)
+ return inspectCloseActivity(row, 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,
+ checkpoint: async (row, phase) => sessionCheckpoints.save(row, {
+ 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 } })) },
})
@@ -344,7 +344,7 @@ try {
const { TerminalStreamManager } = await import('../src/lib/terminalStreamManager.js')
const { TerminalBackendCoordinator } = await import('../src/lib/terminalBackendCoordinator.js')
const streams = new TerminalStreamManager({
- terminals: new TerminalBackendCoordinator([backend], ['tmux'], []),
+ terminals: new TerminalBackendCoordinator([backend], ['tmux']),
resolveAgent: id => registry.byAgent(id), streamingAvailable: true,
sendTarget: (id, type, payload) => socketBackend.sendTerminalTo(id, type, payload),
sendBinaryTarget: (id, frame) => socketBackend.sendTerminalBinaryTo(id, frame),
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 4fab5e865..2cf074ad5 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -31,7 +31,12 @@ import { STRICT_DOWN_TYPES, encryptDownFrame, encryptRpcResult } from './lib/e2e
import { CloseAgentService } from './lib/closeAgentService.js'
describe('safe session close RPC', () => {
- it.each(['idle', 'working'] as const)('uses %s activity even with another live viewer', async activity => {
+ it.each([
+ { activity: 'idle', sessionId: 'close-history' },
+ { activity: 'working', sessionId: 'close-history' },
+ { activity: 'idle', sessionId: '' },
+ { activity: 'working', sessionId: '' },
+ ] as const)('uses $activity activity for session "$sessionId" even with another live viewer', async ({ activity, sessionId }) => {
const socket = new BackendSocket('fixture')
const frames: any[] = []
for (const connId of ['local:close', 'local:other']) {
@@ -41,7 +46,7 @@ describe('safe session close RPC', () => {
})
}
const row = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%7302' }], cwd: '/tmp' })!
- row.sessionId = 'close-history'
+ row.sessionId = sessionId
const checkpoint = vi.fn(async () => {})
const stop = vi.fn(async (_agentId, options) => {
await options.checkpoint(row, 'before')
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index b12b3fccc..8c7ccebd4 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -6824,10 +6824,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
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))
+ return inspectCloseActivity(s, 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,
+ checkpoint: async (s, phase) => sessionCheckpoints.save(s, {
+ screen: phase === 'before' ? await captureTerminal(s.agentId, 2000) : null,
}),
stop: stopAgent,
changed: announceSession,
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index 5090af345..2fdf29210 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -1,9 +1,10 @@
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 { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { env } from '../config/env.js'
+import { SessionCheckpointStore } from './sessionCheckpoint.js'
let row: RegisteredSession
let service: CloseAgentService
@@ -139,14 +140,78 @@ it('will not acknowledge a deferred close when durable storage fails', async ()
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')
+ expect(inspectCloseActivity(row, screen, false, false)).toBe('idle')
+ expect(inspectCloseActivity(row, screen, undefined, false)).toBe('unknown')
+ expect(inspectCloseActivity(row, screen, true, false)).toBe('working')
+ expect(inspectCloseActivity(row, screen, false, true)).toBe('needs_input')
+ expect(inspectCloseActivity(row, null, false, false)).toBe('unknown')
+ expect(inspectCloseActivity(row, '› A draft\n 100% context left', false, false)).toBe('draft')
+ expect(inspectCloseActivity(row, `${screen}\n ◎ /goal active (41m)`, false, false)).toBe('working')
+ expect(inspectCloseActivity({ ...row, engine: 'claude' }, '❯\n 2 background tasks', false, false)).toBe('working')
+})
+
+const unusedScreens = {
+ // Prompt/footer styling observed in the unused Companions terminal; path redacted.
+ codex: '\u001b[1m\u001b[38;5;215m›\u001b[0m\u001b[48;5;234m \u001b[2mAsk Codex to do anything\u001b[0m\n\n GPT-6-Astra max · /tmp/companions\n ? for shortcuts · 1 warning · f2 to view',
+ claude: '────────────\n❯\u00a0\u001b[2mAsk about the codebase\u001b[0m\n────────────\n ? for shortcuts',
+}
+
+it.each(['claude', 'codex'] as const)('closes an unused %s chat only after saving its screen', async engine => {
+ Object.assign(row, { engine, sessionId: '', transcriptPath: null, launch: { state: 'ready' } })
+ const screen = unusedScreens[engine]
+ const directory = join(env.ADAPTER_DATA_DIR, 'unused-checkpoints', row.agentId)
+ const store = new SessionCheckpointStore(directory)
+ deps.activity = vi.fn(async () => inspectCloseActivity(row, screen, undefined, false))
+ deps.checkpoint = vi.fn((s, phase) => store.save(s, { screen: phase === 'before' ? screen : null }))
+ deps.stop = vi.fn(async (id, options) => {
+ await options.checkpoint!(row, 'before')
+ await options.beforeStop!(row)
+ const manifest = JSON.parse(readFileSync(join(directory, readdirSync(directory).find(f => /^[a-f0-9]{64}\.json$/.test(f))!), 'utf8'))
+ expect(JSON.parse(readFileSync(join(directory, manifest.file), 'utf8')).screen).toBe(screen)
+ expect(options.current!()).toBe(true)
+ await options.checkpoint!(row, 'after')
+ registry.removeAgent(id)
+ })
+ expect(await service.request(request('inspect'))).toEqual({ activity: 'idle' })
+ expect(await service.request(request('idle'))).toEqual({ closed: true })
+ expect(deps.checkpoint).toHaveBeenNthCalledWith(1, row, 'before')
+ expect(deps.checkpoint).toHaveBeenNthCalledWith(2, row, 'after')
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+})
+
+it.each([
+ [null, 'unknown'],
+ ['Starting Codex…', 'unknown'],
+ ['unrecognized terminal screen', 'unknown'],
+ ['› Keep this draft\n 100% context left', 'draft'],
+ ['›\n a multiline draft\n 100% context left', 'draft'],
+ ['›\nAllow this action', 'needs_input'],
+ ['• Working (4s · esc to interrupt)\n›\n 100% context left', 'working'],
+ [`${unusedScreens.codex}\n ◎ /goal active (41m)`, 'working'],
+] as const)('does not treat an unused chat as idle with %j', (screen, activity) => {
+ Object.assign(row, { sessionId: '', transcriptPath: null })
+ expect(inspectCloseActivity(row, screen, undefined, false)).toBe(activity)
+ expect(inspectCloseActivity(row, unusedScreens.codex, true, false)).toBe('working')
+ expect(inspectCloseActivity(row, unusedScreens.codex, undefined, true)).toBe('needs_input')
+})
+
+it.each([
+ { sessionId: 'existing-conversation' },
+ { transcriptPath: '/tmp/existing-conversation.jsonl' },
+ { resumeOnly: true as const },
+ { launch: { state: 'starting' as const } },
+ { launch: { state: 'failed' as const, error: 'START_FAILED' } },
+ { engine: 'terminal' as const },
+])('retains unknown turn state with %j', change => {
+ const session = { ...row, sessionId: '', transcriptPath: null, ...change }
+ expect(inspectCloseActivity(session, '›\n\n 100% context left', undefined, false)).toBe('unknown')
+})
+
+it.each(['working', 'draft', 'unknown'] as const)('retains an unused chat that becomes %s while saving', async activity => {
+ Object.assign(row, { sessionId: '', transcriptPath: null })
+ vi.mocked(deps.activity).mockResolvedValueOnce('idle').mockResolvedValue(activity)
+ expect(await service.request(request('idle'))).toEqual({ error: 'SESSION_NOT_IDLE', activity })
+ expect(registry.byAgent(row.agentId)).toBe(row)
})
it('automatically stops only after two timer observations of sustained idle', async () => {
@@ -185,9 +250,8 @@ it('rejects a disposed service and a target replaced while reading activity', as
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'
+it('never automatically closes a shell on an empty composer alone', async () => {
+ row.engine = 'terminal'
expect(await service.request(request('idle'))).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'unknown' })
expect(deps.stop).not.toHaveBeenCalled()
})
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index e81d50762..b13851e68 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -20,9 +20,13 @@ export type AgentClosePlan = {
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,
+type CloseSession = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'launch' | 'resumeOnly'>
+
+/** An empty new chat has no turn state yet. Existing chats still require that state,
+ * and neither kind is idle without a recognized empty composer. */
+export function inspectCloseActivity(session: CloseSession, screen: string | null,
turnOpen: boolean | undefined, needsInput: boolean): CloseActivity {
+ const { engine } = session
if (needsInput) return 'needs_input'
if (turnOpen === true) return 'working'
if (!screen) return 'unknown'
@@ -33,7 +37,10 @@ export function inspectCloseActivity(engine: RegisteredSession['engine'], screen
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'
+ const unusedChat = (engine === 'claude' || engine === 'codex')
+ && !session.sessionId && !session.transcriptPath && !session.resumeOnly
+ && (session.launch == null || session.launch.state === 'ready')
+ if (hold || (turnOpen === undefined && !unusedChat)) return 'unknown'
return 'idle'
}
@@ -48,7 +55,7 @@ function matches(s: RegisteredSession | undefined, request: AgentCloseRequest):
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>
+ checkpoint(s: RegisteredSession, phase: 'before' | 'after'): Promise<void>
stop(agentId: string, options: StopAgentOptions): Promise<void>
changed(s: RegisteredSession): void
now?: () => number
@@ -110,7 +117,7 @@ export class CloseAgentService {
const observed = await this.deps.activity(s)
// Close belongs to the global workspace. Other viewers do not change
// whether the session has unfinished work.
- const activity = observed === 'idle' && (!s.sessionId || resumeMode(s.engine) !== 'conversation') ? 'unknown' : observed
+ const activity = observed === 'idle' && resumeMode(s.engine) !== 'conversation' ? 'unknown' : observed
if (!current()) return { error: 'AGENT_CHANGED' }
if (request.mode === 'inspect') return { activity }
if (request.mode === 'after_task') {
@@ -124,7 +131,7 @@ export class CloseAgentService {
if (request.mode === 'idle' && activity !== 'idle') return { error: 'SESSION_NOT_IDLE', activity }
await this.deps.stop(s.agentId, {
current: () => !!current(),
- checkpoint: (s, phase) => this.deps.checkpoint(s, request.mode === 'now', phase),
+ checkpoint: (s, phase) => this.deps.checkpoint(s, phase),
beforeStop: async () => {
const latest = current()
if (!latest) throw new Error('The session changed while saving. Please try again.')
diff --git a/cli/src/lib/sessionCheckpoint.spec.ts b/cli/src/lib/sessionCheckpoint.spec.ts
index 644b254ad..68d160105 100644
--- a/cli/src/lib/sessionCheckpoint.spec.ts
+++ b/cli/src/lib/sessionCheckpoint.spec.ts
@@ -41,13 +41,12 @@ it('preserves a newly typed draft even when native history has not changed', asy
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 => {
+it.each(['terminal', 'claude', 'codex'] as const)('requires 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' })
+ await expect(store.save(row)).rejects.toThrow('Could not save this terminal')
+ await store.save(row, { screen: 'unsent work' })
const before = await manifest()
- await store.save(row, { explicitlyStopped: true })
+ await store.save(row)
expect(await manifest()).toEqual(before)
expect(JSON.parse(await readFile(join(directory, before.file), 'utf8')).screen).toBe('unsent work')
})
@@ -119,9 +118,9 @@ it('rebuilds a missing backup and refuses a missing terminal snapshot', async ()
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' })
+ await store.save(row, { 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')
+ await expect(store.save(row)).rejects.toThrow('Could not save this terminal')
})
it('refuses an unset conversation path instead of inventing an empty checkpoint', async () => {
row.transcriptPath = null
diff --git a/cli/src/lib/sessionCheckpoint.ts b/cli/src/lib/sessionCheckpoint.ts
index cd3456267..e7199da43 100644
--- a/cli/src/lib/sessionCheckpoint.ts
+++ b/cli/src/lib/sessionCheckpoint.ts
@@ -67,8 +67,7 @@ export class SessionCheckpointStore {
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.')
+ async save(s: RegisteredSession, options: { screen?: string | null } = {}): Promise<void> {
secureStateDirectory(dirname(this.directory))
secureStateDirectory(this.directory)
const key = this.key(s)
@@ -91,8 +90,8 @@ export class SessionCheckpointStore {
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.
+ // A shell or unused chat has no native conversation. Save its terminal
+ // instead; the close service owns the activity check and confirmation.
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
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index e8b1df6d7..3c18190a3 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -253,10 +253,12 @@ from `node_status` pushes — distinct from our own socket status, pending offli
Explicit pane/tab Close uses `requestClosePane` / `requestCloseSwarm` and closes the session across
the global workspace. An owned idle session saves its native conversation and terminal snapshot
-before releasing its process, regardless of other viewers. Working, waiting-for-input, draft, or
-unknown sessions show one short sentence with Cancel and Close; there is no title or deferred-close
-button. Cancel is the default. Previously queued daemon close plans remain compatible. Layout
-cleanup, moving panes, switching tabs, and sign-out retain their view-only behavior. A failed save
+before releasing its process, regardless of other viewers. A ready, unused Claude/Codex chat with
+an empty composer also closes directly, saving its terminal snapshot without requiring a native
+conversation. Missing activity evidence for an existing chat remains unknown. Working,
+waiting-for-input, draft, or unknown sessions show one short sentence with Cancel and Close;
+there is no title or deferred-close button. Cancel is the default. Previously queued daemon close
+plans remain compatible. 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
diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dart
index deccdb44a..6854e63e2 100644
--- a/desktop/test/session_close_test.dart
+++ b/desktop/test/session_close_test.dart
@@ -53,11 +53,11 @@ class _CloseConnection extends WsConn {
void main() {
late AppNotifier app;
late _CloseConnection connection;
- Agent agent(String id) => Agent(
+ Agent agent(String id, {bool started = true}) => Agent(
id: id,
name: 'Work $id',
engine: 'codex',
- sessionId: 'conversation-$id',
+ sessionId: started ? 'conversation-$id' : null,
createdAt: DateTime.utc(2026, 9, 30, 12),
closeSupported: true,
terminalAvailable: true,
@@ -131,6 +131,29 @@ void main() {
},
);
+ testWidgets('an unused idle Companions chat closes its whole tab directly', (
+ tester,
+ ) async {
+ app.stateOf('m')!.agents = [agent('a0', started: false)];
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ // Bind the live utility tab after startup's experimental-feature gate.
+ final tab = app.activeSwarm
+ ..kind = 'companions'
+ ..name = 'companions';
+ await app.requestClosePane(pane.id);
+ await tester.pumpAndSettle();
+ expect(modes(), ['inspect', 'idle']);
+ expect(connection.closes.every((r) => r['sessionId'] == ''), isTrue);
+ expect(app.swarms, isNot(contains(tab)));
+ expect(app.allPanes, isEmpty);
+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
+ expect(app.closedHistory, hasLength(1));
+ expect(find.widgetWithText(FilledButton, 'Close'), findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
for (final entry in {
'working': 'Still working. Close anyway?',
'needs_input': 'Waiting for input. Close anyway?',