Skip to content

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

fix(delete): let Monitor Delete remove a restored agent that never bound a conversation (#1526)

Jacob Pham4acb48303e37
diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.ts
index f953087cc..97ebbea42 100644
--- a/cli/src/core/agents/lifecycle.spec.ts
+++ b/cli/src/core/agents/lifecycle.spec.ts
@@ -111,7 +111,10 @@ describe('stopping, purging and resuming an agent', () => {
it('asks the pane, through the core, whether an agent waits at its folder-trust question', () => {
const atFolderTrust = vi.fn(async () => true)
- expect(setup({ atFolderTrust }).purge.atFolderTrust).toBe(atFolderTrust)
+ const atEmptyComposer = vi.fn(async () => true)
+ const { purge } = setup({ atFolderTrust, atEmptyComposer })
+ expect(purge.atFolderTrust).toBe(atFolderTrust)
+ expect(purge.atEmptyComposer).toBe(atEmptyComposer)
})
it('waits on an agent that is restarting or stopping', () => {
diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.ts
index 69731fda3..326b737ac 100644
--- a/cli/src/core/agents/lifecycle.ts
+++ b/cli/src/core/agents/lifecycle.ts
@@ -34,6 +34,8 @@ export interface LifecycleDeps {
stopNative: StopAgentServiceDeps['stopNative']
/** Whether a fresh read of the agent's pane shows its engine waiting at the folder-trust question (main.ts reads the screen). */
atFolderTrust?: (session: RegisteredSession) => Promise<boolean>
+ /** The same, for an idle pane with an empty composer (a restored agent that never started a conversation). */
+ atEmptyComposer?: (session: RegisteredSession) => Promise<boolean>
markDeleted: typeof markDeletedFn
clearDeleted: typeof clearDeletedFn
sessionCheckpoints: SessionCheckpointStore
@@ -59,7 +61,7 @@ export interface LifecycleDeps {
export function createAgentLifecycle({
registry, stoppedAgents, restartJobs, createBackend, noBackendCode, backendFor, agentReconciler, forgetSession, markDeleted, clearDeleted, stopNative, settlePane, cancelExternal,
sessionCheckpoints, mirror, sessionSearch, send, pinnedControls, retainExitedSession, announceSession,
- relaunchOverrides, prepareSessionResume, refreshGridWebSearch, attachDsh, attachSession, relaunchMarks, stopped, atFolderTrust,
+ relaunchOverrides, prepareSessionResume, refreshGridWebSearch, attachDsh, attachSession, relaunchMarks, stopped, atFolderTrust, atEmptyComposer,
}: LifecycleDeps) {
/**
* Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live
@@ -85,6 +87,7 @@ export function createAgentLifecycle({
stopped: stoppedAgents, checkpoints: sessionCheckpoints, stop: stopAgent,
restarting: id => restartJobs.busy(id) || stopJobs.has(id),
atFolderTrust,
+ atEmptyComposer,
deleted: s => {
if (s.sessionId) { mirror.deleteHistory(s.sessionId); sessionSearch?.deleteHistory(s.sessionId) }
registry.deleteSavedNames([s.agentId, s.sessionId].filter(Boolean))
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 9f763dd55..e2eb03848 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2672,6 +2672,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
clearDeleted,
stopNative: (session, current, confirmUnused) => nativeControls.stop(session, current, confirmUnused),
atFolderTrust: async (session) => (await screens.read(session, await captureTerminal(session.agentId, 80)))?.messageHold === 'trust_open',
+ atEmptyComposer: async (session) => {
+ const reading = await screens.read(session, await captureTerminal(session.agentId, 80))
+ return !!reading && !reading.busy && !reading.question && reading.messageHold === null && reading.teamHold === null
+ },
sessionCheckpoints,
mirror,
sessionSearch,
diff --git a/cli/src/lib/purgeAgentService.ts b/cli/src/lib/purgeAgentService.ts
index 4febe5718..ca626efd1 100644
--- a/cli/src/lib/purgeAgentService.ts
+++ b/cli/src/lib/purgeAgentService.ts
@@ -198,11 +198,27 @@ export interface PurgeDeps {
deleted(session: RegisteredSession): void
/** A fresh read of the pane says the engine is waiting at its folder-trust question (Codex's "Do you trust the contents of this directory?"). */
atFolderTrust?(session: RegisteredSession): Promise<boolean>
+ /** A fresh read of the pane says nothing is running, nothing is asked and the composer is empty (`teamHold` null, not busy). */
+ atEmptyComposer?(session: RegisteredSession): Promise<boolean>
inspect?: typeof inspectNativeHistory
erase?: typeof eraseNativeHistory
now?: () => number
}
+/**
+ * A Claude Code or Codex row a daemon restart (or a resume of a saved agent that had none) put back, that has never shown
+ * a conversation. `resumeOnly` only says that Enter must not start a fresh conversation (registry.ts:103); it carries no
+ * conversation of its own. This row has no id (`sessionId`), no transcript, was never bound (`boundAt`), and no hook has
+ * reached it since its process started: `resumePendingAgent` zeroes `lastHookAt` (registry.ts:1725) and registering a hook
+ * sets it (registry.ts:2046), so a prompt submitted in this pane would have moved it. A pending admission (`admissionHold`, a
+ * hook that arrived but is not yet confirmed) or an external resume counts as evidence, not as absence.
+ */
+export function restoredWithoutConversation(s: RegisteredSession): boolean {
+ return (s.engine === 'claude' || s.engine === 'codex') && s.resumeOnly === true && s.lastHookAt === 0
+ && !s.sessionId && !s.transcriptPath && s.boundAt == null && !s.admissionHold && !s.externalResume
+ && (s.launch == null || s.launch.state === 'ready')
+}
+
export class PurgeAgentService {
private readonly reviews = new Map<string, { session: RegisteredSession; signature: string; expires: number;
history: History | null; worktree?: WorktreeReview; includesWorktree: boolean; worktreeDeleted?: boolean }>()
@@ -273,9 +289,15 @@ export class PurgeAgentService {
* (2026-10-22). Anything that ever bound a conversation is not this, whatever the screen shows.
*/
private async unstartedChat(live: RegisteredSession | undefined): Promise<Pick<StopAgentOptions, 'withoutConversation' | 'confirmUnusedConversation'>> {
- const atTrust = this.deps.atFolderTrust
- if (!live || !atTrust || !unusedChat(live) || !await atTrust(live)) return {}
- return { withoutConversation: () => {}, confirmUnusedConversation: async captured => unusedChat(captured) && await atTrust(captured) }
+ const shows = (session: RegisteredSession): Promise<boolean> => this.showsNoConversation(session)
+ if (!live || !await shows(live)) return {}
+ return { withoutConversation: () => {}, confirmUnusedConversation: async captured => await shows(captured) }
+ }
+
+ /** The row and a fresh read of its pane agree that no conversation was ever started. */
+ private async showsNoConversation(session: RegisteredSession): Promise<boolean> {
+ if (unusedChat(session)) return await this.deps.atFolderTrust?.(session) === true
+ return restoredWithoutConversation(session) && await this.deps.atEmptyComposer?.(session) === true
}
private current(request: Pick<PurgeRequest, 'agentId' | 'sessionId' | 'createdAt'>, deletingHistory = true): RegisteredSession {
diff --git a/cli/src/lib/purgeAtFolderTrust.spec.ts b/cli/src/lib/purgeAtFolderTrust.spec.ts
index 8d1f41db4..edf937e52 100644
--- a/cli/src/lib/purgeAtFolderTrust.spec.ts
+++ b/cli/src/lib/purgeAtFolderTrust.spec.ts
@@ -25,11 +25,12 @@ vi.mock('../core/engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.
*/
let root: string, row: RegisteredSession, stopped: StoppedAgentStore, kill: ReturnType<typeof vi.fn<NonNullable<ReturnType<StopAgentServiceDeps['backendFor']>>['kill']>>
let atFolderTrust: ReturnType<typeof vi.fn<(session: RegisteredSession) => Promise<boolean>>>
+let atEmptyComposer: typeof atFolderTrust
let stopNative: ReturnType<typeof vi.fn<StopAgentServiceDeps['stopNative']>>
const purge = () => new PurgeAgentService({
live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stopped.list()], stopped,
- checkpoints: new SessionCheckpointStore(join(root, 'checkpoints')), restarting: () => false, deleted: vi.fn(), atFolderTrust,
+ checkpoints: new SessionCheckpointStore(join(root, 'checkpoints')), restarting: () => false, deleted: vi.fn(), atFolderTrust, atEmptyComposer,
stop: createStopAgentService({ registry, stoppedAgents: stopped, restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(),
backendFor: () => ({ kill }), agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },
forgetSession: id => registry.removeAgent(id), markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative }),
@@ -47,6 +48,7 @@ beforeEach(() => {
Object.assign(row, { launch: { state: 'ready' }, processIdentity: { pid: 77, executable: 'codex', startMarker: 'fixture' } })
kill = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))
atFolderTrust = vi.fn(async () => true)
+ atEmptyComposer = vi.fn(async () => true)
// The contract of core/engines/nativeControls.ts for an unbound chat while the shared server runs.
stopNative = vi.fn(async (session, _current, confirmUnused) => {
if (!await confirmUnused?.(session)) throw new Error('Cannot confirm which conversation is open. Nothing was stopped.')
@@ -88,3 +90,44 @@ it('does not take a bound conversation for an unused chat, whatever the screen s
expect(atFolderTrust).not.toHaveBeenCalled()
expect(stop).toHaveBeenCalledWith(row.agentId, { current: expect.any(Function) })
})
+
+/**
+ * "Devices" (Codex, dsh autonomous/devices), put back by a daemon restart (2026-10-22): no id, no transcript, never bound,
+ * no hook since, `resumeOnly`, an empty composer. Delete refused it for the same two reasons as above.
+ */
+const restored = (over: Partial<RegisteredSession> = {}) =>
+ Object.assign(row, { resumeOnly: true, lastHookAt: 0, boundAt: null, transcriptPath: null, sessionId: '', dsh: 'autonomous/devices', ...over })
+
+it('deletes a restored (resumeOnly) agent that never bound a conversation, at an empty composer', async () => {
+ restored(); atFolderTrust.mockResolvedValue(false)
+ expect(await deleteIt(purge())).toMatchObject({ deleted: true })
+ expect(kill).toHaveBeenCalledTimes(1)
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+})
+
+it.each([
+ ['a hook has reached it', { lastHookAt: 5 }],
+ ['it was bound', { boundAt: 7 }],
+ ['it has a transcript', { transcriptPath: '/codex/sessions/rollout.jsonl' }],
+ ['a hook awaits admission', { admissionHold: 'pending native hook' }],
+ ['an adoption is in flight', { externalResume: { phase: 'pending' } as never }],
+ ['it is not a Claude Code or Codex row', { engine: 'opencode' as const }],
+ ['it is not ready', { launch: { state: 'failed', error: 'RESUME_FAILED' } as never }],
+])('still refuses a restored agent when %s', async (_why, over) => {
+ restored(over); atFolderTrust.mockResolvedValue(false)
+ expect(await deleteIt(purge())).toHaveProperty('error')
+ expect(kill).not.toHaveBeenCalled()
+ expect(registry.byAgent(row.agentId)).toBeDefined()
+})
+
+it('still refuses a restored agent whose pane is busy, asks something or holds a draft', async () => {
+ restored(); atFolderTrust.mockResolvedValue(false); atEmptyComposer.mockResolvedValue(false)
+ expect(await deleteIt(purge())).toMatchObject({ error: 'IDENTITY_UNAVAILABLE' })
+ expect(kill).not.toHaveBeenCalled()
+})
+
+it('never reads the pane of a row that already holds evidence of a conversation', async () => {
+ restored({ lastHookAt: 5 }); atFolderTrust.mockResolvedValue(false)
+ await deleteIt(purge())
+ expect(atEmptyComposer).not.toHaveBeenCalled()
+})