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 an agent held at its folder-trust question (#1520)

Jacob Pham46adbc1f28a1
diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.ts
index 865f0ef98..f953087cc 100644
--- a/cli/src/core/agents/lifecycle.spec.ts
+++ b/cli/src/core/agents/lifecycle.spec.ts
@@ -109,6 +109,11 @@ describe('stopping, purging and resuming an agent', () => {
expect(purge.stop).toBe(lifecycle.stopAgent)
})
+ 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)
+ })
+
it('waits on an agent that is restarting or stopping', () => {
const restarting = setup({ restartJobs: { busy: vi.fn((id: string) => id === 'a1') } as never })
expect(restarting.purge.restarting('a1')).toBe(true)
diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.ts
index 1a2921961..69731fda3 100644
--- a/cli/src/core/agents/lifecycle.ts
+++ b/cli/src/core/agents/lifecycle.ts
@@ -32,6 +32,8 @@ export interface LifecycleDeps {
agentReconciler: StopAgentServiceDeps['agentReconciler']
forgetSession: StopAgentServiceDeps['forgetSession']
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>
markDeleted: typeof markDeletedFn
clearDeleted: typeof clearDeletedFn
sessionCheckpoints: SessionCheckpointStore
@@ -57,7 +59,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,
+ relaunchOverrides, prepareSessionResume, refreshGridWebSearch, attachDsh, attachSession, relaunchMarks, stopped, atFolderTrust,
}: LifecycleDeps) {
/**
* Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live
@@ -82,6 +84,7 @@ export function createAgentLifecycle({
live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stoppedAgents.list()],
stopped: stoppedAgents, checkpoints: sessionCheckpoints, stop: stopAgent,
restarting: id => restartJobs.busy(id) || stopJobs.has(id),
+ atFolderTrust,
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 02c3c38fd..3aae46cec 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2655,6 +2655,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
markDeleted,
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',
sessionCheckpoints,
mirror,
sessionSearch,
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index d30a5027f..4221ffa72 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -37,7 +37,7 @@ export const CLOSE_STARTING_MS = 60_000
type CloseSession = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'boundAt' | 'launch' | 'resumeOnly'>
-function unusedChat(session: CloseSession): boolean {
+export function unusedChat(session: CloseSession): boolean {
return (session.engine === 'claude' || session.engine === 'codex')
&& !session.sessionId && !session.transcriptPath && session.boundAt == null && !session.resumeOnly
&& (session.launch == null || session.launch.state === 'ready')
diff --git a/cli/src/lib/purgeAgentService.ts b/cli/src/lib/purgeAgentService.ts
index f1ee4c285..4febe5718 100644
--- a/cli/src/lib/purgeAgentService.ts
+++ b/cli/src/lib/purgeAgentService.ts
@@ -16,6 +16,7 @@ import { sqliteReadAll } from './sqliteRead.js'
import type { StoppedAgentStore } from './stoppedAgents.js'
import type { SessionCheckpointStore } from './sessionCheckpoint.js'
import type { StopAgentOptions } from './stopAgentService.js'
+import { unusedChat } from './closeAgentService.js'
import { inspectWorkspace, inspectWorktree, removeReviewedWorktree, type WorktreeReview } from './worktreeDeletion.js'
const exec = promisify(execFile)
@@ -195,6 +196,8 @@ export interface PurgeDeps {
stop(id: string, options: StopAgentOptions): Promise<void>
restarting(id: string): boolean
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>
inspect?: typeof inspectNativeHistory
erase?: typeof eraseNativeHistory
now?: () => number
@@ -262,6 +265,19 @@ export class PurgeAgentService {
}
}
+ /**
+ * An engine waiting at its folder-trust question has opened no conversation, and cannot before it is answered. Stop
+ * is told so, as Close tells it of a chat it saw empty: otherwise a Codex with no bound conversation is held while
+ * the shared server runs ("Cannot confirm which conversation is open"), and where the process cannot be read its
+ * conversation is held too, so two agents a Super Tab started into an untrusted folder could not be deleted
+ * (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) }
+ }
+
private current(request: Pick<PurgeRequest, 'agentId' | 'sessionId' | 'createdAt'>, deletingHistory = true): RegisteredSession {
const s = this.deps.live(request.agentId) ?? this.deps.stopped.get(request.agentId)
if (!s || (s.sessionId || null) !== request.sessionId || s.registeredAt !== request.createdAt) return fail('This harness changed. Refresh and review deletion again.')
@@ -335,7 +351,7 @@ export class PurgeAgentService {
await this.deps.stop(request.agentId, { current: () => {
const live = this.deps.live(request.agentId)
return !!live && identity(live) === review.signature
- } })
+ }, ...await this.unstartedChat(this.deps.live(request.agentId)) })
}
if (this.deps.live(request.agentId)) return fail('The harness did not stop. No session data was deleted.')
stopped = true
diff --git a/cli/src/lib/purgeAtFolderTrust.spec.ts b/cli/src/lib/purgeAtFolderTrust.spec.ts
new file mode 100644
index 000000000..8d1f41db4
--- /dev/null
+++ b/cli/src/lib/purgeAtFolderTrust.spec.ts
@@ -0,0 +1,90 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
+import { PurgeAgentService } from './purgeAgentService.js'
+import { registry, type RegisteredSession } from './registry.js'
+import { SessionCheckpointStore } from './sessionCheckpoint.js'
+import { AgentRestartCoordinator } from './restartAgent.js'
+import { createStopAgentService, type StopAgentServiceDeps } from './stopAgentService.js'
+import { StoppedAgentStore } from './stoppedAgents.js'
+import { captureResumeIdentity } from './captureResumeIdentity.js'
+import { terminateDeletedAgent } from './deleteAgentFallback.js'
+
+vi.mock('./captureResumeIdentity.js', () => ({ captureResumeIdentity: vi.fn() }))
+vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))
+vi.mock('../core/engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))
+
+/**
+ * Monitor Delete of two Codex agents that a Super Tab started into a folder Codex did not trust (2026-10-22). They sat at
+ * "Do you trust the contents of this directory?" with a delivery waiting, and Delete refused them. The step is the stop
+ * Delete makes: a Codex with no bound conversation, on a machine where another Codex agent keeps the shared app-server
+ * running, is only let go when the caller proves the chat unused (core/engines/nativeControls.ts: `unidentified`). Close
+ * supplies that proof; Delete never did.
+ */
+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 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,
+ 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 }),
+})
+const target = () => ({ agentId: row.agentId, sessionId: null, createdAt: row.registeredAt })
+async function deleteIt(service: PurgeAgentService) {
+ const review = await service.request({ ...target(), mode: 'inspect' })
+ return service.request({ ...target(), mode: 'delete', reviewId: String(review.reviewId) })
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'harness-purge-trust-'))
+ stopped = new StoppedAgentStore(join(root, 'stopped'))
+ row = registry.openPendingAgent({ engine: 'codex', cwd: join(root, 'worktree'), runtimes: [{ backend: 'tmux', paneId: '%44' }] })!
+ 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)
+ // 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.')
+ })
+ // This machine could not read the process (the native helper): the conversation is held, not absent.
+ vi.mocked(captureResumeIdentity).mockReset().mockRejectedValue(new IdentityReadUnavailable('the native control helper is unavailable'))
+ vi.mocked(terminateDeletedAgent).mockReset().mockResolvedValue('gone')
+})
+afterEach(() => { for (const entry of registry.list()) registry.removeAgent(entry.agentId); rmSync(root, { recursive: true, force: true }); vi.restoreAllMocks() })
+
+it('deletes a Codex agent held at its folder-trust question, which has no conversation to keep', async () => {
+ expect(await deleteIt(purge())).toMatchObject({ deleted: true })
+ expect(kill).toHaveBeenCalledTimes(1)
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+ expect(atFolderTrust).toHaveBeenCalled()
+})
+
+it('deletes it on a machine that can read the process too, where only the shared server holds it', async () => {
+ vi.mocked(captureResumeIdentity).mockImplementation(async session => session)
+ expect(await deleteIt(purge())).toMatchObject({ deleted: true })
+ expect(stopNative).toHaveBeenCalledTimes(1)
+})
+
+it('still refuses an agent that is not at the trust question, as before', async () => {
+ atFolderTrust.mockResolvedValue(false)
+ expect(await deleteIt(purge())).toMatchObject({ error: 'IDENTITY_UNAVAILABLE', retryable: true })
+ expect(kill).not.toHaveBeenCalled()
+ expect(registry.byAgent(row.agentId)).toBeDefined()
+})
+
+it('does not take a bound conversation for an unused chat, whatever the screen shows', async () => {
+ Object.assign(row, { sessionId: 'bound' })
+ const stop = vi.fn(async () => {})
+ const service = new PurgeAgentService({ live: id => registry.byAgent(id), sessions: () => [], stopped,
+ checkpoints: new SessionCheckpointStore(join(root, 'checkpoints')), restarting: () => false, deleted: vi.fn(), atFolderTrust,
+ inspect: async () => ({ bytes: 0 }), stop })
+ const review = await service.request({ agentId: row.agentId, sessionId: 'bound', createdAt: row.registeredAt, mode: 'inspect' })
+ await service.request({ agentId: row.agentId, sessionId: 'bound', createdAt: row.registeredAt, mode: 'delete', reviewId: String(review.reviewId) })
+ expect(atFolderTrust).not.toHaveBeenCalled()
+ expect(stop).toHaveBeenCalledWith(row.agentId, { current: expect.any(Function) })
+})