From 6732d57a8c4fecf1345da885c81ee4420a0b90ff Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:26:36 -0800 Subject: [PATCH 001/125] fix(agent-hooks): record the exit when a hookless agent quits to its shell A Codex resumed by a wake sends no hooks while idle, so the shell-confirmed reconcile kept its resume row without exit evidence and the next sleep captured it again. Derive the ended presence from the pane's row (the shape sleep settle already builds), and let a later Orca launch forget an exit that predates it. --- .../agent-hooks/server/agent-exit-evidence.ts | 10 +++- src/main/agent-hooks/server/server-cleanup.ts | 27 +++++---- .../server/server-ingest-terminal.ts | 1 + .../agent-hooks/server/server-pane-sleep.ts | 8 +-- src/main/agent-hooks/server/server-state.ts | 6 ++ .../persistence/server-pane-sleep.test.ts | 58 +++++++++++++++++++ src/main/ipc/agent-status-row-teardown-ipc.ts | 3 +- 7 files changed, 91 insertions(+), 22 deletions(-) diff --git a/src/main/agent-hooks/server/agent-exit-evidence.ts b/src/main/agent-hooks/server/agent-exit-evidence.ts index 01185b35a2e9..07a8c198bb73 100644 --- a/src/main/agent-hooks/server/agent-exit-evidence.ts +++ b/src/main/agent-hooks/server/agent-exit-evidence.ts @@ -4,7 +4,8 @@ import { isNewTurnEvent } from '../../../shared/agent-hook-listener/provider-eve import { isSameAgentProcess, readAgentProcessIdentity, - type AgentProcessIdentity + type AgentProcessIdentity, + type AgentProcessPresence } from '../../../shared/agent-status/process/agent-process-presence' /** All pane aliases share the same exit evidence. */ @@ -24,6 +25,13 @@ export type PersistedAgentExitEvidence = { type EndedAgent = { agent?: string; process?: AgentProcessIdentity } +/** The row's owner marked ended, keeping whatever process identity hooks proved. */ +export function endedPresenceOf( + row: Pick +): AgentProcessPresence { + return { agent: row.payload.agentType ?? 'unknown', ...row.agentPresence, ended: true } +} + export function recordAgentExit( exits: Map, paneKeys: Iterable, diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 62cb0ca7f868..3485ac8fce7f 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -16,10 +16,12 @@ import { worktreeIdsEqual } from '../../../shared/worktree/id' import { isLocalHookConnectionId } from '../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import type { EnrichedAgentHookEventPayload } from './server-types' -import { recordAgentExit } from './agent-exit-evidence' +import { endedPresenceOf, recordAgentExit } from './agent-exit-evidence' export type EndedProcessReconciliationOptions = { endedPresence?: AgentProcessPresence + /** The pane's shell is back: its owner ended, even with no process to probe. */ + confirmedExit?: boolean /** Keep resume identity when the pane survives the agent. */ preserveResumeIdentity?: boolean } @@ -124,7 +126,13 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { untouched.push(resolvedPaneKey) continue } - if (options?.endedPresence) { + const previous = this.state.lastStatusByPaneKey.get(resolvedPaneKey) as + | EnrichedAgentHookEventPayload + | undefined + const endedPresence = + options?.endedPresence ?? + (options?.confirmedExit && previous ? endedPresenceOf(previous) : undefined) + if (endedPresence) { // Cleanup drops aliases, but readers may still hold either key. const paneKeys = new Set([resolvedPaneKey, paneKey]) for (const [aliasKey, alias] of this.legacyPaneKeyAliases) { @@ -132,7 +140,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { paneKeys.add(aliasKey) } } - recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, options.endedPresence) + recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, endedPresence) this.scheduleStatusPersist() } if (!this.hasLiveClaimsForPaneKey(resolvedPaneKey)) { @@ -140,19 +148,10 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { continue } const resumeRow = options?.preserveResumeIdentity - ? this.toRetainedProviderSessionRow( - this.state.lastStatusByPaneKey.get(resolvedPaneKey) as - | EnrichedAgentHookEventPayload - | undefined - ) + ? this.toRetainedProviderSessionRow(previous) : null const retained = - resumeRow && options?.endedPresence - ? { ...resumeRow, agentPresence: options.endedPresence } - : resumeRow - const previous = this.state.lastStatusByPaneKey.get(resolvedPaneKey) as - | EnrichedAgentHookEventPayload - | undefined + resumeRow && endedPresence ? { ...resumeRow, agentPresence: endedPresence } : resumeRow clearPane(resolvedPaneKey) if (retained) { admitLegacyAgentStatus( diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index 9da8eb2b40dc..a904221ae9df 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -26,6 +26,7 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges if (!parsedPaneKey || paneKey.length > MAX_PANE_KEY_LEN) { return } + this.forgetAgentExitBefore(paneKey, event.launchedAt) const previous = this.state.lastStatusByPaneKey.get(paneKey) if ( previous && diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index f02937efff45..c5f593f28dd5 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -4,7 +4,7 @@ import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../../shared/agent-sta import type { EnrichedAgentHookEventPayload } from './server-types' import { AgentHookServerAuthorityFences } from './server-authority-fences' -import { recordAgentExit } from './agent-exit-evidence' +import { endedPresenceOf, recordAgentExit } from './agent-exit-evidence' export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityFences { abstract dropStatusEntry(paneKey: string, options?: { preserveResumeIdentity?: boolean }): void @@ -83,11 +83,7 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF ...accepted, payload, paneSleep: { ptyId, ...(incarnationId ? { incarnationId } : {}) }, - agentPresence: { - agent: previous.payload.agentType ?? 'unknown', - ...previous.agentPresence, - ended: true - } + agentPresence: endedPresenceOf(previous) } this.programStatusFacets.delete(resolved) this.hookSilenceRechecks.cancel(resolved) diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 5be52e93d002..d114d9c65e4c 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -104,6 +104,12 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract this.scheduleStatusPersist() } } + /** An exit recorded before a launch belongs to the process that launch replaced. */ + forgetAgentExitBefore(paneKey: string, launchedAt: number): void { + if ((this.agentExitedAtByPaneKey.get(paneKey)?.at ?? Infinity) < launchedAt) { + this.forgetAgentExit(paneKey) + } + } protected readonly canonicalSubjectsByPane = new Map>() private statusListingOrder = 0 protected nextStatusListingOrder = (): number => ++this.statusListingOrder diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 2d6722ddc077..54c06a69e275 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -213,6 +213,64 @@ it.each(['idle Codex', 'Claude hook', 'failed resume', 'ordinary exit'] as const } ) +it('retires a hookless resumed Codex quit to its shell, and keeps a later relaunch', async () => { + const providerSession = { key: 'session_id', id: 'woken-session' } + const saved: SleepingAgentSessionRecord = { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + agent: 'codex', + providerSession, + prompt: '', + state: 'done', + capturedAt: 1, + updatedAt: 1, + origin: 'worktree-sleep', + restoreOnTabOpenOnly: true, + connectionId: null + } + const session = { + ...getDefaultWorkspaceSession(), + sleepingAgentSessionsByPaneKey: { [PANE]: saved } + } + const sleep = async () => { + const capture = await captureWorktreeSleepResumeRecords({ + worktreeId: 'wt-1', + paneKeysByPtyId: new Map([['pty', [PANE]]]), + launchByPtyId: new Map(), + readRowsForPane: (paneKey) => server.getStatusSnapshotForPane(paneKey), + checkAgentPresence: (paneKey, since) => server.checkAgentPresenceSince(paneKey, since ?? 0), + capturedAt: 2 + }) + return applyWorktreeSleepResumeRecords(session, capture, ['pty']) ?? session + } + const launch = () => + server.recordLaunchResumeIdentity({ + paneKey: PANE, + worktreeId: 'wt-1', + agentType: 'codex', + providerSession, + launchedAt: Date.now() + }) + vi.useFakeTimers({ toFake: ['Date'] }) + launch() + vi.setSystemTime(Date.now() + 1000) + // The renderer's confirmed shell return, as the IPC handler reconciles it. + server.reconcileEndedProcessForPaneKeys([PANE], { + preserveResumeIdentity: true, + confirmedExit: true + }) + expect((await sleep()).sleepingAgentSessionsByPaneKey?.[PANE]).toBeUndefined() + + vi.setSystemTime(Date.now() + 1000) + launch() + expect((await sleep()).sleepingAgentSessionsByPaneKey?.[PANE]).toMatchObject({ + agent: 'codex', + providerSession, + origin: 'worktree-sleep' + }) +}) + it('does not restore a sleeping status whose exact placed pane is absent', async () => { server.ingestTerminalStatus({ paneKey: PANE, diff --git a/src/main/ipc/agent-status-row-teardown-ipc.ts b/src/main/ipc/agent-status-row-teardown-ipc.ts index 264f44a3dc2e..b460f3ffd59f 100644 --- a/src/main/ipc/agent-status-row-teardown-ipc.ts +++ b/src/main/ipc/agent-status-row-teardown-ipc.ts @@ -74,7 +74,8 @@ export function registerAgentStatusRowTeardownIpcHandlers(): void { // Confirmed process exit must clear latches with the row (STA-4612). agentHookServer.reconcileEndedProcessForPaneKeys([paneKey], { // The shell still owns the PTY, so keep its usable resume identity. - preserveResumeIdentity: true + preserveResumeIdentity: true, + confirmedExit: true }) clearMigrationUnsupportedPtysForPaneKey(paneKey) } catch (err) { From d70520f4616b6d56bc6a95292ea77505d6c4a661 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:37:38 -0800 Subject: [PATCH 002/125] fix(agent-hooks): keep shell-return exits to process-less rows A row with a proved process gets its exit from the presence probe, and a same-session relaunch replaces an ended resume row. --- src/main/agent-hooks/server/server-cleanup.ts | 7 +++++-- src/main/agent-hooks/server/server-ingest-terminal.ts | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 3485ac8fce7f..c7c6404aaed0 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -20,7 +20,7 @@ import { endedPresenceOf, recordAgentExit } from './agent-exit-evidence' export type EndedProcessReconciliationOptions = { endedPresence?: AgentProcessPresence - /** The pane's shell is back: its owner ended, even with no process to probe. */ + /** The pane's shell is back: a process-less owner ended. */ confirmedExit?: boolean /** Keep resume identity when the pane survives the agent. */ preserveResumeIdentity?: boolean @@ -131,7 +131,10 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { | undefined const endedPresence = options?.endedPresence ?? - (options?.confirmedExit && previous ? endedPresenceOf(previous) : undefined) + // A proved process gets its exit from the presence probe, not a possibly newer row. + (options?.confirmedExit && previous && !previous.agentPresence?.process + ? endedPresenceOf(previous) + : undefined) if (endedPresence) { // Cleanup drops aliases, but readers may still hold either key. const paneKeys = new Set([resolvedPaneKey, paneKey]) diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index a904221ae9df..1d2df3cb50c0 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -30,7 +30,8 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges const previous = this.state.lastStatusByPaneKey.get(paneKey) if ( previous && - (previous.providerSessionOnly === true + // An ended resume row was a predecessor's; only a row since this launch is the agent's own. + (previous.providerSessionOnly === true && !previous.agentPresence?.ended ? agentProviderSessionsEqual( event.agentType, previous.providerSession, From 3e22e833f61d0273e54091835d2131ca13252195 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:56:52 -0800 Subject: [PATCH 003/125] test: type the provider session in the hookless quit test --- .../server/testing/persistence/server-pane-sleep.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 54c06a69e275..434d430f7711 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -3,7 +3,10 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { getDefaultWorkspaceSession } from '../../../../../shared/constants' -import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { + AgentProviderSessionMetadata, + SleepingAgentSessionRecord +} from '../../../../../shared/agent-session/lifecycle/agent-session-resume' import { applyWorktreeSleepResumeRecords, captureWorktreeSleepResumeRecords @@ -214,7 +217,7 @@ it.each(['idle Codex', 'Claude hook', 'failed resume', 'ordinary exit'] as const ) it('retires a hookless resumed Codex quit to its shell, and keeps a later relaunch', async () => { - const providerSession = { key: 'session_id', id: 'woken-session' } + const providerSession: AgentProviderSessionMetadata = { key: 'session_id', id: 'woken-session' } const saved: SleepingAgentSessionRecord = { paneKey: PANE, tabId: 'tab-1', From 0f06dac5fdf390991b275497387f0b6429351687 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:58:55 -0800 Subject: [PATCH 004/125] Keep pane conversation identity through sleep and wake Co-authored-by: d.bondarev --- .../runtime/agent-hook-runtime-deps.ts | 9 +- .../agent-hooks/server/pane-agent-identity.ts | 78 ++++++++ src/main/agent-hooks/server/server-cleanup.ts | 2 +- .../server/server-ingest-terminal.ts | 19 +- .../agent-hooks/server/server-pane-sleep.ts | 100 ++++++++-- src/main/agent-hooks/server/server-state.ts | 42 +++- .../server/server-status-update.ts | 47 ++++- .../persistence/server-pane-sleep.test.ts | 110 ++++++++++- .../pane/terminal-pane-status-lifecycle.ts | 12 ++ src/main/ipc/pty/spawn-commit-publication.ts | 13 +- .../runtime-agent-status-sources.ts | 23 +++ .../runtime-construction-dependencies.ts | 6 + .../construction/runtime-construction.ts | 2 + .../worktree-sleep-resume-recording.test.ts | 180 ++++++++++++++++++ .../stop/worktree-sleep-resume-recording.ts | 20 +- .../stop/worktree-sleep-resume-records.ts | 26 ++- .../runtime-hook-agent-row-selection.ts | 9 +- .../runtime-worktree-pty-agent-sources.ts | 9 +- .../workspace-process-listing.ts | 12 +- .../agent-status-recovery-collection.ts | 18 +- .../promote-saved-live-resume-record.ts | 27 +++ 21 files changed, 698 insertions(+), 66 deletions(-) create mode 100644 src/main/agent-hooks/server/pane-agent-identity.ts create mode 100644 src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts create mode 100644 src/shared/agent-session/lifecycle/resume/promote-saved-live-resume-record.ts diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index 81e6c46c974d..6b90d687ab5a 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -16,8 +16,15 @@ export function agentHookRuntimeDeps( onTerminalProgramStatusFacet: (event) => server.ingestProgramStatusFacet(event), onClaudeTerminalEvidence: (paneKey, evidence) => server.observeClaudeTerminalEvidence(paneKey, evidence), + getPaneAgentIdentity: (paneKey, savedRecord) => server.paneAgentIdentity(paneKey, savedRecord), getAgentStatusSnapshot: () => - server.getStatusSnapshot().filter((entry) => entry.providerSessionOnly !== true), + server.getStatusSnapshot().flatMap((row) => { + if (row.structuredHost) { + return [row] + } + const identity = server.paneAgentIdentity(row.paneKey) + return identity && !identity.ended ? [identity.status] : [] + }), getAgentStatusSnapshotForPane: (paneKey) => server.getStatusSnapshotForPane(paneKey), getPublicAgentStatusSnapshotForPane: (paneKey: string, terminalHandle?: string | null) => server.getPublicStatusSnapshotForPane(paneKey, terminalHandle), diff --git a/src/main/agent-hooks/server/pane-agent-identity.ts b/src/main/agent-hooks/server/pane-agent-identity.ts new file mode 100644 index 000000000000..1b41b3351530 --- /dev/null +++ b/src/main/agent-hooks/server/pane-agent-identity.ts @@ -0,0 +1,78 @@ +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' +import { promoteSavedLiveResumeRecord } from '../../../shared/agent-session/lifecycle/resume/promote-saved-live-resume-record' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' + +export type PaneAgentIdentity = { + status: AgentStatusIpcPayload + /** The agent left the pane; its identity names what to retire, not what to resume. */ + ended: boolean +} + +/** The one rule for which agent conversation a pane holds: its hook row in any at-rest shape, + * else its saved live record, minus an exit recorded since that identity was last updated. */ +export function paneAgentIdentity(args: { + paneKey: string + row?: AgentStatusIpcPayload + savedRecord?: SleepingAgentSessionRecord + worktreeId?: string + exitedAt?: number + /** Process evidence that the pane's agent has ended. */ + ended?: boolean +}): PaneAgentIdentity | null { + const { row } = args + if (row) { + // Structured chats own their sessions elsewhere; a row of any other agent here outranks the record. + if (row.structuredHost) { + return null + } + // Resume-only rows carry placeholder status; read them as at rest without claiming a finished turn. + const { + workingMode: _workingMode, + providerSessionOnly: _providerSessionOnly, + ...placeholder + } = row + const status: AgentStatusIpcPayload = row.providerSessionOnly + ? { ...placeholder, state: 'done' } + : row + // Sleep is a resumable physical stop: its exit retires the process, never the conversation. + if (row.paneSleep) { + return { status, ended: false } + } + return { status, ended: endedSince(args, row.receivedAt) } + } + const saved = args.savedRecord + const promoted = + saved && args.worktreeId + ? promoteSavedLiveResumeRecord({ + record: saved, + worktreeId: args.worktreeId, + capturedAt: saved.capturedAt + }) + : null + if (!saved || !promoted || saved.paneKey !== args.paneKey) { + return null + } + return { + status: { + paneKey: args.paneKey, + ...(promoted.tabId ? { tabId: promoted.tabId } : {}), + worktreeId: promoted.worktreeId, + connectionId: promoted.connectionId ?? null, + receivedAt: saved.updatedAt, + stateStartedAt: saved.updatedAt, + providerSession: promoted.providerSession, + state: 'done', + prompt: promoted.prompt, + agentType: promoted.agent, + ...(promoted.lastAssistantMessage + ? { lastAssistantMessage: promoted.lastAssistantMessage } + : {}) + }, + // The promotion restamps its clock; the exit must postdate the record as saved. + ended: endedSince(args, saved.updatedAt) + } +} + +function endedSince(args: { exitedAt?: number; ended?: boolean }, updatedAt: number): boolean { + return args.ended === true || (args.exitedAt !== undefined && args.exitedAt >= updatedAt) +} diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 62cb0ca7f868..ce38e7942f42 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -120,7 +120,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { let cleared = 0 for (const paneKey of paneKeys) { const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey) - if (this.preservesStoppingDone(resolvedPaneKey)) { + if (this.preservesStoppingAgent(resolvedPaneKey)) { untouched.push(resolvedPaneKey) continue } diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index 9da8eb2b40dc..8ab9cce052a5 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -29,15 +29,16 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges const previous = this.state.lastStatusByPaneKey.get(paneKey) if ( previous && - (previous.providerSessionOnly === true - ? agentProviderSessionsEqual( - event.agentType, - previous.providerSession, - event.providerSession - ) - : 'receivedAt' in previous && + ((previous.payload.agentType === event.agentType && + agentProviderSessionsEqual( + event.agentType, + previous.providerSession, + event.providerSession + )) || + (previous.providerSessionOnly !== true && + 'receivedAt' in previous && typeof previous.receivedAt === 'number' && - previous.receivedAt >= event.launchedAt) + previous.receivedAt >= event.launchedAt)) ) { return } @@ -199,7 +200,7 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges ? this.programStatusFacets.noteState(paneKey, payload, now) : undefined if (event.removesProgramStatusRow === true) { - if (this.preservesStoppingDone(paneKey)) { + if (this.preservesStoppingAgent(paneKey)) { return } this.hookSilenceRechecks.cancel(paneKey) diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index f02937efff45..b75a5e5155cb 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -1,10 +1,16 @@ -import { admitLegacyAgentStatus } from '../../../shared/agent-hook-listener/listener-state' +import { + admitLegacyAgentStatus, + clearPaneProcessCacheState +} from '../../../shared/agent-hook-listener/listener-state' import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../../shared/agent-status/transport/agent-status-legacy-adapter' +import { pickParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' import type { EnrichedAgentHookEventPayload } from './server-types' import { AgentHookServerAuthorityFences } from './server-authority-fences' import { recordAgentExit } from './agent-exit-evidence' +import type { LaunchResumeIdentityEvent } from './launch-resume-identity-event' +import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityFences { abstract dropStatusEntry(paneKey: string, options?: { preserveResumeIdentity?: boolean }): void @@ -20,25 +26,60 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF } } - retireSleepingPaneOnSpawn(paneKey: string): void { - const row = this.state.lastStatusByPaneKey.get(paneKey) as + retireSleepingPaneOnSpawn( + paneKey: string, + resumed?: Pick + ): void { + const resolved = this.resolvePaneKeyAlias(paneKey) + const row = this.state.lastStatusByPaneKey.get(resolved) as | EnrichedAgentHookEventPayload | undefined - if (row?.paneSleep) { - this.dropStatusEntry(paneKey, { preserveResumeIdentity: false }) - // The sleep-time exit belongs to the process that the spawn replaces. - this.forgetAgentExit(paneKey) - this.emitPaneStatusCleared({ paneKey }) + if (!row?.paneSleep) { + return + } + // A dropped resume leaves a shell; only the same conversation keeps its accepted turn. + if ( + resumed && + row.payload.agentType === resumed.agentType && + agentProviderSessionsEqual(resumed.agentType, row.providerSession, resumed.providerSession) + ) { + const { + paneSleep: _paneSleep, + agentPresence: _presence, + terminalHandle: _handle, + ...rest + } = row + admitLegacyAgentStatus( + this.state, + 'main-status-cleanup', + rest, + AGENT_STATUS_2A_CURRENT_PRODUCER_MODE + ) + this.commitStatusRowMutation(row, rest) + this.scheduleStatusPersist() + this.notifyStatusChangeListeners() + this.onAgentStatus?.({ ...rest, isReplay: true }) + } else { + this.dropStatusEntry(resolved, { preserveResumeIdentity: false }) + this.emitPaneStatusCleared({ paneKey: resolved }) } + // The sleep-time exit belongs to the process that the spawn replaces. + this.forgetAgentExit(resolved) } /** The physical stop changes presence, never the accepted completion or its clocks. */ settleTerminalPaneSleep(paneKey: string, ptyId: string, incarnationId?: string): boolean { const resolved = this.resolvePaneKeyAlias(paneKey) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. - const previous = this.state.lastStatusByPaneKey.get(resolved) as - | EnrichedAgentHookEventPayload - | undefined + const identity = this.paneAgentIdentity(resolved) + const previous = + (this.state.lastStatusByPaneKey.get(resolved) as EnrichedAgentHookEventPayload | undefined) ?? + (identity + ? { + ...identity.status, + payload: pickParsedAgentStatusPayload(identity.status) + } + : undefined) if ( previous?.paneSleep?.ptyId === ptyId && (!previous.paneSleep.incarnationId || @@ -52,11 +93,8 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF } if ( !previous || - previous.payload.state !== 'done' || - previous.payload.sessionBoundary === true || - previous.providerSessionOnly || - previous.structuredHost || - previous.observation?.origin === 'launch' || + !identity || + identity.ended || this.terminalPaneLifecycle?.isReversibleStop(ptyId, incarnationId) !== true || this.terminalPaneLifecycle.isPlaced(previous) !== true ) { @@ -69,6 +107,8 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF toolUseId: _toolUseId, toolAgentId: _toolAgentId, terminalHandle: _terminalHandle, + providerSessionOnly: _providerSessionOnly, + retainedForLiveness: _retainedForLiveness, ...accepted } = previous const { @@ -77,11 +117,31 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF interactivePrompt: _interactivePrompt, subagents: _subagents, claudeTaskWakeupPending: _wakeup, + workingMode: _workingMode, ...payload } = previous.payload + // Sleep cut an unfinished turn short; that reads Interrupted, never a completion. + const now = Date.now() + const midTurn = previous.payload.state !== 'done' && previous.providerSessionOnly !== true const row: EnrichedAgentHookEventPayload = { ...accepted, - payload, + ...(midTurn ? { stateStartedAt: now } : {}), + payload: midTurn + ? { + ...payload, + state: 'done', + interrupted: true, + ...(payload.mainAgent + ? { + mainAgent: { + state: 'done' as const, + outcome: 'cancellation' as const, + stateStartedAt: now + } + } + : {}) + } + : { ...payload, state: identity.status.state }, paneSleep: { ptyId, ...(incarnationId ? { incarnationId } : {}) }, agentPresence: { agent: previous.payload.agentType ?? 'unknown', @@ -89,6 +149,10 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF ended: true } } + if (midTurn) { + // The cut-off turn's producer records belong to the stopped process. + clearPaneProcessCacheState(this.state, resolved) + } this.programStatusFacets.delete(resolved) this.hookSilenceRechecks.cancel(resolved) admitLegacyAgentStatus( @@ -97,7 +161,7 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF row, AGENT_STATUS_2A_CURRENT_PRODUCER_MODE ) - recordAgentExit(this.agentExitedAtByPaneKey, [resolved], row.agentPresence) + recordAgentExit(this.agentExitedAtByPaneKey, [resolved], row.agentPresence, now) this.commitStatusRowMutation(previous, row) this.scheduleStatusPersist() this.notifyStatusChangeListeners() diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 5be52e93d002..7a04f08681a2 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -43,9 +43,13 @@ import type { } from './server-types' import { RevisionedMap } from './revisioned-map' import { forgetAgentExit, type AgentExitEvidence } from './agent-exit-evidence' +import { paneAgentIdentity, type PaneAgentIdentity } from './pane-agent-identity' +import { toAgentStatusIpcPayload } from './server-status-identity' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' export abstract class AgentHookServerState extends AgentHookServerStateContract { protected terminalPaneLifecycle: { + readSavedRecord?(paneKey: string): SleepingAgentSessionRecord | undefined ownsProcess(paneKey: string, ptyId: string, incarnationId?: string): boolean isStopping(paneKey: string): boolean isReversibleStop(ptyId: string, incarnationId?: string): boolean @@ -58,15 +62,41 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract this.terminalPaneLifecycle = lifecycle } - protected preservesStoppingDone(paneKey: string): boolean { - const row = this.state.lastStatusByPaneKey.get(paneKey) as + /** Which agent conversation this pane holds; see paneAgentIdentity. */ + paneAgentIdentity( + paneKey: string, + savedRecord?: SleepingAgentSessionRecord, + worktreeId = savedRecord?.worktreeId + ): PaneAgentIdentity | null { + const resolved = this.resolvePaneKeyAlias(paneKey) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. + const row = this.state.lastStatusByPaneKey.get(resolved) as | EnrichedAgentHookEventPayload | undefined + if (!row) { + savedRecord ??= this.terminalPaneLifecycle?.readSavedRecord?.(resolved) + } + worktreeId ??= savedRecord?.worktreeId + const exit = + this.agentExitedAtByPaneKey.get(resolved) ?? this.agentExitedAtByPaneKey.get(paneKey) + return paneAgentIdentity({ + paneKey: resolved, + ...(row ? { row: toAgentStatusIpcPayload(row) } : {}), + ...(savedRecord ? { savedRecord } : {}), + ...(worktreeId ? { worktreeId } : {}), + ...(exit ? { exitedAt: exit.at } : {}), + ended: row?.agentPresence?.ended === true + }) + } + + /** A stopping pane's agent keeps its row for the sleep gate, whatever shape it rests in. */ + protected preservesStoppingAgent(paneKey: string): boolean { + const identity = this.paneAgentIdentity(paneKey) return ( - row?.payload.state === 'done' && - row.payload.sessionBoundary !== true && - row.providerSessionOnly !== true && - (row.paneSleep !== undefined || this.terminalPaneLifecycle?.isStopping(paneKey) === true) + identity !== null && + !identity.ended && + (identity.status.paneSleep !== undefined || + this.terminalPaneLifecycle?.isStopping(paneKey) === true) ) } protected canWriteLegacyStatusRow(entry: AgentHookEventPayload): boolean { diff --git a/src/main/agent-hooks/server/server-status-update.ts b/src/main/agent-hooks/server/server-status-update.ts index c0293ac1cb60..6a19d83eefcd 100644 --- a/src/main/agent-hooks/server/server-status-update.ts +++ b/src/main/agent-hooks/server/server-status-update.ts @@ -27,6 +27,31 @@ import { isForeignTurnHook } from './server-foreign-turn-hook' import { resolveCancelVerdictLatch } from '../../../shared/agent-hook-listener/state/agent-hook-cancel-verdict-latch' import { claimsPaneAfterExit } from './agent-exit-evidence' +import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' + +/** A boundary for the conversation whose turn the pane last accepted keeps that turn's verdict. */ +function resumesAcceptedDone( + previous: EnrichedAgentHookEventPayload, + incoming: AgentHookEventPayload +): boolean { + return ( + incoming.payload.sessionBoundary === true && + previous.payload.state === 'done' && + previous.payload.sessionBoundary !== true && + previous.providerSessionOnly !== true && + previous.paneSleep === undefined && + previous.providerSession !== undefined && + previous.payload.agentType === incoming.payload.agentType && + sameAgentStatusTerminalOwner(previous, incoming) && + agentProviderSessionsEqual( + incoming.payload.agentType, + previous.providerSession, + incoming.providerSession + ) + ) +} export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusRowMutation { protected applyNormalizedStatus( @@ -104,7 +129,7 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusR payload.payload.sessionBoundary === true && !rootContext.acquired && this.sameTerminalOwner(previous, payload) && - this.preservesStoppingDone(previous.paneKey) + this.preservesStoppingAgent(previous.paneKey) ) { return previous } @@ -195,6 +220,26 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusR if (previous && stateReconciledPayload === previous) { return previous } + if (previous && resumesAcceptedDone(previous, stateReconciledPayload)) { + // The resumed process owns the conversation's last verdict; the slept one's identity stays behind. + const { agentPresence: _sleptOwner, restoredUnconfirmed: _restored, ...accepted } = previous + const resumed: EnrichedAgentHookEventPayload = { + ...accepted, + ...(stateReconciledPayload.providerSession + ? { providerSession: stateReconciledPayload.providerSession } + : {}), + ...(stateReconciledPayload.agentPresence + ? { agentPresence: stateReconciledPayload.agentPresence } + : {}) + } + if (!this.writeLegacyStatusRow(resumed)) { + return undefined + } + this.runtimeObservedStatusPaneKeys.add(resumed.paneKey) + this.commitStatusRowMutation(rowBefore, resumed) + this.scheduleStatusPersist() + return resumed + } // Relay restart loses root context; child hooks must not erase persisted resume/model identity. const rootContextPreservingPayload = retainHookRootContext( stateReconciledPayload, diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 2d6722ddc077..20b95db3dba9 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -24,6 +24,7 @@ let home: string let server: AgentHookServer let stopping: boolean let placed: boolean +let pty: { id: string; birth: string } const read = () => server.getStatusSnapshotForPane(PANE)[0] beforeEach(async () => { @@ -31,11 +32,13 @@ beforeEach(async () => { home = mkdtempSync(join(tmpdir(), 'orca-sleep-status-')) stopping = false placed = true + pty = { id: 'pty', birth: 'birth' } server = new AgentHookServer() + const owns = (id: string, incarnation?: string) => id === pty.id && incarnation === pty.birth server.setTerminalPaneLifecycle({ - ownsProcess: (_key, pty, incarnation) => pty === 'pty' && incarnation === 'birth', + ownsProcess: (_key, id, incarnation) => owns(id, incarnation), isStopping: () => stopping, - isReversibleStop: (pty, incarnation) => stopping && pty === 'pty' && incarnation === 'birth', + isReversibleStop: (id, incarnation) => stopping && owns(id, incarnation), isPlaced: () => placed }) await server.start({ env: 'production', userDataPath: home }) @@ -103,7 +106,6 @@ it('accepts a genuine providerless completion after stop intent and preserves it }) publish('working') stopping = true - expect(server.settleTerminalPaneSleep(PANE, 'pty', 'birth')).toBe(false) publish('done') expect(server.settleTerminalPaneSleep(PANE, 'pty', 'other-birth')).toBe(false) expect(server.settleTerminalPaneSleep(PANE, 'pty', 'birth')).toBe(true) @@ -171,7 +173,12 @@ it.each(['idle Codex', 'Claude hook', 'failed resume', 'ordinary exit'] as const expect(await server.checkAgentPresenceSince(PANE, 0)).toBe('exited') stopping = false - server.retireSleepingPaneOnSpawn(PANE) + server.retireSleepingPaneOnSpawn( + PANE, + wake === 'idle Codex' || wake === 'Claude hook' + ? { agentType: agent, providerSession: { key: 'session_id', id: 'sleep-session' } } + : undefined + ) if (wake === 'idle Codex' || wake === 'Claude hook') { server.recordLaunchResumeIdentity({ paneKey: PANE, @@ -180,7 +187,7 @@ it.each(['idle Codex', 'Claude hook', 'failed resume', 'ordinary exit'] as const providerSession: { key: 'session_id', id: 'sleep-session' }, launchedAt: Date.now() }) - expect(read()).toMatchObject({ providerSessionOnly: true }) + expect(read()).toMatchObject({ state: 'done', prompt: 'Finished work' }) } if (wake === 'Claude hook') { await hook('SessionStart', 4002) @@ -213,6 +220,99 @@ it.each(['idle Codex', 'Claude hook', 'failed resume', 'ordinary exit'] as const } ) +const agentHook = (agent: 'claude' | 'codex', event: string, pid: number, source = 'resume') => + postHookEvent( + server, + buildBody( + { hook_event_name: event, session_id: `${agent}-session`, source, prompt: 'Finished work' }, + { + agentProcess: JSON.stringify({ pid, platform: process.platform, startTime: `birth-${pid}` }) + } + ), + `/hook/${agent}` + ) + +async function sleepPane(agent: 'claude' | 'codex', id: string, pid: number): Promise { + pty = { id, birth: `birth-${id}` } + stopping = true + if (agent === 'claude') { + await agentHook(agent, 'SessionEnd', pid) + } + expect(server.settleTerminalPaneSleep(PANE, pty.id, pty.birth)).toBe(true) + stopping = false +} + +it.each(['claude', 'codex'] as const)( + 'keeps %s Done through sleep, idle wake and sleep again', + async (agent) => { + await agentHook(agent, 'UserPromptSubmit', 4001) + await agentHook(agent, 'Stop', 4001) + await sleepPane(agent, 'pty-1', 4001) + server.retireSleepingPaneOnSpawn(PANE, { + agentType: agent, + providerSession: { key: 'session_id', id: `${agent}-session` } + }) + server.recordLaunchResumeIdentity({ + paneKey: PANE, + worktreeId: 'wt-1', + agentType: agent, + providerSession: { key: 'session_id', id: `${agent}-session` }, + launchedAt: Date.now() + }) + if (agent === 'claude') { + await agentHook(agent, 'SessionStart', 4002) + } + expect(read()).toMatchObject({ state: 'done', prompt: 'Finished work' }) + expect(read()).not.toHaveProperty('paneSleep') + await sleepPane(agent, 'pty-2', 4002) + expect(read()).toMatchObject({ + state: 'done', + prompt: 'Finished work', + paneSleep: { ptyId: 'pty-2' } + }) + } +) + +it.each(['claude', 'codex'] as const)( + 'keeps a mid-turn %s through sleep as Interrupted without a completion', + async (agent) => { + await agentHook(agent, 'UserPromptSubmit', 4001) + const emitted = vi.fn() + server.setListener(emitted) + emitted.mockClear() + await sleepPane(agent, 'pty-1', 4001) + expect(read()).toMatchObject({ + state: 'done', + interrupted: true, + prompt: 'Finished work', + paneSleep: { ptyId: 'pty-1' } + }) + expect(emitted.mock.calls.filter(([row]) => !row.isReplay)).toHaveLength(0) + } +) + +it.each(['claude', 'codex'] as const)( + 'keeps a %s that never had a turn through sleep', + async (agent) => { + if (agent === 'claude') { + await agentHook(agent, 'SessionStart', 4001, 'startup') + } else { + server.recordLaunchResumeIdentity({ + paneKey: PANE, + worktreeId: 'wt-1', + agentType: agent, + providerSession: { key: 'session_id', id: `${agent}-session` }, + launchedAt: Date.now() + }) + } + await sleepPane(agent, 'pty-1', 4001) + expect(server.paneAgentIdentity(PANE)).toMatchObject({ + status: { agentType: agent, state: 'done', paneSleep: { ptyId: 'pty-1' } }, + ended: false + }) + } +) + it('does not restore a sleeping status whose exact placed pane is absent', async () => { server.ingestTerminalStatus({ paneKey: PANE, diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index e8887901ce57..a4783469d96f 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -13,6 +13,18 @@ export function bindTerminalPaneStatusLifecycle( store: Store | undefined ): void { agentHookServer.setTerminalPaneLifecycle({ + readSavedRecord: (paneKey) => { + try { + const pane = runtime?.resolveTerminalPane(paneKey) + if (!pane?.worktreeId) { + return undefined + } + return runtime?.getWorkspaceSessionForWorktree(pane.worktreeId) + ?.sleepingAgentSessionsByPaneKey?.[paneKey] + } catch { + return undefined + } + }, ownsProcess: (paneKey, ptyId, incarnationId) => { const current = paneKeyPtyId.get(paneKey) if (current) { diff --git a/src/main/ipc/pty/spawn-commit-publication.ts b/src/main/ipc/pty/spawn-commit-publication.ts index 75e6ffb35103..58597e85c514 100644 --- a/src/main/ipc/pty/spawn-commit-publication.ts +++ b/src/main/ipc/pty/spawn-commit-publication.ts @@ -1,3 +1,7 @@ +import { + isResumableTuiAgent, + normalizeAgentProviderSession +} from '../../../shared/agent-session/lifecycle/agent-session-resume' import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { clearMigrationUnsupportedPtysForPaneKey } from '../../agent-hooks/observations/migration-unsupported-pty-state' import { registerPty } from '../../memory/pty-registry' @@ -88,7 +92,14 @@ export function publishCommittedPtySpawn(input: PtySpawnCommitInput): PtySpawnOu !result.isReattach && result.agentSessionEnsure?.disposition !== 'adopted' ) { - agentHookServer.retireSleepingPaneOnSpawn(rememberedPaneKey) + const providerSession = + !input.resumeArgvDropped && normalizeAgentProviderSession(args.resumeProviderSession) + agentHookServer.retireSleepingPaneOnSpawn( + rememberedPaneKey, + providerSession && isResumableTuiAgent(args.launchAgent) + ? { agentType: args.launchAgent, providerSession } + : undefined + ) } if (input.paneKeyAliases) { registerSpawnPaneKeyAliases(result, input.paneKey, input.paneKeyAliases) diff --git a/src/main/runtime/construction/runtime-agent-status-sources.ts b/src/main/runtime/construction/runtime-agent-status-sources.ts index a6267cdf85b0..ffed2c479acd 100644 --- a/src/main/runtime/construction/runtime-agent-status-sources.ts +++ b/src/main/runtime/construction/runtime-agent-status-sources.ts @@ -1,3 +1,5 @@ +import { paneAgentIdentity } from '../../agent-hooks/server/pane-agent-identity' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { AgentProviderSessionMetadata } from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { RuntimeConstructionBindings as HostBindings } from './runtime-construction-dependencies' @@ -7,6 +9,27 @@ import { OrcaRuntimeWithTerminalDrivers } from '../terminal/driver/terminal-driv import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' export abstract class RuntimeAgentStatusSources extends OrcaRuntimeWithTerminalDrivers { + protected readonly getPaneAgentIdentityFn!: HostBindings['getPaneAgentIdentity'] | null + + readPaneAgentIdentity( + paneKey: string, + savedRecord?: SleepingAgentSessionRecord, + row?: AgentStatusIpcPayload + ) { + return this.getPaneAgentIdentityFn + ? this.getPaneAgentIdentityFn(paneKey, savedRecord) + : paneAgentIdentity({ + paneKey, + row: + row ?? + this.getAgentProviderSessionRowsForPaneFn?.(paneKey).find( + (row) => row.paneKey === paneKey + ), + savedRecord, + worktreeId: savedRecord?.worktreeId + }) + } + readonly getAgentStatusSnapshotFn!: HostBindings['getAgentStatusSnapshot'] | null protected readonly structuredAgentStatusSinkFn!: HostBindings['structuredAgentStatusSink'] | null diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 834683123898..5ff35aa7be05 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -1,3 +1,5 @@ +import type { paneAgentIdentity } from '../../agent-hooks/server/pane-agent-identity' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { AgentProviderSessionMetadata } from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { CliWriterObservation } from '../../agent-hooks/server/cli-writer-observation' import type { ExecutionHostScope } from '../../../shared/execution-host' @@ -34,6 +36,10 @@ export type RuntimeConstructionDependencies = { onTerminalProgramStatusFacet?: (event: RuntimeTerminalProgramStatusFacetEvent) => void onTerminalSideEffects?: (batch: TerminalSideEffectBatch) => void onClaudeTerminalEvidence?: (paneKey: string, evidence: ClaudeTerminalEvidence) => void + getPaneAgentIdentity?: ( + paneKey: string, + savedRecord?: SleepingAgentSessionRecord + ) => ReturnType getAgentStatusSnapshot?: () => AgentStatusIpcPayload[] getAgentStatusSnapshotForPane?: (paneKey: string) => AgentStatusIpcPayload[] getPublicAgentStatusSnapshotForPane?: ( diff --git a/src/main/runtime/construction/runtime-construction.ts b/src/main/runtime/construction/runtime-construction.ts index 8ad4d20268a0..24bb36f08671 100644 --- a/src/main/runtime/construction/runtime-construction.ts +++ b/src/main/runtime/construction/runtime-construction.ts @@ -66,6 +66,7 @@ export abstract class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCo declare protected readonly onTerminalProgramStatusFacet: HostServices['onTerminalProgramStatusFacet'] declare protected readonly onTerminalSideEffects: HostServices['onTerminalSideEffects'] declare protected readonly onClaudeTerminalEvidence: HostServices['onClaudeTerminalEvidence'] + declare protected readonly getPaneAgentIdentityFn: HostServices['getPaneAgentIdentityFn'] declare readonly getAgentStatusSnapshotFn: HostServices['getAgentStatusSnapshotFn'] declare protected readonly structuredAgentStatusSinkFn: HostServices['structuredAgentStatusSinkFn'] declare readonly readObservedAgentStatusPaneIdentityFn: HostServices['readObservedAgentStatusPaneIdentityFn'] @@ -258,6 +259,7 @@ export abstract class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCo deps?.getAgentProviderSessionSnapshot ?? deps?.getAgentStatusSnapshot ?? null this.getAgentProviderSessionRowsForSessionFn = deps?.getAgentProviderSessionRowsForSession ?? null + this.getPaneAgentIdentityFn = deps?.getPaneAgentIdentity ?? null this.getAgentProviderSessionRowsForPaneFn = deps?.getAgentProviderSessionRowsForPane ?? null this.getAcceptedAgentReply = deps?.getAcceptedAgentReply ?? (() => undefined) this.subscribeAgentStatusRowChanges = deps?.subscribeAgentStatusRowChanges ?? (() => () => {}) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts new file mode 100644 index 000000000000..0ff4c2589ee5 --- /dev/null +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -0,0 +1,180 @@ +import { describe, expect, it } from 'vitest' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' + +// Preserve side-effect order: mocks, lifecycle, fixtures. +await import('../../orca-runtime-tests/runtime-test-module-registration.spec') +const { OrcaRuntimeService } = await import('../../orca-runtime') +await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec') +const { AgentHookServer } = await import('../../../agent-hooks/server/agent-hook-server') +const { + HEADLESS_LEAF_ID, + TEST_WORKTREE_ID, + TEST_WORKTREE_PATH, + deferred, + makeRuntimeStoreWithWorkspaceSession, + makeWorkspaceSessionWithHeadlessTerminal +} = await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') + +const PANE_KEY = `host-tab:${HEADLESS_LEAF_ID}` + +const OLDER_CHECKPOINT: SleepingAgentSessionRecord = { + paneKey: PANE_KEY, + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + agent: 'claude', + providerSession: { key: 'session_id', id: 'claude-session-1' }, + prompt: 'first conversation', + state: 'done', + capturedAt: 100, + updatedAt: 100, + origin: 'live', + connectionId: null +} + +const NEWER_STATUS: AgentStatusIpcPayload = { + paneKey: PANE_KEY, + state: 'done', + prompt: 'second conversation', + agentType: 'claude', + connectionId: null, + receivedAt: 200, + stateStartedAt: 200, + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + providerSession: { key: 'session_id', id: 'claude-session-2' } +} + +describe('main-run sleep of a pane whose hook row is gone', () => { + it.each([false, true])( + 'uses a saved live conversation unless an exit was recorded (exited=%s)', + async (exited) => { + const fixture = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + sleepingAgentSessionsByPaneKey: { [PANE_KEY]: OLDER_CHECKPOINT } + }) + ) + const server = new AgentHookServer() + if (exited) { + server.reconcileEndedProcessForPaneKeys([PANE_KEY], { + endedPresence: { agent: 'claude', ended: true } + }) + } + const runtime = new OrcaRuntimeService(fixture.runtimeStore, undefined, { + getAgentProviderSessionRowsForPane: () => [], + checkHookAgentPresence: (paneKey, since) => + server.checkAgentPresenceSince(paneKey, since ?? 0) + }) + const live = new Set(['persisted-pty']) + runtime.setPtyController({ + write: () => true, + kill: () => false, + stopAndWait: async (ptyId) => { + live.delete(ptyId) + runtime.onPtyExit(ptyId, -1) + return true + }, + getForegroundProcess: async () => null, + listProcesses: async () => + [...live].map((id) => ({ id, cwd: TEST_WORKTREE_PATH, title: 'claude' })) + }) + runtime.attachWindow(1) + await runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'claude', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'persisted-pty' + } + ] + }) + try { + await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) + const record = fixture.getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY] + if (exited) { + expect(record).toBeUndefined() + } else { + expect(record).toMatchObject({ + origin: 'worktree-sleep', + restoreOnTabOpenOnly: true, + providerSession: { key: 'session_id', id: 'claude-session-1' } + }) + } + } finally { + server.stop() + } + } + ) + + it('captures the checkpoint a status accepted before the sleep wrote, not the one it replaced', async () => { + const fixture = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + sleepingAgentSessionsByPaneKey: { [PANE_KEY]: OLDER_CHECKPOINT } + }) + ) + const statusWriteLands = deferred() + const applyLayoutCommand = fixture.runtimeStore.applyLayoutCommand.getMockImplementation()! + fixture.runtimeStore.applyLayoutCommand.mockImplementationOnce(async (...args) => { + await statusWriteLands.promise + return applyLayoutCommand(...args) + }) + const runtime = new OrcaRuntimeService(fixture.runtimeStore, undefined, { + // The newer status was accepted, then its row went away before the sleep read the store. + getAgentProviderSessionRowsForPane: () => [], + checkHookAgentPresence: async () => null + }) + const processLists = [[{ id: 'persisted-pty', cwd: TEST_WORKTREE_PATH, title: 'claude' }]] + runtime.setPtyController({ + write: () => true, + kill: () => false, + stopAndWait: async (ptyId) => { + runtime.onPtyExit(ptyId, -1) + return true + }, + getForegroundProcess: async () => null, + listProcesses: async () => processLists.shift() ?? [] + }) + runtime.attachWindow(1) + await runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'claude', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'persisted-pty' + } + ] + }) + runtime.recordHookStatusResume(NEWER_STATUS) + + const sleeping = runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) + statusWriteLands.resolve() + await sleeping + + expect(fixture.getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toMatchObject({ + origin: 'worktree-sleep', + providerSession: { key: 'session_id', id: 'claude-session-2' } + }) + }) +}) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index a06e3ae601e9..fd409dea6fe3 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -99,6 +99,8 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu paneKeysByPtyId, launchByPtyId: new Map([...ptyIds].map((ptyId) => [ptyId, this.ptysById.get(ptyId)])), readRowsForPane: (paneKey) => this.getAgentProviderSessionRowsForPaneFn?.(paneKey) ?? [], + readSavedRecord: (paneKey) => this.readSavedResumeSource(worktreeId, paneKey), + readIdentity: (paneKey, savedRecord) => this.readPaneAgentIdentity(paneKey, savedRecord), checkAgentPresence: this.checkHookAgentPresenceFn, capturedAt: Date.now() }) @@ -207,8 +209,22 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu /** A layout-owner build's quit capture of the agents of the panes one partition holds. */ quitResumeRecordsFor(session: WorkspaceSessionState): SleepingAgentSessionRecord[] { - const statuses = (this.getAgentProviderSessionSnapshotFn?.() ?? []).flatMap((row) => { - const status = resumeStatusFromHookRow(row, this.previousHookStatusByPaneKey.get(row.paneKey)) + const paneKeys = new Set([ + ...(this.getAgentProviderSessionSnapshotFn?.() ?? []).map((row) => row.paneKey), + ...Object.keys(session.sleepingAgentSessionsByPaneKey ?? {}) + ]) + const statuses = [...paneKeys].flatMap((paneKey) => { + const identity = this.readPaneAgentIdentity( + paneKey, + session.sleepingAgentSessionsByPaneKey?.[paneKey] + ) + if (!identity || identity.ended) { + return [] + } + const status = resumeStatusFromHookRow( + identity.status, + this.previousHookStatusByPaneKey.get(paneKey) + ) return status ? [status] : [] }) return quitResumeRecords({ diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts index fcdd9485599f..eb73ca334515 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts @@ -1,3 +1,4 @@ +import { paneAgentIdentity } from '../../../agent-hooks/server/pane-agent-identity' import { isResumableTuiAgent, normalizeAgentProviderSession, @@ -41,6 +42,11 @@ export async function captureWorktreeSleepResumeRecords(args: { launchByPtyId: ReadonlyMap /** Read after each presence probe, so a conversation started during it is the one captured. */ readRowsForPane: (paneKey: string) => readonly AgentStatusIpcPayload[] + readSavedRecord?: (paneKey: string) => Promise + readIdentity?: ( + paneKey: string, + savedRecord?: SleepingAgentSessionRecord + ) => ReturnType checkAgentPresence: | ((paneKey: string, exitedSince?: number) => Promise) | null @@ -57,19 +63,31 @@ export async function captureWorktreeSleepResumeRecords(args: { const launch = args.launchByPtyId.get(ptyId) let launchUnknown = false for (const { paneKey, tabId } of panes) { - // Why: the one holder rule — an agent the hook store proved exited left a plain shell. - if ((await args.checkAgentPresence?.(paneKey, 0).catch(() => null)) === 'exited') { + const savedBeforeProbe = await args.readSavedRecord?.(paneKey) + const presence = await args + .checkAgentPresence?.(paneKey, savedBeforeProbe?.updatedAt ?? 0) + .catch(() => null) + const savedRecord = await args.readSavedRecord?.(paneKey) + const identity = args.readIdentity + ? args.readIdentity(paneKey, savedRecord) + : paneAgentIdentity({ + paneKey, + row: args.readRowsForPane(paneKey).find((candidate) => candidate.paneKey === paneKey), + savedRecord, + worktreeId: args.worktreeId, + ended: presence === 'exited' + }) + if (identity?.ended || (presence === 'exited' && !identity?.status.paneSleep)) { retiredPaneKeys.push(paneKey) continue } - const row = args.readRowsForPane(paneKey).find((candidate) => candidate.paneKey === paneKey) + const row = identity?.status const agent = row?.agentType const providerSession = normalizeAgentProviderSession(row?.providerSession) if (!row) { continue } if (!isResumableTuiAgent(agent) || !providerSession) { - // Why: the hook store names another agent here now, so an older capture no longer applies. retiredPaneKeys.push(paneKey) continue } diff --git a/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts b/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts index e7f3881cc560..cdb8d92af5c4 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts @@ -1,3 +1,4 @@ +import { paneAgentIdentity } from '../../../agent-hooks/server/pane-agent-identity' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status/contracts/agent-status-freshness' import { pickHostTurnEnd, @@ -32,8 +33,11 @@ export type RuntimeAgentRowSnapshot = { } function isLiveObservation(row: AgentStatusIpcPayload): boolean { - // Restored rows cannot prove current liveness; resume-identity rows carry no status. - return row.restoredUnconfirmed !== true && row.providerSessionOnly !== true + if (row.structuredHost) { + return row.restoredUnconfirmed !== true + } + const identity = paneAgentIdentity({ paneKey: row.paneKey, row }) + return row.restoredUnconfirmed !== true && identity !== null && !identity.ended } type HookRowJoin = { @@ -52,7 +56,6 @@ function isPermissionState(state: AgentStatusEntry['state']): boolean { function isHeldRestoredPermission(row: AgentStatusIpcPayload, join: HookRowJoin): boolean { return ( row.restoredUnconfirmed === true && - row.providerSessionOnly !== true && isPermissionState(row.state) && join.screenMayHoldDialog?.() === true ) diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-pty-agent-sources.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-pty-agent-sources.ts index 8e480b91215e..ff4d3d1a9e38 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-pty-agent-sources.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-pty-agent-sources.ts @@ -1,3 +1,4 @@ +import { paneAgentIdentity } from '../../../agent-hooks/server/pane-agent-identity' import { pickParsedAgentStatusPayload, type ParsedAgentStatusPayload @@ -49,8 +50,12 @@ export function collectRuntimeWorktreePtyAgentSources(args: { string, RuntimeWorktreeAgentSource & { payload: ParsedAgentStatusPayload } >() - for (const entry of args.hookSnapshots) { - if (entry.restoredUnconfirmed === true || entry.providerSessionOnly === true) { + for (const source of args.hookSnapshots) { + const identity = source.structuredHost + ? null + : paneAgentIdentity({ paneKey: source.paneKey, row: source }) + const entry = source.structuredHost ? source : identity?.status + if (!entry || identity?.ended || entry.restoredUnconfirmed === true) { continue } const hookPayload = pickParsedAgentStatusPayload(entry) diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index 80a6d006c1d3..c5def6133291 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -132,7 +132,17 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven const rowSources = collectRuntimeWorktreeAgentSources({ mirroredWorktreeIdByTabId, connectedPtyEvidence, - hookSnapshots: this.getAgentStatusSnapshotFn?.() ?? [], + hookSnapshots: ( + this.getAgentProviderSessionSnapshotFn?.() ?? + this.getAgentStatusSnapshotFn?.() ?? + [] + ).flatMap((row) => { + if (row.structuredHost) { + return [row] + } + const identity = this.readPaneAgentIdentity(row.paneKey, undefined, row) + return identity && !identity.ended ? [identity.status] : [] + }), readStructuredSummary: getStructuredAgentSessionHost()?.readStatusSummary }) attachRuntimeWorktreeAgentRows({ diff --git a/src/renderer/src/store/slices/agent-status/agent-status-recovery-collection.ts b/src/renderer/src/store/slices/agent-status/agent-status-recovery-collection.ts index d4e0ac71024f..82d365d71ec3 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-recovery-collection.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-recovery-collection.ts @@ -1,7 +1,7 @@ import type { AppState } from '../../types' import { sleepingAgentRecordIndex } from '../../terminals/sleep/sleeping-agent-record-index' import '../../../../../shared/agent-session/lifecycle/agent-session-resume' -import { getAgentResumeArgv } from '../../../../../shared/agent-launch/startup/agent-resume-argv' +import { promoteSavedLiveResumeRecord } from '../../../../../shared/agent-session/lifecycle/resume/promote-saved-live-resume-record' import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' import { paneKeyMatchesAnyTabPrefix } from './agent-status-pane-key-tab-binding' import { @@ -41,23 +41,17 @@ export function collectSleepingAgentSessionRecordsForWorktree( )) { const liveEntry = state.agentStatusByPaneKey.get(existing.paneKey) if ( - existing.worktreeId !== worktreeId || - existing.origin !== 'live' || (liveEntry !== undefined && !isCompletedPiCompatibleAgentWithLiveRecoveryRecord(liveEntry, existing)) || - (allowedPaneKeys && !allowedPaneKeys.has(existing.paneKey)) || - !getAgentResumeArgv(existing.agent, existing.providerSession) + (allowedPaneKeys && !allowedPaneKeys.has(existing.paneKey)) ) { continue } - // Pi resumes without turn status and while done/idle; manual sleep must promote these checkpoints too. - records[existing.paneKey] = { - ...existing, - state: 'working', - capturedAt, - updatedAt: capturedAt, - origin: 'worktree-sleep' + const promoted = promoteSavedLiveResumeRecord({ record: existing, worktreeId, capturedAt }) + if (!promoted) { + continue } + records[existing.paneKey] = promoted promotedLiveRecoveryPaneKeys.add(existing.paneKey) } } diff --git a/src/shared/agent-session/lifecycle/resume/promote-saved-live-resume-record.ts b/src/shared/agent-session/lifecycle/resume/promote-saved-live-resume-record.ts new file mode 100644 index 000000000000..6b074603d2ee --- /dev/null +++ b/src/shared/agent-session/lifecycle/resume/promote-saved-live-resume-record.ts @@ -0,0 +1,27 @@ +import { getAgentResumeArgv } from '../../../agent-launch/startup/agent-resume-argv' +import { isResumableTuiAgent, type SleepingAgentSessionRecord } from '../agent-session-resume' + +/** Promote the pane's live checkpoint when its volatile status is missing. */ +export function promoteSavedLiveResumeRecord(args: { + record: SleepingAgentSessionRecord | undefined + worktreeId: string + capturedAt: number +}): SleepingAgentSessionRecord | null { + const { record, worktreeId, capturedAt } = args + if ( + !record || + record.worktreeId !== worktreeId || + record.origin !== 'live' || + !isResumableTuiAgent(record.agent) || + !getAgentResumeArgv(record.agent, record.providerSession) + ) { + return null + } + return { + ...record, + state: 'working', + capturedAt, + updatedAt: capturedAt, + origin: 'worktree-sleep' + } +} From 232e5a5c4f3314e446d665a320a796ded6eb8836 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:22:37 -0800 Subject: [PATCH 005/125] Read canonical pane identity and preserve saved turn verdicts --- .../agent-hooks/server/pane-agent-identity.ts | 5 ++++- .../agent-hooks/server/server-ingest-terminal.ts | 1 + src/main/agent-hooks/server/server-pane-sleep.ts | 16 +++++++++++++--- src/main/agent-hooks/server/server-state.ts | 6 +++--- .../persistence/server-pane-sleep.test.ts | 7 ++++++- .../testing/tmux/server-tmux-canonical.test.ts | 4 ++++ 6 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/main/agent-hooks/server/pane-agent-identity.ts b/src/main/agent-hooks/server/pane-agent-identity.ts index 1b41b3351530..f61c61f48a5f 100644 --- a/src/main/agent-hooks/server/pane-agent-identity.ts +++ b/src/main/agent-hooks/server/pane-agent-identity.ts @@ -32,7 +32,7 @@ export function paneAgentIdentity(args: { ...placeholder } = row const status: AgentStatusIpcPayload = row.providerSessionOnly - ? { ...placeholder, state: 'done' } + ? { ...placeholder, state: 'done', sessionBoundary: true } : row // Sleep is a resumable physical stop: its exit retires the process, never the conversation. if (row.paneSleep) { @@ -62,6 +62,9 @@ export function paneAgentIdentity(args: { stateStartedAt: saved.updatedAt, providerSession: promoted.providerSession, state: 'done', + ...(saved.state === 'done' ? {} : { sessionBoundary: true }), + ...(saved.interrupted !== undefined ? { interrupted: saved.interrupted } : {}), + ...(saved.mainAgent ? { mainAgent: saved.mainAgent } : {}), prompt: promoted.prompt, agentType: promoted.agent, ...(promoted.lastAssistantMessage diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index 8ab9cce052a5..c8b73a4c9e63 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -29,6 +29,7 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges const previous = this.state.lastStatusByPaneKey.get(paneKey) if ( previous && + !previous.agentPresence?.ended && ((previous.payload.agentType === event.agentType && agentProviderSessionsEqual( event.agentType, diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index b75a5e5155cb..15c0e3cad5f4 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -72,11 +72,17 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF const resolved = this.resolvePaneKeyAlias(paneKey) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. const identity = this.paneAgentIdentity(resolved) - const previous = + const previous: EnrichedAgentHookEventPayload | undefined = (this.state.lastStatusByPaneKey.get(resolved) as EnrichedAgentHookEventPayload | undefined) ?? (identity ? { - ...identity.status, + paneKey: resolved, + tabId: identity.status.tabId, + worktreeId: identity.status.worktreeId, + connectionId: identity.status.connectionId, + receivedAt: identity.status.receivedAt, + stateStartedAt: identity.status.stateStartedAt, + providerSession: identity.status.providerSession, payload: pickParsedAgentStatusPayload(identity.status) } : undefined) @@ -141,7 +147,11 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF } : {}) } - : { ...payload, state: identity.status.state }, + : { + ...payload, + state: identity.status.state, + ...(identity.status.sessionBoundary ? { sessionBoundary: true } : {}) + }, paneSleep: { ptyId, ...(incarnationId ? { incarnationId } : {}) }, agentPresence: { agent: previous.payload.agentType ?? 'unknown', diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 7a04f08681a2..07219adba95f 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -70,9 +70,9 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract ): PaneAgentIdentity | null { const resolved = this.resolvePaneKeyAlias(paneKey) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. - const row = this.state.lastStatusByPaneKey.get(resolved) as - | EnrichedAgentHookEventPayload - | undefined + const row = + (this.state.lastStatusByPaneKey.get(resolved) as EnrichedAgentHookEventPayload | undefined) ?? + this.getTmuxSelectedStatus(resolved) if (!row) { savedRecord ??= this.terminalPaneLifecycle?.readSavedRecord?.(resolved) } diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 20b95db3dba9..37d5816a7cf6 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -307,7 +307,12 @@ it.each(['claude', 'codex'] as const)( } await sleepPane(agent, 'pty-1', 4001) expect(server.paneAgentIdentity(PANE)).toMatchObject({ - status: { agentType: agent, state: 'done', paneSleep: { ptyId: 'pty-1' } }, + status: { + agentType: agent, + state: 'done', + sessionBoundary: true, + paneSleep: { ptyId: 'pty-1' } + }, ended: false }) } diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts index 7ff17f525818..dec8abff46ff 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts @@ -33,6 +33,10 @@ describe('main canonical tmux projection', () => { it('publishes one canonical outer row, blocks legacy overwrites, and cleans the exact outer and inner subjects', async () => { expect((await postHookEvent(server, tmuxTestBody(), '/hook/opencode')).status).toBe(204) expect(server.hasLegacyRow()).toBe(false) + expect(server.paneAgentIdentity(TMUX_TEST_PANE)).toMatchObject({ + status: { paneKey: TMUX_TEST_PANE, state: 'done' }, + ended: false + }) expect( server.attestCompatibilityAuthority({ paneKey: TMUX_TEST_PANE, From 15993dc0938d83acbdd4cc47e93ab4d375b9c398 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:24:19 -0800 Subject: [PATCH 006/125] Retire exited pane recovery before exit evidence expires --- src/main/agent-hooks/server/server-cleanup.ts | 6 +++- src/main/agent-hooks/server/server-state.ts | 1 + .../pane/terminal-pane-status-lifecycle.ts | 1 + .../worktree-sleep-resume-recording.test.ts | 31 +++++++++++++------ .../stop/worktree-sleep-resume-recording.ts | 24 ++++++++++++++ 5 files changed, 53 insertions(+), 10 deletions(-) diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 8e03e0d2cfff..a7416c7f0513 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -143,7 +143,11 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { paneKeys.add(aliasKey) } } - recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, endedPresence) + const exitedAt = Date.now() + recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, endedPresence, exitedAt) + for (const key of paneKeys) { + this.terminalPaneLifecycle?.retireSavedRecord?.(key, exitedAt) + } this.scheduleStatusPersist() } if (!this.hasLiveClaimsForPaneKey(resolvedPaneKey)) { diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 37125976444c..0af132b078c6 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -49,6 +49,7 @@ import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/l export abstract class AgentHookServerState extends AgentHookServerStateContract { protected terminalPaneLifecycle: { + retireSavedRecord?(paneKey: string, exitedAt: number): void readSavedRecord?(paneKey: string): SleepingAgentSessionRecord | undefined ownsProcess(paneKey: string, ptyId: string, incarnationId?: string): boolean isStopping(paneKey: string): boolean diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index a4783469d96f..b9446f2193af 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -13,6 +13,7 @@ export function bindTerminalPaneStatusLifecycle( store: Store | undefined ): void { agentHookServer.setTerminalPaneLifecycle({ + retireSavedRecord: (paneKey, exitedAt) => runtime?.retireExitedPaneResume(paneKey, exitedAt), readSavedRecord: (paneKey) => { try { const pane = runtime?.resolveTerminalPane(paneKey) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 0ff4c2589ee5..bd3069656c5f 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -46,21 +46,18 @@ const NEWER_STATUS: AgentStatusIpcPayload = { } describe('main-run sleep of a pane whose hook row is gone', () => { - it.each([false, true])( - 'uses a saved live conversation unless an exit was recorded (exited=%s)', - async (exited) => { + it.each(['live', 'exited', 'expired exit'] as const)( + 'uses a saved live conversation unless an exit was recorded (%s)', + async (scenario) => { const fixture = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ sleepingAgentSessionsByPaneKey: { [PANE_KEY]: OLDER_CHECKPOINT } }) ) const server = new AgentHookServer() - if (exited) { - server.reconcileEndedProcessForPaneKeys([PANE_KEY], { - endedPresence: { agent: 'claude', ended: true } - }) - } const runtime = new OrcaRuntimeService(fixture.runtimeStore, undefined, { + getPaneAgentIdentity: (paneKey, savedRecord) => + server.paneAgentIdentity(paneKey, savedRecord), getAgentProviderSessionRowsForPane: () => [], checkHookAgentPresence: (paneKey, since) => server.checkAgentPresenceSince(paneKey, since ?? 0) @@ -99,10 +96,26 @@ describe('main-run sleep of a pane whose hook row is gone', () => { } ] }) + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => false, + isPlaced: () => true, + retireSavedRecord: (paneKey, at) => runtime.retireExitedPaneResume(paneKey, at) + }) + if (scenario !== 'live') { + server.reconcileEndedProcessForPaneKeys([PANE_KEY], { + endedPresence: { agent: 'claude', ended: true } + }) + if (scenario === 'expired exit') { + // Exit evidence can expire after a week; the saved checkpoint must already be retired. + server.forgetAgentExit(PANE_KEY) + } + } try { await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) const record = fixture.getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY] - if (exited) { + if (scenario !== 'live') { expect(record).toBeUndefined() } else { expect(record).toMatchObject({ diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index fd409dea6fe3..a9f8f953fca3 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -41,6 +41,30 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu ) } + /** A confirmed quit retires recovery durably before its exit evidence can expire. */ + retireExitedPaneResume(paneKey: string, exitedAt: number): void { + const worktreeId = this.getTerminalWorktreeIdForPaneKey(paneKey) + if (!worktreeId) { + return + } + this.inResumeRecordOrder(() => + this.commitWorkspaceSessionEdit( + this.getWorkspaceSessionHostIdForWorktree(worktreeId), + (session) => { + const saved = session.sleepingAgentSessionsByPaneKey?.[paneKey] + if (!saved || saved.updatedAt > exitedAt) { + return null + } + const { [paneKey]: _exited, ...kept } = session.sleepingAgentSessionsByPaneKey ?? {} + return { ...session, sleepingAgentSessionsByPaneKey: kept } + } + ) + ).catch((error) => + console.warn('[runtime] could not retire an exited agent resume record', error) + ) + this.previousHookStatusByPaneKey.delete(paneKey) + } + /** Forgets a pane's saved resume the host refused because a chat is its conversation's home, * as a window does for its own panes; a host with no window has no one else to. */ async forgetRefusedSavedResume( From 86f46123688c2352c37922002261fa84b60d1a80 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:36:12 -0800 Subject: [PATCH 007/125] Complete canonical sleep settlement and skip empty recovery edits --- src/main/agent-hooks/server/server-cleanup.ts | 9 ++++++-- .../agent-hooks/server/server-pane-sleep.ts | 23 ++++++++++++------- src/main/agent-hooks/server/server-state.ts | 2 +- .../tmux/server-tmux-canonical.test.ts | 15 ++++++++++++ .../worktree-sleep-resume-recording.test.ts | 19 +++++++++++++-- .../stop/worktree-sleep-resume-recording.ts | 12 +++++++--- 6 files changed, 64 insertions(+), 16 deletions(-) diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index a7416c7f0513..4c40183f732d 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -132,8 +132,13 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { const endedPresence = options?.endedPresence ?? // A proved process gets its exit from the presence probe, not a possibly newer row. - (options?.confirmedExit && previous && !previous.agentPresence?.process - ? endedPresenceOf(previous) + (options?.confirmedExit && !previous?.agentPresence?.process + ? previous + ? endedPresenceOf(previous) + : { + agent: this.paneAgentIdentity(resolvedPaneKey)?.status.agentType ?? 'unknown', + ended: true + } : undefined) if (endedPresence) { // Cleanup drops aliases, but readers may still hold either key. diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index 0ac4c58d76be..e6e248822d24 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -8,7 +8,7 @@ import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../../shared/agent-sta import { pickParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' import type { EnrichedAgentHookEventPayload } from './server-types' import { AgentHookServerAuthorityFences } from './server-authority-fences' -import { recordAgentExit } from './agent-exit-evidence' +import { endedPresenceOf, recordAgentExit } from './agent-exit-evidence' import type { LaunchResumeIdentityEvent } from './launch-resume-identity-event' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' @@ -47,8 +47,9 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF paneSleep: _paneSleep, agentPresence: _presence, terminalHandle: _handle, - ...rest + ...accepted } = row + const rest = { ...accepted, evidenceObservedAt: Date.now() } admitLegacyAgentStatus( this.state, 'main-status-cleanup', @@ -74,6 +75,7 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF const identity = this.paneAgentIdentity(resolved) const previous: EnrichedAgentHookEventPayload | undefined = (this.state.lastStatusByPaneKey.get(resolved) as EnrichedAgentHookEventPayload | undefined) ?? + this.getTmuxSelectedStatus(resolved) ?? (identity ? { paneKey: resolved, @@ -161,12 +163,17 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF } this.programStatusFacets.delete(resolved) this.hookSilenceRechecks.cancel(resolved) - admitLegacyAgentStatus( - this.state, - 'main-status-cleanup', - row, - AGENT_STATUS_2A_CURRENT_PRODUCER_MODE - ) + this.clearTmuxInnerSubjects(resolved) + if ( + !admitLegacyAgentStatus( + this.state, + 'main-status-cleanup', + row, + AGENT_STATUS_2A_CURRENT_PRODUCER_MODE + ) + ) { + return false + } recordAgentExit(this.agentExitedAtByPaneKey, [resolved], row.agentPresence, now) this.commitStatusRowMutation(previous, row) this.scheduleStatusPersist() diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 0af132b078c6..377fad1967dc 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -82,7 +82,7 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract this.agentExitedAtByPaneKey.get(resolved) ?? this.agentExitedAtByPaneKey.get(paneKey) return paneAgentIdentity({ paneKey: resolved, - ...(row ? { row: toAgentStatusIpcPayload(row) } : {}), + ...(row ? { row: toAgentStatusIpcPayload(this.programStatusFacets.stitch(row)) } : {}), ...(savedRecord ? { savedRecord } : {}), ...(worktreeId ? { worktreeId } : {}), ...(exit ? { exitedAt: exit.at } : {}), diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts index dec8abff46ff..49376d262466 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts @@ -58,6 +58,21 @@ describe('main canonical tmux projection', () => { expect(server.getCanonicalStatusSnapshot().parents).toHaveLength(0) expect(server.getStatusSnapshot()).toHaveLength(0) }) + it('keeps one sleeping row when the canonical selected agent stops with its pane', async () => { + await postHookEvent(server, tmuxTestBody(), '/hook/opencode') + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => true, + isReversibleStop: () => true, + isPlaced: () => true + }) + expect(server.settleTerminalPaneSleep(TMUX_TEST_PANE, 'pty', 'birth')).toBe(true) + server.reconcileEndedProcessForPaneKeys([TMUX_TEST_PANE]) + expect(server.getStatusSnapshot()).toMatchObject([ + { paneKey: TMUX_TEST_PANE, state: 'done', paneSleep: { ptyId: 'pty' } } + ]) + expect(server.getStatusSnapshot()).toHaveLength(1) + }) it('removes canonical tmux status on certified retirement', async () => { await postHookEvent(server, tmuxTestBody(), '/hook/opencode') server.retirePaneAuthority(TMUX_TEST_PANE) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index bd3069656c5f..1ea802921f46 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' @@ -105,7 +105,7 @@ describe('main-run sleep of a pane whose hook row is gone', () => { }) if (scenario !== 'live') { server.reconcileEndedProcessForPaneKeys([PANE_KEY], { - endedPresence: { agent: 'claude', ended: true } + confirmedExit: true }) if (scenario === 'expired exit') { // Exit evidence can expire after a week; the saved checkpoint must already be retired. @@ -191,3 +191,18 @@ describe('main-run sleep of a pane whose hook row is gone', () => { }) }) }) + +it.each([100, 1000])( + 'skips durable session transactions for %s exits without recovery records', + async (count) => { + const fixture = makeRuntimeStoreWithWorkspaceSession(makeWorkspaceSessionWithHeadlessTerminal()) + const runtime = new OrcaRuntimeService(fixture.runtimeStore) + vi.spyOn(runtime, 'getTerminalWorktreeIdForPaneKey').mockReturnValue(TEST_WORKTREE_ID) + fixture.runtimeStore.runDurableMutation.mockClear() + for (let i = 0; i < count; i++) { + runtime.retireExitedPaneResume(`absent-tab-${i}:11111111-1111-4111-8111-111111111111`, 200) + } + await runtime.readSavedResumeSource(TEST_WORKTREE_ID, PANE_KEY) + expect(fixture.runtimeStore.runDurableMutation).not.toHaveBeenCalled() + } +) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index a9f8f953fca3..4df79612a26a 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -47,8 +47,14 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu if (!worktreeId) { return } - this.inResumeRecordOrder(() => - this.commitWorkspaceSessionEdit( + this.inResumeRecordOrder(() => { + const hostId = this.getWorkspaceSessionHostIdForWorktree(worktreeId) + const existing = + this.store?.getWorkspaceSession?.(hostId)?.sleepingAgentSessionsByPaneKey?.[paneKey] + if (!existing || existing.updatedAt > exitedAt) { + return Promise.resolve() + } + return this.commitWorkspaceSessionEdit( this.getWorkspaceSessionHostIdForWorktree(worktreeId), (session) => { const saved = session.sleepingAgentSessionsByPaneKey?.[paneKey] @@ -59,7 +65,7 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu return { ...session, sleepingAgentSessionsByPaneKey: kept } } ) - ).catch((error) => + }).catch((error) => console.warn('[runtime] could not retire an exited agent resume record', error) ) this.previousHookStatusByPaneKey.delete(paneKey) From 53d80c77a15ed785012bab22f6e1f93f9e506c0a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:03:08 -0800 Subject: [PATCH 008/125] Keep wake continuity scoped to resume boundaries and satisfy source gates --- .../server/pane-agent-turn-continuity.ts | 44 ++++++++++++++ src/main/agent-hooks/server/server-cleanup.ts | 16 +----- .../server/server-ingest-terminal.ts | 10 ++-- .../agent-hooks/server/server-pane-sleep.ts | 5 +- .../server/server-state-contract.ts | 3 + src/main/agent-hooks/server/server-state.ts | 25 ++++++-- .../server/server-status-row-mutation.ts | 20 +++++++ .../server/server-status-update.ts | 57 +++---------------- .../runtime-agent-status-sources.ts | 20 ++++++- .../runtime-construction-dependencies.ts | 6 +- .../workspace-process-listing.ts | 12 +--- 11 files changed, 128 insertions(+), 90 deletions(-) create mode 100644 src/main/agent-hooks/server/pane-agent-turn-continuity.ts diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts new file mode 100644 index 000000000000..d0a3a811f8f5 --- /dev/null +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -0,0 +1,44 @@ +import type { EnrichedAgentHookEventPayload } from './server-types' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' +import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' + +/** A boundary for the conversation whose turn the pane last accepted keeps that turn's verdict. */ +export function resumedAcceptedTurn( + previous: EnrichedAgentHookEventPayload, + incoming: AgentHookEventPayload +): EnrichedAgentHookEventPayload | null { + const continuesTurn = + incoming.payload.agentType === 'claude' && + incoming.payload.sessionBoundary === true && + previous.payload.state === 'done' && + previous.payload.sessionBoundary !== true && + previous.providerSessionOnly !== true && + previous.paneSleep === undefined && + previous.providerSession !== undefined && + previous.payload.agentType === incoming.payload.agentType && + sameAgentStatusTerminalOwner(previous, incoming) && + agentProviderSessionsEqual( + incoming.payload.agentType, + previous.providerSession, + incoming.providerSession + ) + if (!continuesTurn) { + return null + } + const { agentPresence: _sleptOwner, restoredUnconfirmed: _restored, ...accepted } = previous + return { + ...accepted, + ...(incoming.providerSession ? { providerSession: incoming.providerSession } : {}), + ...(incoming.agentPresence ? { agentPresence: incoming.agentPresence } : {}) + } +} + +export function resolvedHookAgentType( + row: T, + agentType: AgentHookEventPayload['payload']['agentType'] +): T { + return row.payload.agentType === agentType + ? row + : { ...row, payload: { ...row.payload, agentType } } +} diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 4c40183f732d..7080efcb2cb2 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -16,7 +16,7 @@ import { worktreeIdsEqual } from '../../../shared/worktree/id' import { isLocalHookConnectionId } from '../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import type { EnrichedAgentHookEventPayload } from './server-types' -import { endedPresenceOf, recordAgentExit } from './agent-exit-evidence' +import { endedPresenceOf } from './agent-exit-evidence' export type EndedProcessReconciliationOptions = { endedPresence?: AgentProcessPresence @@ -141,19 +141,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { } : undefined) if (endedPresence) { - // Cleanup drops aliases, but readers may still hold either key. - const paneKeys = new Set([resolvedPaneKey, paneKey]) - for (const [aliasKey, alias] of this.legacyPaneKeyAliases) { - if (alias.stablePaneKey === resolvedPaneKey) { - paneKeys.add(aliasKey) - } - } - const exitedAt = Date.now() - recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, endedPresence, exitedAt) - for (const key of paneKeys) { - this.terminalPaneLifecycle?.retireSavedRecord?.(key, exitedAt) - } - this.scheduleStatusPersist() + this.recordPaneAgentExit(paneKey, endedPresence) } if (!this.hasLiveClaimsForPaneKey(resolvedPaneKey)) { untouched.push(resolvedPaneKey) diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index 9f7537559b0e..28aada4b63b4 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -28,15 +28,13 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges } this.forgetAgentExitBefore(paneKey, event.launchedAt) const previous = this.state.lastStatusByPaneKey.get(paneKey) + const sameConversation = + previous?.payload.agentType === event.agentType && + agentProviderSessionsEqual(event.agentType, previous?.providerSession, event.providerSession) if ( previous && !previous.agentPresence?.ended && - ((previous.payload.agentType === event.agentType && - agentProviderSessionsEqual( - event.agentType, - previous.providerSession, - event.providerSession - )) || + (sameConversation || (previous.providerSessionOnly !== true && 'receivedAt' in previous && typeof previous.receivedAt === 'number' && diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index e6e248822d24..4eabb48c45e8 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -72,9 +72,12 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF settleTerminalPaneSleep(paneKey: string, ptyId: string, incarnationId?: string): boolean { const resolved = this.resolvePaneKeyAlias(paneKey) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. + const legacy = this.state.lastStatusByPaneKey.get(resolved) as + | EnrichedAgentHookEventPayload + | undefined const identity = this.paneAgentIdentity(resolved) const previous: EnrichedAgentHookEventPayload | undefined = - (this.state.lastStatusByPaneKey.get(resolved) as EnrichedAgentHookEventPayload | undefined) ?? + legacy ?? this.getTmuxSelectedStatus(resolved) ?? (identity ? { diff --git a/src/main/agent-hooks/server/server-state-contract.ts b/src/main/agent-hooks/server/server-state-contract.ts index b2606f79f84b..31021b1e5a86 100644 --- a/src/main/agent-hooks/server/server-state-contract.ts +++ b/src/main/agent-hooks/server/server-state-contract.ts @@ -29,7 +29,10 @@ import type { import type { LastStatusStore } from './last-status-store' +import type { ProgramStatusFacetStore } from './program-status/facet-store' + export abstract class AgentHookServerStateContract { + protected abstract readonly programStatusFacets: ProgramStatusFacetStore protected abstract state: HookListenerState protected abstract withdrawReplayObservation(paneKey: string): void diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 377fad1967dc..2600e8d6cbbf 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -42,9 +42,10 @@ import type { StatusRowMutationListener } from './server-types' import { RevisionedMap } from './revisioned-map' -import { forgetAgentExit, type AgentExitEvidence } from './agent-exit-evidence' +import { recordAgentExit, forgetAgentExit, type AgentExitEvidence } from './agent-exit-evidence' import { paneAgentIdentity, type PaneAgentIdentity } from './pane-agent-identity' import { toAgentStatusIpcPayload } from './server-status-identity' +import type { AgentProcessPresence } from '../../../shared/agent-status/process/agent-process-presence' import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' export abstract class AgentHookServerState extends AgentHookServerStateContract { @@ -71,9 +72,10 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract ): PaneAgentIdentity | null { const resolved = this.resolvePaneKeyAlias(paneKey) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. - const row = - (this.state.lastStatusByPaneKey.get(resolved) as EnrichedAgentHookEventPayload | undefined) ?? - this.getTmuxSelectedStatus(resolved) + const legacy = this.state.lastStatusByPaneKey.get(resolved) as + | EnrichedAgentHookEventPayload + | undefined + const row = legacy ?? this.getTmuxSelectedStatus(resolved) if (!row) { savedRecord ??= this.terminalPaneLifecycle?.readSavedRecord?.(resolved) } @@ -90,6 +92,21 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract }) } + protected recordPaneAgentExit(paneKey: string, endedPresence: AgentProcessPresence): void { + const paneKeys = new Set([this.resolvePaneKeyAlias(paneKey), paneKey]) + for (const [aliasKey, alias] of this.legacyPaneKeyAliases) { + if (alias.stablePaneKey === this.resolvePaneKeyAlias(paneKey)) { + paneKeys.add(aliasKey) + } + } + const exitedAt = Date.now() + recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, endedPresence, exitedAt) + for (const key of paneKeys) { + this.terminalPaneLifecycle?.retireSavedRecord?.(key, exitedAt) + } + this.scheduleStatusPersist() + } + /** A stopping pane's agent keeps its row for the sleep gate, whatever shape it rests in. */ protected preservesStoppingAgent(paneKey: string): boolean { const identity = this.paneAgentIdentity(paneKey) diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index 7a8ccc1f57d0..5404caa0e4b7 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -1,3 +1,5 @@ +import { resumedAcceptedTurn } from './pane-agent-turn-continuity' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import { RelaySessionGenerations } from './server-relay-sessions' import type { EnrichedAgentHookEventPayload } from './server-types' @@ -7,6 +9,24 @@ import { ClaudeOwedNotificationExpiryTimers } from '../../../shared/agent-hook-l import { AgentHookServerStatusApplication } from './server-status-application' export abstract class AgentHookServerStatusRowMutation extends AgentHookServerStatusApplication { + protected preserveResumedAcceptedTurn( + previous: EnrichedAgentHookEventPayload | undefined, + incoming: AgentHookEventPayload, + before: EnrichedAgentHookEventPayload | undefined + ): EnrichedAgentHookEventPayload | null | undefined { + const resumed = previous && resumedAcceptedTurn(previous, incoming) + if (!resumed) { + return null + } + if (!this.writeLegacyStatusRow(resumed)) { + return undefined + } + this.runtimeObservedStatusPaneKeys.add(resumed.paneKey) + this.commitStatusRowMutation(before, resumed) + this.scheduleStatusPersist() + return resumed + } + protected readonly claudeOwedNotificationExpiry = new ClaudeOwedNotificationExpiryTimers( this.state ) diff --git a/src/main/agent-hooks/server/server-status-update.ts b/src/main/agent-hooks/server/server-status-update.ts index 6a19d83eefcd..39366f40ca2a 100644 --- a/src/main/agent-hooks/server/server-status-update.ts +++ b/src/main/agent-hooks/server/server-status-update.ts @@ -27,31 +27,7 @@ import { isForeignTurnHook } from './server-foreign-turn-hook' import { resolveCancelVerdictLatch } from '../../../shared/agent-hook-listener/state/agent-hook-cancel-verdict-latch' import { claimsPaneAfterExit } from './agent-exit-evidence' -import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' -import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' -import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' - -/** A boundary for the conversation whose turn the pane last accepted keeps that turn's verdict. */ -function resumesAcceptedDone( - previous: EnrichedAgentHookEventPayload, - incoming: AgentHookEventPayload -): boolean { - return ( - incoming.payload.sessionBoundary === true && - previous.payload.state === 'done' && - previous.payload.sessionBoundary !== true && - previous.providerSessionOnly !== true && - previous.paneSleep === undefined && - previous.providerSession !== undefined && - previous.payload.agentType === incoming.payload.agentType && - sameAgentStatusTerminalOwner(previous, incoming) && - agentProviderSessionsEqual( - incoming.payload.agentType, - previous.providerSession, - incoming.providerSession - ) - ) -} +import { resolvedHookAgentType } from './pane-agent-turn-continuity' export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusRowMutation { protected applyNormalizedStatus( @@ -220,24 +196,8 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusR if (previous && stateReconciledPayload === previous) { return previous } - if (previous && resumesAcceptedDone(previous, stateReconciledPayload)) { - // The resumed process owns the conversation's last verdict; the slept one's identity stays behind. - const { agentPresence: _sleptOwner, restoredUnconfirmed: _restored, ...accepted } = previous - const resumed: EnrichedAgentHookEventPayload = { - ...accepted, - ...(stateReconciledPayload.providerSession - ? { providerSession: stateReconciledPayload.providerSession } - : {}), - ...(stateReconciledPayload.agentPresence - ? { agentPresence: stateReconciledPayload.agentPresence } - : {}) - } - if (!this.writeLegacyStatusRow(resumed)) { - return undefined - } - this.runtimeObservedStatusPaneKeys.add(resumed.paneKey) - this.commitStatusRowMutation(rowBefore, resumed) - this.scheduleStatusPersist() + const resumed = this.preserveResumedAcceptedTurn(previous, stateReconciledPayload, rowBefore) + if (resumed !== null) { return resumed } // Relay restart loses root context; child hooks must not erase persisted resume/model identity. @@ -248,13 +208,10 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusR !!previous && this.sameTerminalOwner(previous, stateReconciledPayload), rootContext.returningProviderSession ) - const identityResolvedPayload = - identity.agentType === rootContextPreservingPayload.payload.agentType - ? rootContextPreservingPayload - : { - ...rootContextPreservingPayload, - payload: { ...rootContextPreservingPayload.payload, agentType: identity.agentType } - } + const identityResolvedPayload = resolvedHookAgentType( + rootContextPreservingPayload, + identity.agentType + ) const attachedPayload = attachClaudePermissionToolUseId(previous, identityResolvedPayload) // Resolve cancellation before permission holds adopt a replayed main-agent observation. const latch = resolveCancelVerdictLatch(previous, attachedPayload, Date.now()) diff --git a/src/main/runtime/construction/runtime-agent-status-sources.ts b/src/main/runtime/construction/runtime-agent-status-sources.ts index ffed2c479acd..fdfe6a6202b6 100644 --- a/src/main/runtime/construction/runtime-agent-status-sources.ts +++ b/src/main/runtime/construction/runtime-agent-status-sources.ts @@ -1,6 +1,8 @@ import { paneAgentIdentity } from '../../agent-hooks/server/pane-agent-identity' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { AgentProviderSessionMetadata } from '../../../shared/agent-session/lifecycle/agent-session-resume' +import type { + SleepingAgentSessionRecord, + AgentProviderSessionMetadata +} from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { RuntimeConstructionBindings as HostBindings } from './runtime-construction-dependencies' @@ -30,6 +32,20 @@ export abstract class RuntimeAgentStatusSources extends OrcaRuntimeWithTerminalD }) } + protected paneAgentStatuses( + rows: readonly AgentStatusIpcPayload[] = this.getAgentProviderSessionSnapshotFn?.() ?? + this.getAgentStatusSnapshotFn?.() ?? + [] + ): AgentStatusIpcPayload[] { + return rows.flatMap((row) => { + if (row.structuredHost) { + return [row] + } + const identity = this.readPaneAgentIdentity(row.paneKey, undefined, row) + return identity && !identity.ended ? [identity.status] : [] + }) + } + readonly getAgentStatusSnapshotFn!: HostBindings['getAgentStatusSnapshot'] | null protected readonly structuredAgentStatusSinkFn!: HostBindings['structuredAgentStatusSink'] | null diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 5ff35aa7be05..9c7a9fccd175 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -1,6 +1,8 @@ import type { paneAgentIdentity } from '../../agent-hooks/server/pane-agent-identity' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { AgentProviderSessionMetadata } from '../../../shared/agent-session/lifecycle/agent-session-resume' +import type { + SleepingAgentSessionRecord, + AgentProviderSessionMetadata +} from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { CliWriterObservation } from '../../agent-hooks/server/cli-writer-observation' import type { ExecutionHostScope } from '../../../shared/execution-host' import type { IPtyProvider } from '../../providers/pty/provider-contract' diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index c5def6133291..cf74b1692b42 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -132,17 +132,7 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven const rowSources = collectRuntimeWorktreeAgentSources({ mirroredWorktreeIdByTabId, connectedPtyEvidence, - hookSnapshots: ( - this.getAgentProviderSessionSnapshotFn?.() ?? - this.getAgentStatusSnapshotFn?.() ?? - [] - ).flatMap((row) => { - if (row.structuredHost) { - return [row] - } - const identity = this.readPaneAgentIdentity(row.paneKey, undefined, row) - return identity && !identity.ended ? [identity.status] : [] - }), + hookSnapshots: this.paneAgentStatuses(), readStructuredSummary: getStructuredAgentSessionHost()?.readStatusSummary }) attachRuntimeWorktreeAgentRows({ From 1ea5808a3c1ebdd2a28d7ffe0f38f1b601728dc3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:15:53 -0800 Subject: [PATCH 009/125] fix(agent-hooks): record the exit when main sees the launched agent's command finish QA showed main's own command-finished retirement clears a hookless Codex's row before the renderer's shell-return reconcile lands, so neither recorded an exit. Pass confirmedExit through that path (command finish only, not PTY exit). --- src/main/agent-hooks/server/server-tab-cleanup.ts | 7 +++++-- .../server/testing/persistence/server-pane-sleep.test.ts | 7 ++----- .../construction/runtime-construction-dependencies.ts | 5 ++++- .../terminal/output/terminal-orchestration-authority.ts | 5 +++-- src/main/runtime/terminal/output/terminal-title-tracker.ts | 2 +- .../runtime/terminal/output/terminal-transient-facts.ts | 4 ++-- .../runtime-startup/main-process-runtime-service.ts | 4 ++-- 7 files changed, 19 insertions(+), 15 deletions(-) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index c493a742da7d..37b4b50ede31 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -14,9 +14,12 @@ import type { import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { - retireProcessAuthority(paneKey: string): void { + retireProcessAuthority( + paneKey: string, + options?: Pick + ): void { const { paneKeys, authorityChanged } = this.revokeProcessAuthority(paneKey) - const { untouched } = this.reconcileEndedProcess(paneKeys, undefined, (key) => + const { untouched } = this.reconcileEndedProcess(paneKeys, options, (key) => this.clearRevokedPaneState(key) ) for (const key of untouched) { diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 434d430f7711..57780bc849e2 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -258,11 +258,8 @@ it('retires a hookless resumed Codex quit to its shell, and keeps a later relaun vi.useFakeTimers({ toFake: ['Date'] }) launch() vi.setSystemTime(Date.now() + 1000) - // The renderer's confirmed shell return, as the IPC handler reconciles it. - server.reconcileEndedProcessForPaneKeys([PANE], { - preserveResumeIdentity: true, - confirmedExit: true - }) + // The launched command's shell-confirmed finish, which clears the pane's row. + server.retireProcessAuthority(PANE, { confirmedExit: true }) expect((await sleep()).sleepingAgentSessionsByPaneKey?.[PANE]).toBeUndefined() vi.setSystemTime(Date.now() + 1000) diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 834683123898..0a4198c7a435 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -62,7 +62,10 @@ export type RuntimeConstructionDependencies = { connectionId: string | null terminalProvenance: 'current_runtime' | 'restored' }) => AgentHookAuthorityAttestation | null - retireAgentHookCompatibilityAuthority?: (paneKey: string) => void + retireAgentHookCompatibilityAuthority?: ( + paneKey: string, + options?: { confirmedExit?: boolean } + ) => void readHookCliWriterObservation?: (row: AgentStatusIpcPayload) => CliWriterObservation | null /** `exitedSince`: also answer `exited` for an exit the hook store proved at or after it. */ checkHookAgentPresence?: ( diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index a818b1457eac..27eb6698b323 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -180,7 +180,8 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O } } - protected retirePtyAgentLaunchAuthority(ptyId: string): void { + /** `confirmedExit`: the launched command finished at the shell, so its agent ended. */ + protected retirePtyAgentLaunchAuthority(ptyId: string, confirmedExit = false): void { const pty = this.retireHeldLaunch(ptyId) if (!pty) { return @@ -199,7 +200,7 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O pty.launchAgent = null pty.launchCommandAgent = null for (const paneKey of paneKeys) { - this.retireAgentHookCompatibilityAuthorityFn?.(paneKey) + this.retireAgentHookCompatibilityAuthorityFn?.(paneKey, { confirmedExit }) } if (changed) { void this.refreshAgentSenderAssociations().catch(console.warn) diff --git a/src/main/runtime/terminal/output/terminal-title-tracker.ts b/src/main/runtime/terminal/output/terminal-title-tracker.ts index 72405b007604..898563930dd4 100644 --- a/src/main/runtime/terminal/output/terminal-title-tracker.ts +++ b/src/main/runtime/terminal/output/terminal-title-tracker.ts @@ -166,7 +166,7 @@ export abstract class OrcaRuntimeWithGetUnpersistedTrackedTitleForPty extends Or }, onCommandFinished: (exitCode: number | null) => { void this.recheckHookAgentPresenceForPty(ptyId) - this.retirePtyAgentLaunchAuthority(ptyId) + this.retirePtyAgentLaunchAuthority(ptyId, true) this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode }) this.openCodeRunLifetime.onCommandFinished(ptyId, exitCode) }, diff --git a/src/main/runtime/terminal/output/terminal-transient-facts.ts b/src/main/runtime/terminal/output/terminal-transient-facts.ts index 8fca1181344c..45437c118dfb 100644 --- a/src/main/runtime/terminal/output/terminal-transient-facts.ts +++ b/src/main/runtime/terminal/output/terminal-transient-facts.ts @@ -21,7 +21,7 @@ import type { import type { TerminalTitleFactMeta } from '../../../../shared/terminal/output/terminal-output-side-effects' export abstract class OrcaRuntimeWithEmitDaemonPtyTransientFact extends OrcaRuntimeWithScheduleWaitBlockedCheck { - protected abstract retirePtyAgentLaunchAuthority(ptyId: string): void + protected abstract retirePtyAgentLaunchAuthority(ptyId: string, confirmedExit?: boolean): void /** A transient fact the daemon detected while it held scan authority — * emitted through the same fact channel as byte-scanned facts. Arrives @@ -32,7 +32,7 @@ export abstract class OrcaRuntimeWithEmitDaemonPtyTransientFact extends OrcaRunt this.recordTerminalSideEffectFact(ptyId, { kind: 'bell' }) return case 'command-finished': - this.retirePtyAgentLaunchAuthority(ptyId) + this.retirePtyAgentLaunchAuthority(ptyId, true) this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode: fact.exitCode diff --git a/src/main/startup/runtime-startup/main-process-runtime-service.ts b/src/main/startup/runtime-startup/main-process-runtime-service.ts index 54b22dcb0ef9..8c7e7617aafd 100644 --- a/src/main/startup/runtime-startup/main-process-runtime-service.ts +++ b/src/main/startup/runtime-startup/main-process-runtime-service.ts @@ -90,8 +90,8 @@ export function initializeMainProcessRuntime(): OrcaRuntimeService { getDesktopWindowStatus, attestAgentHookCompatibilityAuthority: (candidate) => agentHookServer.attestCompatibilityAuthority(candidate), - retireAgentHookCompatibilityAuthority: (paneKey) => - agentHookServer.retireProcessAuthority(paneKey), + retireAgentHookCompatibilityAuthority: (paneKey, options) => + agentHookServer.retireProcessAuthority(paneKey, options), canRecoverPersistentLocalPtys: () => getDaemonProvider() !== null, // Resolve per call: the RPC server/device registry is constructed later with this runtime. getPairedDeviceName: (pairedDeviceId) => From bab7e7a73722acb6bf8c06f00f5a5a1f491e41bc Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:37:59 -0800 Subject: [PATCH 010/125] Spy on durable mutations in the exit performance contract --- .../terminal/stop/worktree-sleep-resume-recording.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 1ea802921f46..84c13d68b79e 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -198,11 +198,11 @@ it.each([100, 1000])( const fixture = makeRuntimeStoreWithWorkspaceSession(makeWorkspaceSessionWithHeadlessTerminal()) const runtime = new OrcaRuntimeService(fixture.runtimeStore) vi.spyOn(runtime, 'getTerminalWorktreeIdForPaneKey').mockReturnValue(TEST_WORKTREE_ID) - fixture.runtimeStore.runDurableMutation.mockClear() + const durableMutation = vi.spyOn(fixture.runtimeStore, 'runDurableMutation') for (let i = 0; i < count; i++) { runtime.retireExitedPaneResume(`absent-tab-${i}:11111111-1111-4111-8111-111111111111`, 200) } await runtime.readSavedResumeSource(TEST_WORKTREE_ID, PANE_KEY) - expect(fixture.runtimeStore.runDurableMutation).not.toHaveBeenCalled() + expect(durableMutation).not.toHaveBeenCalled() } ) From 153a248fb41a967beb0209dbe8d055981d645d04 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:51:20 -0800 Subject: [PATCH 011/125] Exercise Interrupted through an idle wake and second sleep --- .../persistence/server-pane-sleep.test.ts | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index b3d638672f73..985b9f8dae26 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -277,7 +277,7 @@ it.each(['claude', 'codex'] as const)( ) it.each(['claude', 'codex'] as const)( - 'keeps a mid-turn %s through sleep as Interrupted without a completion', + 'keeps a mid-turn %s Interrupted through sleep, idle wake and sleep again', async (agent) => { await agentHook(agent, 'UserPromptSubmit', 4001) const emitted = vi.fn() @@ -290,6 +290,27 @@ it.each(['claude', 'codex'] as const)( prompt: 'Finished work', paneSleep: { ptyId: 'pty-1' } }) + server.retireSleepingPaneOnSpawn(PANE, { + agentType: agent, + providerSession: { key: 'session_id', id: `${agent}-session` } + }) + server.recordLaunchResumeIdentity({ + paneKey: PANE, + worktreeId: 'wt-1', + agentType: agent, + providerSession: { key: 'session_id', id: `${agent}-session` }, + launchedAt: Date.now() + }) + if (agent === 'claude') { + await agentHook(agent, 'SessionStart', 4002) + } + expect(read()).toMatchObject({ state: 'done', interrupted: true }) + await sleepPane(agent, 'pty-2', 4002) + expect(read()).toMatchObject({ + state: 'done', + interrupted: true, + paneSleep: { ptyId: 'pty-2' } + }) expect(emitted.mock.calls.filter(([row]) => !row.isReplay)).toHaveLength(0) } ) From 21de4349739231dc28cad62eaef65e4650fb0eb3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:51:39 -0800 Subject: [PATCH 012/125] Scope sleep notification assertions to the sleep transition --- .../server/testing/persistence/server-pane-sleep.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 985b9f8dae26..c0726c0cf0e3 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -290,6 +290,7 @@ it.each(['claude', 'codex'] as const)( prompt: 'Finished work', paneSleep: { ptyId: 'pty-1' } }) + expect(emitted.mock.calls.filter(([row]) => !row.isReplay)).toHaveLength(0) server.retireSleepingPaneOnSpawn(PANE, { agentType: agent, providerSession: { key: 'session_id', id: `${agent}-session` } @@ -305,6 +306,7 @@ it.each(['claude', 'codex'] as const)( await agentHook(agent, 'SessionStart', 4002) } expect(read()).toMatchObject({ state: 'done', interrupted: true }) + emitted.mockClear() await sleepPane(agent, 'pty-2', 4002) expect(read()).toMatchObject({ state: 'done', From 4dc3a6b139b1296eb4f737e3a1458688e82c09cd Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:08:27 -0800 Subject: [PATCH 013/125] test: expect the confirmed-exit flag on launch retirement --- .../orca-runtime-tests/terminal-creation-and-readiness.spec.ts | 2 +- .../terminal/surface/slept-pane-exit-status-main.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts index bab05aeaa994..ec9f6aeb2e27 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts @@ -72,7 +72,7 @@ describe('OrcaRuntimeService', () => { runtime.onPtyData('pty-authority', '\x1b]133;D;0\x07', 100) - expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY) + expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { confirmedExit: true }) expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull() expect((await runtime.listTerminals()).terminals).toEqual([ expect.not.objectContaining({ agentIdentity: expect.anything() }) diff --git a/src/main/runtime/terminal/surface/slept-pane-exit-status-main.test.ts b/src/main/runtime/terminal/surface/slept-pane-exit-status-main.test.ts index 7aca7d37feb4..6818122582d2 100644 --- a/src/main/runtime/terminal/surface/slept-pane-exit-status-main.test.ts +++ b/src/main/runtime/terminal/surface/slept-pane-exit-status-main.test.ts @@ -90,7 +90,7 @@ it.each([ clearProviderPtyState('pty-b', { exitProven: true }) } if (launched) { - expect(retireAuthority).toHaveBeenCalledWith(PANE_B) + expect(retireAuthority).toHaveBeenCalledWith(PANE_B, { confirmedExit: false }) } expect(server.getStatusSnapshotForPane(PANE_B)[0]).toMatchObject({ state: 'done', From 0cc34b7f27ffe9fd34643df372d82d28c68109dd Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:23:52 -0800 Subject: [PATCH 014/125] Preserve saved turn verdicts and keep sleep replay out of completion delivery --- .../agent-hooks/server/pane-agent-identity.ts | 13 +- .../agent-hooks/server/server-pane-sleep.ts | 29 ++-- .../server-pane-saved-sleep.test.ts | 75 ++++++++++ .../worktree-sleep-resume-recording.test.ts | 17 ++- .../stop/worktree-sleep-resume-records.ts | 3 + .../hooks/agent-status-sleep-handoff.test.ts | 132 ++++++++++-------- .../hooks/ipc-events/agent-status-routing.ts | 5 +- .../lifecycle/agent-pane-sleep-status.ts | 18 +++ 8 files changed, 206 insertions(+), 86 deletions(-) create mode 100644 src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts create mode 100644 src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts diff --git a/src/main/agent-hooks/server/pane-agent-identity.ts b/src/main/agent-hooks/server/pane-agent-identity.ts index f61c61f48a5f..2601232d70a9 100644 --- a/src/main/agent-hooks/server/pane-agent-identity.ts +++ b/src/main/agent-hooks/server/pane-agent-identity.ts @@ -1,6 +1,7 @@ import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' import { promoteSavedLiveResumeRecord } from '../../../shared/agent-session/lifecycle/resume/promote-saved-live-resume-record' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' +import { agentMainAgentVerdict } from '../../../shared/agent-status/lifecycle/agent-main-agent-verdict' export type PaneAgentIdentity = { status: AgentStatusIpcPayload @@ -32,7 +33,11 @@ export function paneAgentIdentity(args: { ...placeholder } = row const status: AgentStatusIpcPayload = row.providerSessionOnly - ? { ...placeholder, state: 'done', sessionBoundary: true } + ? { + ...placeholder, + state: 'done', + ...(agentMainAgentVerdict(row) === null ? { sessionBoundary: true } : {}) + } : row // Sleep is a resumable physical stop: its exit retires the process, never the conversation. if (row.paneSleep) { @@ -61,8 +66,10 @@ export function paneAgentIdentity(args: { receivedAt: saved.updatedAt, stateStartedAt: saved.updatedAt, providerSession: promoted.providerSession, - state: 'done', - ...(saved.state === 'done' ? {} : { sessionBoundary: true }), + state: saved.state, + ...(saved.state === 'done' && agentMainAgentVerdict(saved) === null + ? { sessionBoundary: true } + : {}), ...(saved.interrupted !== undefined ? { interrupted: saved.interrupted } : {}), ...(saved.mainAgent ? { mainAgent: saved.mainAgent } : {}), prompt: promoted.prompt, diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index 4eabb48c45e8..36735b52bcdf 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -11,6 +11,7 @@ import { AgentHookServerAuthorityFences } from './server-authority-fences' import { endedPresenceOf, recordAgentExit } from './agent-exit-evidence' import type { LaunchResumeIdentityEvent } from './launch-resume-identity-event' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' +import { agentPaneSleepStatus } from '../../../shared/agent-status/lifecycle/agent-pane-sleep-status' export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityFences { abstract dropStatusEntry(paneKey: string, options?: { preserveResumeIdentity?: boolean }): void @@ -137,26 +138,14 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF const row: EnrichedAgentHookEventPayload = { ...accepted, ...(midTurn ? { stateStartedAt: now } : {}), - payload: midTurn - ? { - ...payload, - state: 'done', - interrupted: true, - ...(payload.mainAgent - ? { - mainAgent: { - state: 'done' as const, - outcome: 'cancellation' as const, - stateStartedAt: now - } - } - : {}) - } - : { - ...payload, - state: identity.status.state, - ...(identity.status.sessionBoundary ? { sessionBoundary: true } : {}) - }, + payload: agentPaneSleepStatus( + { + ...payload, + state: identity.status.state, + ...(identity.status.sessionBoundary ? { sessionBoundary: true } : {}) + }, + now + ), paneSleep: { ptyId, ...(incarnationId ? { incarnationId } : {}) }, agentPresence: endedPresenceOf(previous) } diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts new file mode 100644 index 000000000000..4ac326f8cdbf --- /dev/null +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts @@ -0,0 +1,75 @@ +import { expect, it } from 'vitest' +import { AgentHookServer } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' +import { resumeStatusFromHookRow } from '../../../../runtime/terminal/stop/hook-status-resume-records' +import { liveResumeRecord } from '../../../../../shared/agent-session/lifecycle/resume/agent-resume-record-from-status' +import { agentEntryCompletionAt } from '../../../../../shared/agent-status/lifecycle/agent-completion-time' + +it.each(['claude', 'codex'] as const)( + 'settles %s saved-only turns without inventing a completion', + (agent) => { + for (const turn of ['working', 'waiting', 'boundary', 'interrupted'] as const) { + const state = turn === 'working' || turn === 'waiting' ? turn : 'done' + const status = resumeStatusFromHookRow( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + agentType: agent, + connectionId: null, + receivedAt: 100, + stateStartedAt: 100, + providerSession: { key: 'session_id', id: `${agent}-session` }, + state, + prompt: '', + ...(turn === 'boundary' ? { sessionBoundary: true } : {}), + ...(turn === 'interrupted' ? { interrupted: true } : {}), + mainAgent: { + state, + stateStartedAt: 100, + ...(turn === 'interrupted' ? { outcome: 'cancellation' } : {}) + } + }, + undefined + )! + const saved = liveResumeRecord({ + entry: status, + retainsResumableIdentity: state === 'done', + worktreeIdOf: () => 'wt-1', + tabOf: () => ({ id: 'tab-1' }), + capturedAt: 100 + })! + const server = new AgentHookServer() + server.setTerminalPaneLifecycle({ + readSavedRecord: () => saved, + ownsProcess: () => true, + isStopping: () => true, + isReversibleStop: () => true, + isPlaced: () => true + }) + try { + expect(server.settleTerminalPaneSleep(PANE, 'pty', 'birth')).toBe(true) + const row = server.getStatusSnapshotForPane(PANE)[0]! + expect(row).toMatchObject({ state: 'done', paneSleep: { ptyId: 'pty' } }) + if (turn === 'boundary') { + expect(row.sessionBoundary).toBe(true) + expect(agentEntryCompletionAt(row)).toBeNull() + } else { + expect(row).toMatchObject({ + interrupted: true, + mainAgent: { state: 'done', outcome: 'cancellation' } + }) + expect(row.sessionBoundary).not.toBe(true) + server.retireSleepingPaneOnSpawn(PANE, { + agentType: agent, + providerSession: { key: 'session_id', id: `${agent}-session` } + }) + expect(server.settleTerminalPaneSleep(PANE, 'pty-2', 'birth-2')).toBe(true) + expect(server.getStatusSnapshotForPane(PANE)[0]).toMatchObject({ interrupted: true }) + } + } finally { + server.stop() + } + } + } +) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 84c13d68b79e..7bb925e2d016 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -46,12 +46,18 @@ const NEWER_STATUS: AgentStatusIpcPayload = { } describe('main-run sleep of a pane whose hook row is gone', () => { - it.each(['live', 'exited', 'expired exit'] as const)( + it.each(['live', 'working', 'interrupted', 'exited', 'expired exit'] as const)( 'uses a saved live conversation unless an exit was recorded (%s)', async (scenario) => { const fixture = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ - sleepingAgentSessionsByPaneKey: { [PANE_KEY]: OLDER_CHECKPOINT } + sleepingAgentSessionsByPaneKey: { + [PANE_KEY]: { + ...OLDER_CHECKPOINT, + ...(scenario === 'working' ? { state: 'working' as const } : {}), + ...(scenario === 'interrupted' ? { interrupted: true } : {}) + } + } }) ) const server = new AgentHookServer() @@ -103,7 +109,7 @@ describe('main-run sleep of a pane whose hook row is gone', () => { isPlaced: () => true, retireSavedRecord: (paneKey, at) => runtime.retireExitedPaneResume(paneKey, at) }) - if (scenario !== 'live') { + if (scenario === 'exited' || scenario === 'expired exit') { server.reconcileEndedProcessForPaneKeys([PANE_KEY], { confirmedExit: true }) @@ -115,7 +121,7 @@ describe('main-run sleep of a pane whose hook row is gone', () => { try { await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) const record = fixture.getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY] - if (scenario !== 'live') { + if (scenario === 'exited' || scenario === 'expired exit') { expect(record).toBeUndefined() } else { expect(record).toMatchObject({ @@ -123,6 +129,9 @@ describe('main-run sleep of a pane whose hook row is gone', () => { restoreOnTabOpenOnly: true, providerSession: { key: 'session_id', id: 'claude-session-1' } }) + if (scenario === 'working' || scenario === 'interrupted') { + expect(record?.interrupted).toBe(true) + } } } finally { server.stop() diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts index eb73ca334515..0667ac5e9ad3 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts @@ -12,6 +12,8 @@ import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/ import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { isWorkspaceSleepRecord } from '../../../../shared/workspace/lifecycle/workspace-sleep' import { launchStatement, type PtyLaunchFacts } from '../launch/launch-evidence' +import { agentPaneSleepStatus } from '../../../../shared/agent-status/lifecycle/agent-pane-sleep-status' +import { agentVerdictFields } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' /** Per slept PTY: the resume records captured, and the panes the hook store proves moved on. */ export type WorktreeSleepResumeCapture = Map< @@ -103,6 +105,7 @@ export async function captureWorktreeSleepResumeRecords(args: { prompt: row.prompt, // Why done: a pane-owned capture whose `--resume` waits for the tab open (#11598). state: 'done', + ...agentVerdictFields(agentPaneSleepStatus(row, args.capturedAt)), capturedAt: args.capturedAt, updatedAt: row.receivedAt, origin: 'worktree-sleep', diff --git a/src/renderer/src/hooks/agent-status-sleep-handoff.test.ts b/src/renderer/src/hooks/agent-status-sleep-handoff.test.ts index b1bf31995781..ed77d86a63bc 100644 --- a/src/renderer/src/hooks/agent-status-sleep-handoff.test.ts +++ b/src/renderer/src/hooks/agent-status-sleep-handoff.test.ts @@ -4,13 +4,14 @@ import { buildWindowApi } from './ipc-events-agent-status-window-test-fixtures' import { makeTab } from '../store/terminals/testing/terminal-tab.test-fixture' import { registerAgentStatusIpcBridge } from './ipc-events/agent-status-ipc-bridge' import { useAppStore } from '../store' +import { observeAgentHookCompletionForNotification } from './agent-hook-completion-notifications' vi.mock('../store', async () => { const { createTestStore } = await import('../store/testing/app-store-test-fixture') return { useAppStore: createTestStore() } }) vi.mock('./agent-hook-completion-notifications', () => ({ - observeAgentHookCompletionForNotification: () => {}, + observeAgentHookCompletionForNotification: vi.fn(), syncAgentHookCompletionNotificationsForStoreUpdate: () => {} })) const NOW = 1_800_000_000_000 @@ -23,67 +24,82 @@ afterEach(() => { }) describe('successful sleep status handoff', () => { - it('publishes a queued same-row Done marker before post-kill cleanup can drop it', () => { - vi.useFakeTimers() - vi.setSystemTime(NOW) - useAppStore.setState(useAppStore.getInitialState(), true) - useAppStore.setState({ - workspaceSessionReady: true, - tabsByWorktree: { 'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1' })] }, - terminalLayoutsByTabId: { - 'tab-1': { root: { type: 'leaf', leafId: LEAF }, activeLeafId: LEAF, expandedLeafId: null } - }, - ptyIdsByTabId: { 'tab-1': ['pty-1'] } - }) - let send: (event: AgentStatusSetData) => void = () => { - throw new Error('Listener missing') - } - vi.stubGlobal( - 'window', - buildWindowApi({ - onSet: (listener) => { - send = listener - return () => {} - } + it.each(['done', 'working'] as const)( + 'hands off %s sleep without announcing completion', + (state) => { + vi.useFakeTimers() + vi.setSystemTime(NOW) + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ + workspaceSessionReady: true, + tabsByWorktree: { 'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1' })] }, + terminalLayoutsByTabId: { + 'tab-1': { + root: { type: 'leaf', leafId: LEAF }, + activeLeafId: LEAF, + expandedLeafId: null + } + }, + ptyIdsByTabId: { 'tab-1': ['pty-1'] } }) - ) - const unsubs: (() => void)[] = [] - const bridge = registerAgentStatusIpcBridge(unsubs) - try { - const event: AgentStatusSetData = { - paneKey: PANE, - connectionId: null, - tabId: 'tab-1', - worktreeId: 'wt-1', - state: 'done', - prompt: 'Finished', - agentType: 'claude', - receivedAt: NOW, - stateStartedAt: NOW - 10 + let send: (event: AgentStatusSetData) => void = () => { + throw new Error('Listener missing') } - send(event) - expect(useAppStore.getState().agentStatusByPaneKey.get(PANE)?.state).toBe('done') - const publications: (string | undefined)[] = [] - const stop = useAppStore.subscribe((state) => - publications.push(state.agentStatusByPaneKey.get(PANE)?.state) + vi.stubGlobal( + 'window', + buildWindowApi({ + onSet: (listener) => { + send = listener + return () => {} + } + }) ) - send({ ...event, paneSleep: { ptyId: 'pty-1' }, isReplay: true }) - useAppStore.getState().dropHibernatedAgentStatusPane('wt-1', PANE) - expect(useAppStore.getState().agentStatusByPaneKey.get(PANE)?.paneSleep).toEqual({ - ptyId: 'pty-1' - }) - vi.advanceTimersByTime(40) - expect(publications).not.toContain(undefined) - expect(useAppStore.getState().agentStatusByPaneKey.get(PANE)?.state).toBe('done') - useAppStore.getState().dropAgentStatus(PANE) - expect(useAppStore.getState().agentStatusByPaneKey.has(PANE)).toBe(false) - stop() - } finally { - bridge.disposeAsyncState() - bridge.unsubscribeStore() - for (const stop of unsubs) { + const unsubs: (() => void)[] = [] + const bridge = registerAgentStatusIpcBridge(unsubs) + try { + const event: AgentStatusSetData = { + paneKey: PANE, + connectionId: null, + tabId: 'tab-1', + worktreeId: 'wt-1', + state, + prompt: 'Finished', + agentType: 'claude', + receivedAt: NOW, + stateStartedAt: NOW - 10 + } + send(event) + expect(useAppStore.getState().agentStatusByPaneKey.get(PANE)?.state).toBe(state) + const publications: (string | undefined)[] = [] + const stop = useAppStore.subscribe((state) => + publications.push(state.agentStatusByPaneKey.get(PANE)?.state) + ) + vi.mocked(observeAgentHookCompletionForNotification).mockClear() + send({ + ...event, + state: 'done', + ...(state === 'working' ? { interrupted: true, stateStartedAt: NOW + 1 } : {}), + paneSleep: { ptyId: 'pty-1' }, + isReplay: true + }) + useAppStore.getState().dropHibernatedAgentStatusPane('wt-1', PANE) + expect(useAppStore.getState().agentStatusByPaneKey.get(PANE)?.paneSleep).toEqual({ + ptyId: 'pty-1' + }) + vi.advanceTimersByTime(40) + expect(publications).not.toContain(undefined) + expect(useAppStore.getState().agentStatusByPaneKey.get(PANE)?.state).toBe('done') + expect(observeAgentHookCompletionForNotification).not.toHaveBeenCalled() + useAppStore.getState().dropAgentStatus(PANE) + expect(useAppStore.getState().agentStatusByPaneKey.has(PANE)).toBe(false) stop() + } finally { + bridge.disposeAsyncState() + bridge.unsubscribeStore() + for (const stop of unsubs) { + stop() + } } } - }) + ) }) diff --git a/src/renderer/src/hooks/ipc-events/agent-status-routing.ts b/src/renderer/src/hooks/ipc-events/agent-status-routing.ts index 63cad5d4d326..0f60bab7cee0 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status-routing.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status-routing.ts @@ -36,7 +36,7 @@ export function isAgentStatusForRecentlyClosedTab( export function isSeenHostReplay( data: Pick< AgentStatusIpcPayload, - 'isReplay' | 'stateStartedAt' | 'turnCompletedAt' | 'turnEndedAt' + 'isReplay' | 'paneSleep' | 'stateStartedAt' | 'turnCompletedAt' | 'turnEndedAt' >, state: string, existing: @@ -49,6 +49,9 @@ export function isSeenHostReplay( if (data.isReplay !== true) { return false } + if (data.paneSleep) { + return true + } // Why: with no row there is no proof the turn was unseen, so keep seeding (no reload re-fires). if (existing === undefined) { return true diff --git a/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts new file mode 100644 index 000000000000..d963b75ed6c4 --- /dev/null +++ b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts @@ -0,0 +1,18 @@ +import type { AgentMainAgentStatus } from './main-agent-status' +import type { AgentStatusState } from '../contracts/agent-status-types' + +/** A physical sleep interrupts unfinished work and preserves an already accepted verdict. */ +export function agentPaneSleepStatus< + T extends { state: AgentStatusState; interrupted?: boolean; mainAgent?: AgentMainAgentStatus } +>(status: T, at: number): T { + return status.state === 'done' + ? status + : { + ...status, + state: 'done', + interrupted: true, + ...(status.mainAgent + ? { mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: at } } + : {}) + } +} From b6889c61abd3e6032290252913e8234b211e8346 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:40:42 -0800 Subject: [PATCH 015/125] Supply renderer history when checking recovered completion eligibility --- .../server/testing/persistence/server-pane-saved-sleep.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts index 4ac326f8cdbf..eed13cd559fc 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts @@ -53,7 +53,7 @@ it.each(['claude', 'codex'] as const)( expect(row).toMatchObject({ state: 'done', paneSleep: { ptyId: 'pty' } }) if (turn === 'boundary') { expect(row.sessionBoundary).toBe(true) - expect(agentEntryCompletionAt(row)).toBeNull() + expect(agentEntryCompletionAt({ ...row, stateHistory: [] })).toBeNull() } else { expect(row).toMatchObject({ interrupted: true, From 8ff883aa6b76dc736c10977035d86e3ca14365e6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:49:01 -0800 Subject: [PATCH 016/125] fix(agent-hooks): don't treat a suspended launch as an exit A Ctrl-Z'd agent finishes its shell command with a stop status while its process lives on; only record the exit for other statuses. Drop the renderer reconcile's confirmedExit, whose message can't tell a suspend. --- src/main/ipc/agent-status-row-teardown-ipc.ts | 3 +- .../terminal-creation-and-readiness.spec.ts | 114 ++++++++++-------- .../terminal/output/terminal-title-tracker.ts | 3 +- .../output/terminal-transient-facts.ts | 3 +- .../terminal-osc133-command-finished.ts | 7 ++ 5 files changed, 73 insertions(+), 57 deletions(-) diff --git a/src/main/ipc/agent-status-row-teardown-ipc.ts b/src/main/ipc/agent-status-row-teardown-ipc.ts index b460f3ffd59f..264f44a3dc2e 100644 --- a/src/main/ipc/agent-status-row-teardown-ipc.ts +++ b/src/main/ipc/agent-status-row-teardown-ipc.ts @@ -74,8 +74,7 @@ export function registerAgentStatusRowTeardownIpcHandlers(): void { // Confirmed process exit must clear latches with the row (STA-4612). agentHookServer.reconcileEndedProcessForPaneKeys([paneKey], { // The shell still owns the PTY, so keep its usable resume identity. - preserveResumeIdentity: true, - confirmedExit: true + preserveResumeIdentity: true }) clearMigrationUnsupportedPtysForPaneKey(paneKey) } catch (err) { diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts index ec9f6aeb2e27..9764e11373fc 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts @@ -21,63 +21,71 @@ import { spawnedPtyEnv } from '../terminal/launch/spawned-pty-env-fixtures' import '../../../shared/agent-launch/startup/jcode-runtime-dir' describe('OrcaRuntimeService', () => { - it('retires inherited launch authority when the agent command exits', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'pty-authority', incarnationId: 'process-1' }) - const retireAuthority = vi.fn() - const runtime = new OrcaRuntimeService(store, undefined, { - attestAgentHookCompatibilityAuthority: (candidate) => ({ - paneKey: candidate.paneKey, - source: 'current_hook' - }), - retireAgentHookCompatibilityAuthority: retireAuthority - }) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession: vi.fn().mockResolvedValue({ tabId: 'tab-authority' }), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + it.each([ + ['exits', 0, true], + ['is suspended', 148, false] + ] as const)( + 'retires inherited launch authority when the agent command %s', + async (_, status, exited) => { + const spawn = vi.fn().mockResolvedValue({ id: 'pty-authority', incarnationId: 'process-1' }) + const retireAuthority = vi.fn() + const runtime = new OrcaRuntimeService(store, undefined, { + attestAgentHookCompatibilityAuthority: (candidate) => ({ + paneKey: candidate.paneKey, + source: 'current_hook' + }), + retireAgentHookCompatibilityAuthority: retireAuthority + }) + runtime.setPtyController({ + spawn: committingSpawn(runtime, spawn), + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + runtime.setNotifier({ + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession: vi.fn().mockResolvedValue({ tabId: 'tab-authority' }), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + focusTerminal: vi.fn(), + closeTerminal: vi.fn(), + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + runtime.attachWindow(1) + await runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const terminal = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'codex', - launchAgent: 'codex', - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} } - }) - const spawnEnv = spawnedPtyEnv(spawn.mock.calls[0]?.[0]) - const evidence = { - terminalHandle: terminal.handle, - paneKey: spawnEnv.ORCA_PANE_KEY, - launchToken: spawnEnv.ORCA_AGENT_LAUNCH_TOKEN - } + const terminal = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { + command: 'codex', + launchAgent: 'codex', + launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} } + }) + const spawnEnv = spawnedPtyEnv(spawn.mock.calls[0]?.[0]) + const evidence = { + terminalHandle: terminal.handle, + paneKey: spawnEnv.ORCA_PANE_KEY, + launchToken: spawnEnv.ORCA_AGENT_LAUNCH_TOKEN + } - expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).not.toBeNull() - expect((await runtime.listTerminals()).terminals).toEqual([ - expect.objectContaining({ handle: terminal.handle, agentIdentity: 'codex' }) - ]) + expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).not.toBeNull() + expect((await runtime.listTerminals()).terminals).toEqual([ + expect.objectContaining({ handle: terminal.handle, agentIdentity: 'codex' }) + ]) - runtime.onPtyData('pty-authority', '\x1b]133;D;0\x07', 100) + runtime.onPtyData('pty-authority', `\x1b]133;D;${status}\x07`, 100) - expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { confirmedExit: true }) - expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull() - expect((await runtime.listTerminals()).terminals).toEqual([ - expect.not.objectContaining({ agentIdentity: expect.anything() }) - ]) - }) + expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { + confirmedExit: exited + }) + expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull() + expect((await runtime.listTerminals()).terminals).toEqual([ + expect.not.objectContaining({ agentIdentity: expect.anything() }) + ]) + } + ) it('restores a retained coordinator handle after a late controller inventory', async () => { const paneKey = makePaneKey('host-tab', HEADLESS_LEAF_ID) diff --git a/src/main/runtime/terminal/output/terminal-title-tracker.ts b/src/main/runtime/terminal/output/terminal-title-tracker.ts index 898563930dd4..9691888a29f3 100644 --- a/src/main/runtime/terminal/output/terminal-title-tracker.ts +++ b/src/main/runtime/terminal/output/terminal-title-tracker.ts @@ -1,4 +1,5 @@ import { OrcaRuntimeWithEmitDaemonPtyTransientFact } from './terminal-transient-facts' +import { isJobStopStatus } from '../../../../shared/terminal/output/terminal-osc133-command-finished' import { getDecorativeTitleGateKey } from '../../../../shared/agent-status/title/agent-decorative-title-signature' import { shouldEmitTitleFactForFrame } from './decorative-title-fact-emission' import type { RuntimePtyTitleTrackerEntry } from '../records/runtime-terminal-state-records' @@ -166,7 +167,7 @@ export abstract class OrcaRuntimeWithGetUnpersistedTrackedTitleForPty extends Or }, onCommandFinished: (exitCode: number | null) => { void this.recheckHookAgentPresenceForPty(ptyId) - this.retirePtyAgentLaunchAuthority(ptyId, true) + this.retirePtyAgentLaunchAuthority(ptyId, !isJobStopStatus(exitCode)) this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode }) this.openCodeRunLifetime.onCommandFinished(ptyId, exitCode) }, diff --git a/src/main/runtime/terminal/output/terminal-transient-facts.ts b/src/main/runtime/terminal/output/terminal-transient-facts.ts index 45437c118dfb..9ff82506e76c 100644 --- a/src/main/runtime/terminal/output/terminal-transient-facts.ts +++ b/src/main/runtime/terminal/output/terminal-transient-facts.ts @@ -1,5 +1,6 @@ import { OrcaRuntimeWithScheduleWaitBlockedCheck } from '../wait/terminal-wait-blocked-checks' import type { PtyTransientFact } from '../../../providers/pty/events' +import { isJobStopStatus } from '../../../../shared/terminal/output/terminal-osc133-command-finished' import type { TerminalSideEffectBatch, TerminalSideEffectFact @@ -32,7 +33,7 @@ export abstract class OrcaRuntimeWithEmitDaemonPtyTransientFact extends OrcaRunt this.recordTerminalSideEffectFact(ptyId, { kind: 'bell' }) return case 'command-finished': - this.retirePtyAgentLaunchAuthority(ptyId, true) + this.retirePtyAgentLaunchAuthority(ptyId, !isJobStopStatus(fact.exitCode)) this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode: fact.exitCode diff --git a/src/shared/terminal/output/terminal-osc133-command-finished.ts b/src/shared/terminal/output/terminal-osc133-command-finished.ts index 7b0c30032dfe..91b162b4a680 100644 --- a/src/shared/terminal/output/terminal-osc133-command-finished.ts +++ b/src/shared/terminal/output/terminal-osc133-command-finished.ts @@ -8,6 +8,8 @@ type OscTerminator = { } const OSC_133_PREFIX = '\x1b]133;' +// 128 + SIGSTOP/SIGTSTP/SIGTTIN/SIGTTOU, as numbered on macOS (17, 18, 21, 22) and Linux (19, 20, 21, 22). +const JOB_STOP_STATUSES: ReadonlySet = new Set([145, 146, 147, 148, 149, 150]) const MAX_OSC_CARRY_LENGTH = 4096 function findOscTerminator(data: string, startIndex: number): OscTerminator | null { @@ -138,3 +140,8 @@ export function createOsc133CommandFinishedScanner( } } } + +/** A suspended job (Ctrl-Z) finishes its command with a stop status while its process lives on. */ +export function isJobStopStatus(exitCode: number | null): boolean { + return exitCode !== null && JOB_STOP_STATUSES.has(exitCode) +} From 03ac47c96e386ab7f92b28f159bfe92c76602462 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:03:24 -0800 Subject: [PATCH 017/125] fix(agent-hooks): keep a suspended agent's launch held A Ctrl-Z stop status isn't the launch command finishing, so don't retire the launch for it; the agent's real finish after fg then still records the exit. --- .../terminal-creation-and-readiness.spec.ts | 9 ++++++--- .../runtime/terminal/output/terminal-title-tracker.ts | 5 ++++- .../runtime/terminal/output/terminal-transient-facts.ts | 5 ++++- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts index 9764e11373fc..7cc6bed25361 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts @@ -77,9 +77,12 @@ describe('OrcaRuntimeService', () => { runtime.onPtyData('pty-authority', `\x1b]133;D;${status}\x07`, 100) - expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { - confirmedExit: exited - }) + if (!exited) { + expect(retireAuthority).not.toHaveBeenCalled() + expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).not.toBeNull() + return + } + expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { confirmedExit: true }) expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull() expect((await runtime.listTerminals()).terminals).toEqual([ expect.not.objectContaining({ agentIdentity: expect.anything() }) diff --git a/src/main/runtime/terminal/output/terminal-title-tracker.ts b/src/main/runtime/terminal/output/terminal-title-tracker.ts index 9691888a29f3..2acf03ab6529 100644 --- a/src/main/runtime/terminal/output/terminal-title-tracker.ts +++ b/src/main/runtime/terminal/output/terminal-title-tracker.ts @@ -167,7 +167,10 @@ export abstract class OrcaRuntimeWithGetUnpersistedTrackedTitleForPty extends Or }, onCommandFinished: (exitCode: number | null) => { void this.recheckHookAgentPresenceForPty(ptyId) - this.retirePtyAgentLaunchAuthority(ptyId, !isJobStopStatus(exitCode)) + // A suspended (Ctrl-Z) agent still holds its launch; only a real finish ends it. + if (!isJobStopStatus(exitCode)) { + this.retirePtyAgentLaunchAuthority(ptyId, true) + } this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode }) this.openCodeRunLifetime.onCommandFinished(ptyId, exitCode) }, diff --git a/src/main/runtime/terminal/output/terminal-transient-facts.ts b/src/main/runtime/terminal/output/terminal-transient-facts.ts index 9ff82506e76c..87fdc129867e 100644 --- a/src/main/runtime/terminal/output/terminal-transient-facts.ts +++ b/src/main/runtime/terminal/output/terminal-transient-facts.ts @@ -33,7 +33,10 @@ export abstract class OrcaRuntimeWithEmitDaemonPtyTransientFact extends OrcaRunt this.recordTerminalSideEffectFact(ptyId, { kind: 'bell' }) return case 'command-finished': - this.retirePtyAgentLaunchAuthority(ptyId, !isJobStopStatus(fact.exitCode)) + // A suspended (Ctrl-Z) agent still holds its launch; only a real finish ends it. + if (!isJobStopStatus(fact.exitCode)) { + this.retirePtyAgentLaunchAuthority(ptyId, true) + } this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode: fact.exitCode From 12bdc5e272ce8b03267e2e6c7ce85ce1b3ec6e2a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:04:45 -0800 Subject: [PATCH 018/125] Revert "fix(agent-hooks): keep a suspended agent's launch held" This reverts commit 03ac47c96e386ab7f92b28f159bfe92c76602462. --- .../terminal-creation-and-readiness.spec.ts | 9 +++------ .../runtime/terminal/output/terminal-title-tracker.ts | 5 +---- .../runtime/terminal/output/terminal-transient-facts.ts | 5 +---- 3 files changed, 5 insertions(+), 14 deletions(-) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts index 7cc6bed25361..9764e11373fc 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts @@ -77,12 +77,9 @@ describe('OrcaRuntimeService', () => { runtime.onPtyData('pty-authority', `\x1b]133;D;${status}\x07`, 100) - if (!exited) { - expect(retireAuthority).not.toHaveBeenCalled() - expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).not.toBeNull() - return - } - expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { confirmedExit: true }) + expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { + confirmedExit: exited + }) expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull() expect((await runtime.listTerminals()).terminals).toEqual([ expect.not.objectContaining({ agentIdentity: expect.anything() }) diff --git a/src/main/runtime/terminal/output/terminal-title-tracker.ts b/src/main/runtime/terminal/output/terminal-title-tracker.ts index 2acf03ab6529..9691888a29f3 100644 --- a/src/main/runtime/terminal/output/terminal-title-tracker.ts +++ b/src/main/runtime/terminal/output/terminal-title-tracker.ts @@ -167,10 +167,7 @@ export abstract class OrcaRuntimeWithGetUnpersistedTrackedTitleForPty extends Or }, onCommandFinished: (exitCode: number | null) => { void this.recheckHookAgentPresenceForPty(ptyId) - // A suspended (Ctrl-Z) agent still holds its launch; only a real finish ends it. - if (!isJobStopStatus(exitCode)) { - this.retirePtyAgentLaunchAuthority(ptyId, true) - } + this.retirePtyAgentLaunchAuthority(ptyId, !isJobStopStatus(exitCode)) this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode }) this.openCodeRunLifetime.onCommandFinished(ptyId, exitCode) }, diff --git a/src/main/runtime/terminal/output/terminal-transient-facts.ts b/src/main/runtime/terminal/output/terminal-transient-facts.ts index 87fdc129867e..9ff82506e76c 100644 --- a/src/main/runtime/terminal/output/terminal-transient-facts.ts +++ b/src/main/runtime/terminal/output/terminal-transient-facts.ts @@ -33,10 +33,7 @@ export abstract class OrcaRuntimeWithEmitDaemonPtyTransientFact extends OrcaRunt this.recordTerminalSideEffectFact(ptyId, { kind: 'bell' }) return case 'command-finished': - // A suspended (Ctrl-Z) agent still holds its launch; only a real finish ends it. - if (!isJobStopStatus(fact.exitCode)) { - this.retirePtyAgentLaunchAuthority(ptyId, true) - } + this.retirePtyAgentLaunchAuthority(ptyId, !isJobStopStatus(fact.exitCode)) this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode: fact.exitCode From c44caafa62ab07c246dd40615331ac8dd3518cea Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:12:59 -0800 Subject: [PATCH 019/125] Run the sleep runtime integration on the native test worker --- .../test-runtime/sqlite-admission/vitest-node-runtime-files.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 8a09a936ba4d..4e2c6b558be4 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -46,6 +46,7 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-background-stop-unreadable.test.ts', 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-exit-delivery.test.ts', 'src/main/runtime/construction/orca-runtime.test.ts', + 'src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts', 'src/main/runtime/workspaces/startup/worktree-agent-first-surface.test.ts', 'src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts', 'src/cli/**/*.test.ts', From 9964ec40434d71a4bd1834d237788c626566c9e0 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:38:52 -0800 Subject: [PATCH 020/125] Preserve recovered turns on wake and avoid resuming shared agent processes --- .../agent-hooks/server/pane-agent-identity.ts | 41 ++-- .../server/pane-agent-turn-continuity.ts | 4 +- .../server/server-ingest-terminal.ts | 42 +++- .../agent-hooks/server/server-pane-sleep.ts | 7 +- src/main/agent-hooks/server/server-state.ts | 9 +- .../server-pane-saved-sleep.test.ts | 149 ++++++++++++++ .../tmux/server-tmux-canonical.test.ts | 23 ++- .../pane/terminal-pane-status-lifecycle.ts | 6 +- .../runtime-agent-status-sources.ts | 17 +- .../stop/worktree-sleep-resume-recording.ts | 2 +- .../stop/worktree-sleep-resume-records.ts | 6 +- .../runtime-worktree-ps-activity.ts | 6 +- .../workspace-process-listing.ts | 4 +- .../attention/agent-finish-drop-breadcrumb.ts | 1 + .../dispatch-terminal-notification.ts | 14 ++ ...agent-status-sleep-wake-completion.test.ts | 187 ++++++++++++++++++ .../promote-saved-live-resume-record.ts | 12 +- 17 files changed, 487 insertions(+), 43 deletions(-) create mode 100644 src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts diff --git a/src/main/agent-hooks/server/pane-agent-identity.ts b/src/main/agent-hooks/server/pane-agent-identity.ts index 2601232d70a9..cff960a67231 100644 --- a/src/main/agent-hooks/server/pane-agent-identity.ts +++ b/src/main/agent-hooks/server/pane-agent-identity.ts @@ -7,10 +7,12 @@ export type PaneAgentIdentity = { status: AgentStatusIpcPayload /** The agent left the pane; its identity names what to retire, not what to resume. */ ended: boolean + /** Shared servers survive the pane; their conversation must not be launched again on wake. */ + processTopology?: 'pane-owned' | 'shared' | 'unverifiable' } /** The one rule for which agent conversation a pane holds: its hook row in any at-rest shape, - * else its saved live record, minus an exit recorded since that identity was last updated. */ + * else its saved resume record, minus an exit recorded since that identity was last updated. */ export function paneAgentIdentity(args: { paneKey: string row?: AgentStatusIpcPayload @@ -46,37 +48,36 @@ export function paneAgentIdentity(args: { return { status, ended: endedSince(args, row.receivedAt) } } const saved = args.savedRecord - const promoted = - saved && args.worktreeId - ? promoteSavedLiveResumeRecord({ - record: saved, - worktreeId: args.worktreeId, - capturedAt: saved.capturedAt - }) - : null - if (!saved || !promoted || saved.paneKey !== args.paneKey) { + if (!saved || !args.worktreeId || saved.paneKey !== args.paneKey) { + return null + } + const recovered = promoteSavedLiveResumeRecord({ + record: saved, + worktreeId: args.worktreeId, + capturedAt: saved.capturedAt, + includeSleepRecord: true + }) + if (!recovered) { return null } return { status: { paneKey: args.paneKey, - ...(promoted.tabId ? { tabId: promoted.tabId } : {}), - worktreeId: promoted.worktreeId, - connectionId: promoted.connectionId ?? null, + ...(saved.tabId ? { tabId: saved.tabId } : {}), + worktreeId: saved.worktreeId, + connectionId: saved.connectionId ?? null, receivedAt: saved.updatedAt, - stateStartedAt: saved.updatedAt, - providerSession: promoted.providerSession, + stateStartedAt: saved.mainAgent?.stateStartedAt ?? saved.updatedAt, + providerSession: saved.providerSession, state: saved.state, ...(saved.state === 'done' && agentMainAgentVerdict(saved) === null ? { sessionBoundary: true } : {}), ...(saved.interrupted !== undefined ? { interrupted: saved.interrupted } : {}), ...(saved.mainAgent ? { mainAgent: saved.mainAgent } : {}), - prompt: promoted.prompt, - agentType: promoted.agent, - ...(promoted.lastAssistantMessage - ? { lastAssistantMessage: promoted.lastAssistantMessage } - : {}) + prompt: saved.prompt, + agentType: saved.agent, + ...(saved.lastAssistantMessage ? { lastAssistantMessage: saved.lastAssistantMessage } : {}) }, // The promotion restamps its clock; the exit must postdate the record as saved. ended: endedSince(args, saved.updatedAt) diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index d0a3a811f8f5..30a22e40d935 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -9,8 +9,10 @@ export function resumedAcceptedTurn( incoming: AgentHookEventPayload ): EnrichedAgentHookEventPayload | null { const continuesTurn = - incoming.payload.agentType === 'claude' && + (incoming.payload.agentType === 'claude' || previous.payload.interrupted === true) && incoming.payload.sessionBoundary === true && + incoming.hasExplicitPrompt !== true && + incoming.toolAgentId === undefined && previous.payload.state === 'done' && previous.payload.sessionBoundary !== true && previous.providerSessionOnly !== true && diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index 28aada4b63b4..c1c6c40ba457 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -6,7 +6,11 @@ import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { terminalStatusPayloadMatchesHook } from '../../../shared/agent-status/lifecycle/agent-terminal-status-equivalence' -import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' +import { + pickParsedAgentStatusPayload, + type ParsedAgentStatusPayload +} from '../../../shared/agent-status/contracts/agent-status-types' +import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' import type { EnrichedAgentHookEventPayload } from './server-types' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' @@ -26,8 +30,10 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges if (!parsedPaneKey || paneKey.length > MAX_PANE_KEY_LEN) { return } - this.forgetAgentExitBefore(paneKey, event.launchedAt) const previous = this.state.lastStatusByPaneKey.get(paneKey) + // Check saved turn authority before the new process forgets its predecessor's exit. + const savedIdentity = !previous ? this.paneAgentIdentity(paneKey) : null + this.forgetAgentExitBefore(paneKey, event.launchedAt) const sameConversation = previous?.payload.agentType === event.agentType && agentProviderSessionsEqual(event.agentType, previous?.providerSession, event.providerSession) @@ -42,6 +48,38 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges ) { return } + if ( + savedIdentity && + !savedIdentity.ended && + savedIdentity.status.agentType === event.agentType && + sameAgentStatusTerminalOwner(savedIdentity.status, { ...event, connectionId: null }) && + agentProviderSessionsEqual( + event.agentType, + savedIdentity.status.providerSession, + event.providerSession + ) + ) { + const status = savedIdentity.status + const recovered: EnrichedAgentHookEventPayload = { + paneKey, + tabId: parsedPaneKey.tabId, + worktreeId: status.worktreeId, + connectionId: status.connectionId, + providerSession: event.providerSession, + receivedAt: status.receivedAt, + stateStartedAt: status.stateStartedAt, + evidenceObservedAt: Date.now(), + payload: pickParsedAgentStatusPayload(status) + } + recovered.observation = this.stampObservation(recovered, 'launch', Date.now()) + if (this.writeLegacyStatusRow(recovered)) { + this.commitStatusRowMutation(undefined, recovered) + this.scheduleStatusPersist() + this.notifyStatusChangeListeners() + this.onAgentStatus?.({ ...recovered, isReplay: true }) + } + return + } const identity: AgentHookEventPayload & Pick = { paneKey, diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index 36735b52bcdf..505e1fa72730 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -50,7 +50,11 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF terminalHandle: _handle, ...accepted } = row - const rest = { ...accepted, evidenceObservedAt: Date.now() } + const rest = { + ...accepted, + evidenceObservedAt: Date.now(), + observation: this.stampObservation(accepted, 'launch', Date.now()) + } admitLegacyAgentStatus( this.state, 'main-status-cleanup', @@ -107,6 +111,7 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF !previous || !identity || identity.ended || + identity.processTopology === 'shared' || this.terminalPaneLifecycle?.isReversibleStop(ptyId, incarnationId) !== true || this.terminalPaneLifecycle.isPlaced(previous) !== true ) { diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 2600e8d6cbbf..34ed484e26b0 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -44,6 +44,7 @@ import type { import { RevisionedMap } from './revisioned-map' import { recordAgentExit, forgetAgentExit, type AgentExitEvidence } from './agent-exit-evidence' import { paneAgentIdentity, type PaneAgentIdentity } from './pane-agent-identity' +import { cliWriterTopology } from './cli-writer-observation' import { toAgentStatusIpcPayload } from './server-status-identity' import type { AgentProcessPresence } from '../../../shared/agent-status/process/agent-process-presence' import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' @@ -82,7 +83,7 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract worktreeId ??= savedRecord?.worktreeId const exit = this.agentExitedAtByPaneKey.get(resolved) ?? this.agentExitedAtByPaneKey.get(paneKey) - return paneAgentIdentity({ + const identity = paneAgentIdentity({ paneKey: resolved, ...(row ? { row: toAgentStatusIpcPayload(this.programStatusFacets.stitch(row)) } : {}), ...(savedRecord ? { savedRecord } : {}), @@ -90,6 +91,12 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract ...(exit ? { exitedAt: exit.at } : {}), ended: row?.agentPresence?.ended === true }) + return identity + ? { + ...identity, + processTopology: row ? (legacy ? cliWriterTopology(row) : 'shared') : 'pane-owned' + } + : null } protected recordPaneAgentExit(paneKey: string, endedPresence: AgentProcessPresence): void { diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts index eed13cd559fc..33df954902f6 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts @@ -1,4 +1,6 @@ import { expect, it } from 'vitest' +import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' +import { captureWorktreeSleepResumeRecords } from '../../../../runtime/terminal/stop/worktree-sleep-resume-records' import { AgentHookServer } from '../../agent-hook-server' import { PANE } from '../server.test-fixtures' import { resumeStatusFromHookRow } from '../../../../runtime/terminal/stop/hook-status-resume-records' @@ -73,3 +75,150 @@ it.each(['claude', 'codex'] as const)( } } ) + +it.each(['claude', 'codex'] as const)( + 'recovers saved %s Interrupted before hooks and keeps it until a new turn', + async (agent) => { + for (const origin of ['live', 'worktree-sleep'] as const) { + let saved: SleepingAgentSessionRecord = { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + agent, + providerSession: { key: 'session_id', id: `${agent}-saved-session` }, + prompt: 'Interrupted task', + state: 'done', + interrupted: true, + mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: 100 }, + capturedAt: 100, + updatedAt: 100, + origin, + connectionId: null + } + let stopping = false + const server = new AgentHookServer() + server.setTerminalPaneLifecycle({ + readSavedRecord: () => saved, + ownsProcess: () => true, + isStopping: () => stopping, + isReversibleStop: () => stopping, + isPlaced: () => true + }) + const read = () => server.getStatusSnapshotForPane(PANE)[0] + const launch = () => + server.recordLaunchResumeIdentity({ + paneKey: PANE, + worktreeId: 'wt-1', + agentType: agent, + providerSession: saved.providerSession, + launchedAt: Date.now() + }) + const publish = (newTurn: boolean) => + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + source: agent, + hookEventName: newTurn ? 'UserPromptSubmit' : 'SessionStart', + hasExplicitPrompt: newTurn, + providerSession: saved.providerSession, + payload: { + agentType: agent, + state: newTurn ? 'working' : 'done', + prompt: newTurn ? 'Next task' : '', + ...(newTurn ? {} : { sessionBoundary: true }) + } + }, + null + ) + try { + launch() + expect(read()).toMatchObject({ + state: 'done', + interrupted: true, + mainAgent: { state: 'done', outcome: 'cancellation' } + }) + publish(false) + expect(read()).toMatchObject({ state: 'done', interrupted: true }) + server.dropStatusEntry(PANE, { preserveResumeIdentity: false }) + expect(read()).toBeUndefined() + stopping = true + expect(server.settleTerminalPaneSleep(PANE, 'pty', 'birth')).toBe(true) + stopping = false + const capture = await captureWorktreeSleepResumeRecords({ + worktreeId: 'wt-1', + paneKeysByPtyId: new Map([['pty', [PANE]]]), + launchByPtyId: new Map(), + readRowsForPane: (paneKey) => server.getStatusSnapshotForPane(paneKey), + checkAgentPresence: null, + capturedAt: Date.now() + }) + saved = capture.get('pty')!.records[0]! + expect(saved).toMatchObject({ + origin: 'worktree-sleep', + state: 'done', + interrupted: true, + providerSession: { key: 'session_id', id: `${agent}-saved-session` } + }) + server.retireSleepingPaneOnSpawn(PANE, { + agentType: agent, + providerSession: saved.providerSession + }) + launch() + publish(false) + stopping = true + expect(server.settleTerminalPaneSleep(PANE, 'pty-2', 'birth-2')).toBe(true) + stopping = false + expect(read()).toMatchObject({ state: 'done', interrupted: true }) + server.retireSleepingPaneOnSpawn(PANE, { + agentType: agent, + providerSession: saved.providerSession + }) + publish(true) + expect(read()).toMatchObject({ state: 'working', prompt: 'Next task' }) + expect(read()?.interrupted).not.toBe(true) + } finally { + server.stop() + } + } + } +) + +it('does not recover a saved Interrupted turn after its conversation exited', () => { + const saved: SleepingAgentSessionRecord = { + paneKey: PANE, + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'quit-session' }, + prompt: 'Interrupted task', + state: 'done', + interrupted: true, + capturedAt: 100, + updatedAt: 100, + origin: 'worktree-sleep' + } + const server = new AgentHookServer() + server.setTerminalPaneLifecycle({ + readSavedRecord: () => saved, + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => false, + isPlaced: () => true + }) + try { + server.retireProcessAuthority(PANE, { confirmedExit: true }) + expect(server.paneAgentIdentity(PANE)?.ended).toBe(true) + server.recordLaunchResumeIdentity({ + paneKey: PANE, + worktreeId: 'wt-1', + agentType: 'codex', + providerSession: saved.providerSession, + launchedAt: Date.now() + 1 + }) + expect(server.getPublicStatusSnapshotForPane(PANE)).toEqual([]) + expect(server.paneAgentIdentity(PANE)?.status.interrupted).not.toBe(true) + } finally { + server.stop() + } +}) diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts index 49376d262466..a32c1e5bf987 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts @@ -1,6 +1,7 @@ import { createHash } from 'node:crypto' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AgentHookServer, _internals } from '../../agent-hook-server' +import { captureWorktreeSleepResumeRecords } from '../../../../runtime/terminal/stop/worktree-sleep-resume-records' import { postHookEvent } from '../server.test-fixtures' import { TMUX_TEST_PANE, @@ -58,7 +59,7 @@ describe('main canonical tmux projection', () => { expect(server.getCanonicalStatusSnapshot().parents).toHaveLength(0) expect(server.getStatusSnapshot()).toHaveLength(0) }) - it('keeps one sleeping row when the canonical selected agent stops with its pane', async () => { + it('does not resume an inner agent whose tmux server outlives the sleeping pane', async () => { await postHookEvent(server, tmuxTestBody(), '/hook/opencode') server.setTerminalPaneLifecycle({ ownsProcess: () => true, @@ -66,12 +67,22 @@ describe('main canonical tmux projection', () => { isReversibleStop: () => true, isPlaced: () => true }) - expect(server.settleTerminalPaneSleep(TMUX_TEST_PANE, 'pty', 'birth')).toBe(true) + const capture = await captureWorktreeSleepResumeRecords({ + worktreeId: 'workspace', + paneKeysByPtyId: new Map([['pty', [TMUX_TEST_PANE]]]), + launchByPtyId: new Map(), + readRowsForPane: (key) => server.getStatusSnapshotForPane(key), + readIdentity: (key) => server.paneAgentIdentity(key), + checkAgentPresence: null, + capturedAt: 200 + }) + expect(capture.get('pty')).toMatchObject({ + records: [], + retiredPaneKeys: [TMUX_TEST_PANE] + }) + expect(server.settleTerminalPaneSleep(TMUX_TEST_PANE, 'pty', 'birth')).toBe(false) server.reconcileEndedProcessForPaneKeys([TMUX_TEST_PANE]) - expect(server.getStatusSnapshot()).toMatchObject([ - { paneKey: TMUX_TEST_PANE, state: 'done', paneSleep: { ptyId: 'pty' } } - ]) - expect(server.getStatusSnapshot()).toHaveLength(1) + expect(server.getStatusSnapshot()).toHaveLength(0) }) it('removes canonical tmux status on certified retirement', async () => { await postHookEvent(server, tmuxTestBody(), '/hook/opencode') diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index b9446f2193af..05bd36664b77 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -16,11 +16,11 @@ export function bindTerminalPaneStatusLifecycle( retireSavedRecord: (paneKey, exitedAt) => runtime?.retireExitedPaneResume(paneKey, exitedAt), readSavedRecord: (paneKey) => { try { - const pane = runtime?.resolveTerminalPane(paneKey) - if (!pane?.worktreeId) { + const worktreeId = runtime?.getTerminalWorktreeIdForPaneKey(paneKey) + if (!worktreeId) { return undefined } - return runtime?.getWorkspaceSessionForWorktree(pane.worktreeId) + return runtime?.getWorkspaceSessionForWorktree(worktreeId) ?.sleepingAgentSessionsByPaneKey?.[paneKey] } catch { return undefined diff --git a/src/main/runtime/construction/runtime-agent-status-sources.ts b/src/main/runtime/construction/runtime-agent-status-sources.ts index fdfe6a6202b6..dcceb9d4735d 100644 --- a/src/main/runtime/construction/runtime-agent-status-sources.ts +++ b/src/main/runtime/construction/runtime-agent-status-sources.ts @@ -35,15 +35,28 @@ export abstract class RuntimeAgentStatusSources extends OrcaRuntimeWithTerminalD protected paneAgentStatuses( rows: readonly AgentStatusIpcPayload[] = this.getAgentProviderSessionSnapshotFn?.() ?? this.getAgentStatusSnapshotFn?.() ?? - [] + [], + savedRecords: Iterable = [] ): AgentStatusIpcPayload[] { - return rows.flatMap((row) => { + const paneKeys = new Set(rows.map((row) => row.paneKey)) + const statuses = rows.flatMap((row) => { if (row.structuredHost) { return [row] } const identity = this.readPaneAgentIdentity(row.paneKey, undefined, row) return identity && !identity.ended ? [identity.status] : [] }) + for (const record of savedRecords) { + if (paneKeys.has(record.paneKey)) { + continue + } + const identity = this.readPaneAgentIdentity(record.paneKey, record) + if (identity && !identity.ended) { + paneKeys.add(record.paneKey) + statuses.push(identity.status) + } + } + return statuses } readonly getAgentStatusSnapshotFn!: HostBindings['getAgentStatusSnapshot'] | null diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 4df79612a26a..1af2acb7854b 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -248,7 +248,7 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu paneKey, session.sleepingAgentSessionsByPaneKey?.[paneKey] ) - if (!identity || identity.ended) { + if (!identity || identity.ended || identity.processTopology === 'shared') { return [] } const status = resumeStatusFromHookRow( diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts index 0667ac5e9ad3..8a140fca1b72 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts @@ -79,7 +79,11 @@ export async function captureWorktreeSleepResumeRecords(args: { worktreeId: args.worktreeId, ended: presence === 'exited' }) - if (identity?.ended || (presence === 'exited' && !identity?.status.paneSleep)) { + if ( + identity?.ended || + identity?.processTopology === 'shared' || + (presence === 'exited' && !identity?.status.paneSleep) + ) { retiredPaneKeys.push(paneKey) continue } diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-ps-activity.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-ps-activity.ts index f746fb337669..b3b7b62e9db8 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-ps-activity.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-ps-activity.ts @@ -1,3 +1,4 @@ +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import type { RuntimeSyncedTab } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import type { RuntimeWorktreePsSummary } from '../../../../shared/worktree/catalog/runtime-worktree-contracts' import type { Repo } from '../../../../shared/repository/repo-types' @@ -208,6 +209,7 @@ export function applyRuntimeWorktreePsSessionActivity(args: { getSummary: RuntimeWorktreePsSummaryLookup }): { mirroredWorktreeIdByTabId: Map + savedAgentRecords: SleepingAgentSessionRecord[] connectedPtyEvidence: { tabIds: Set paneKeys: Set @@ -225,8 +227,10 @@ export function applyRuntimeWorktreePsSessionActivity(args: { sessionsByHostId.set(hostId, session) } } + const savedAgentRecords: SleepingAgentSessionRecord[] = [] // Each host's session names that host's copy of a same-id workspace. for (const [hostId, session] of sessionsByHostId) { + savedAgentRecords.push(...Object.values(session.sleepingAgentSessionsByPaneKey ?? {})) const getSummary = (worktreeId: string) => args.getSummary(worktreeId, hostId) for (const [worktreeId, tabs] of Object.entries(session.tabsByWorktree ?? {})) { for (const tab of tabs) { @@ -278,5 +282,5 @@ export function applyRuntimeWorktreePsSessionActivity(args: { connectedPtyEvidence.ptyIdByTerminalHandle.set(terminalHandle, pty.ptyId) } } - return { mirroredWorktreeIdByTabId, connectedPtyEvidence } + return { mirroredWorktreeIdByTabId, connectedPtyEvidence, savedAgentRecords } } diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index cf74b1692b42..4e7cf7640c56 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -118,7 +118,7 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven getLivenessVerdict: (ptyId) => this.getPtyLivenessVerdict(ptyId), getSummary }) - const { mirroredWorktreeIdByTabId, connectedPtyEvidence } = + const { mirroredWorktreeIdByTabId, connectedPtyEvidence, savedAgentRecords } = applyRuntimeWorktreePsSessionActivity({ store: this.store, summaries, @@ -132,7 +132,7 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven const rowSources = collectRuntimeWorktreeAgentSources({ mirroredWorktreeIdByTabId, connectedPtyEvidence, - hookSnapshots: this.paneAgentStatuses(), + hookSnapshots: this.paneAgentStatuses(undefined, savedAgentRecords), readStructuredSummary: getStructuredAgentSessionHost()?.readStatusSummary }) attachRuntimeWorktreeAgentRows({ diff --git a/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts b/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts index 195a5672a3a3..dec01bf76faa 100644 --- a/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts +++ b/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts @@ -17,6 +17,7 @@ export type AgentFinishDropCause = | 'turn-end-not-counted' | 'restored-unconfirmed' | 'host-replay-skipped' + | 'resume-restatement' /** Every path that drops a finish was silent, so a missing unread could not be traced (#40340). */ export function recordAgentFinishDropped( diff --git a/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.ts b/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.ts index bceb35620a9e..f4828a67d5c1 100644 --- a/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.ts +++ b/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.ts @@ -108,6 +108,20 @@ export function dispatchTerminalNotification( agentSnapshotMatchesExplicitTitle(storedAgentStatus, explicitTitleAgentType) ? storedAgentStatus : undefined + // A launch restores the accepted turn; only later agent evidence can finish another one. + if ( + event.source === 'agent-task-complete' && + storedAgentStatus?.state === 'done' && + storedAgentStatus.observation?.origin === 'launch' && + (!eventAgentStatusSnapshot || + eventAgentStatusSnapshot.stateStartedAt === storedAgentStatus.stateStartedAt) + ) { + recordAgentFinishDropped('resume-restatement', { + workspaceId: worktreeId, + paneKey: event.paneKey + }) + return false + } if ( event.source === 'agent-task-complete' && event.agentCompletionSource !== 'process-exit' && diff --git a/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts b/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts new file mode 100644 index 000000000000..2ec255dc05fd --- /dev/null +++ b/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts @@ -0,0 +1,187 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusSetData } from './ipc-events-agent-status-store-test-fixtures' +import { buildWindowApi } from './ipc-events-agent-status-window-test-fixtures' +import { makeTab } from '../store/terminals/testing/terminal-tab.test-fixture' +import { makeUnifiedTab } from '../store/slices/tabs/tab-group.test-fixture' +import { makeWorktree } from '../store/slices/worktrees/worktree.test-fixture' +import { TEST_REPO } from '../store/repos/repo.test-fixture' +import { setPresenceGated } from './agent-auto-ack-presence' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { registerAgentStatusIpcBridge } from './ipc-events/agent-status-ipc-bridge' +import { dispatchTerminalNotification } from '../components/terminal-pane/notifications/dispatch-terminal-notification' +import { useAppStore } from '../store' + +vi.mock('../store', async () => { + const { createTestStore } = await import('../store/testing/app-store-test-fixture') + return { useAppStore: createTestStore() } +}) +// The lanes are replaced by direct restatements below; only admission is under test. +vi.mock('./agent-hook-completion-notifications', () => ({ + observeAgentHookCompletionForNotification: vi.fn(), + syncAgentHookCompletionNotificationsForStoreUpdate: () => {} +})) +vi.mock('@/lib/notifications/desktop-notification-sound', () => ({ + playDesktopNotificationSound: vi.fn() +})) +vi.mock('@/store/slices/worktrees/metadata/worktree-meta-persist', () => ({ + persistWorktreeMeta: vi.fn(async () => undefined) +})) + +const NOW = 1_800_000_000_000 +const WORKSPACE = 'repo1::/tmp/sleep' +const LEAF = '11111111-1111-4111-8111-111111111111' +const PANE = `tab-1:${LEAF}` +const notifications = vi.fn(async () => ({ delivered: true })) + +function bindPty(ptyId: string): void { + const layout = useAppStore.getState().terminalLayoutsByTabId['tab-1'] + useAppStore.setState({ + tabsByWorktree: { [WORKSPACE]: [makeTab({ id: 'tab-1', worktreeId: WORKSPACE, ptyId })] }, + ptyIdsByTabId: { 'tab-1': [ptyId] }, + terminalLayoutsByTabId: { 'tab-1': { ...layout, ptyIdsByLeafId: { [LEAF]: ptyId } } } + }) +} + +let send: (event: AgentStatusSetData) => void +let disposeBridge: () => void + +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(NOW) + setPresenceGated(false) + notifications.mockClear() + vi.stubGlobal('document', { visibilityState: 'hidden', hasFocus: () => false }) + const windowApi = buildWindowApi({ + onSet: (listener) => { + send = listener + return () => {} + } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture builds `api` as a plain record. + ;(windowApi.api as Record).notifications = { dispatch: notifications } + vi.stubGlobal('window', windowApi) + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ + workspaceSessionReady: true, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only notification policy fields are read. + settings: { experimentalTerminalAttention: true } as GlobalSettings, + repos: [{ ...TEST_REPO, executionHostId: 'local' }], + worktreesByRepo: { + repo1: [makeWorktree({ id: WORKSPACE, repoId: 'repo1', hostId: 'local' })] + }, + unifiedTabsByWorktree: { + [WORKSPACE]: [ + makeUnifiedTab({ + id: 'tab-1', + entityId: 'tab-1', + contentType: 'terminal', + groupId: 'group-1', + worktreeId: WORKSPACE, + executionHostId: 'local' + }) + ] + }, + terminalLayoutsByTabId: { + 'tab-1': { root: { type: 'leaf', leafId: LEAF }, activeLeafId: LEAF, expandedLeafId: null } + }, + activeWorktreeId: null + }) + bindPty('pty-1') + const unsubs: (() => void)[] = [] + const bridge = registerAgentStatusIpcBridge(unsubs) + disposeBridge = () => { + bridge.disposeAsyncState() + bridge.unsubscribeStore() + for (const stop of unsubs) { + stop() + } + } +}) + +afterEach(() => { + disposeBridge() + setPresenceGated(true) + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +describe('waking a pane slept mid-turn', () => { + it.each(['claude', 'codex'] as const)( + 'announces no %s finish until the pane runs a new turn', + async (agentType) => { + const working: AgentStatusSetData = { + paneKey: PANE, + connectionId: null, + tabId: 'tab-1', + worktreeId: WORKSPACE, + state: 'working', + prompt: 'Run delayed shell command', + agentType, + receivedAt: NOW, + stateStartedAt: NOW + } + send(working) + const slept = { + ...working, + state: 'done' as const, + interrupted: true, + stateStartedAt: NOW + 5 + } + send({ ...slept, paneSleep: { ptyId: 'pty-1' }, isReplay: true }) + vi.advanceTimersByTime(40) + vi.setSystemTime(NOW + 30_000) + bindPty('pty-2') + // Main hands the slept turn back to the resumed process. + send({ + ...slept, + isReplay: true, + observation: { + origin: 'launch', + authorityId: 'main', + incarnation: 2, + revision: 3, + observedAt: NOW + 30_000, + kind: 'snapshot' + } + }) + vi.advanceTimersByTime(40) + + // The title lane reads the resumed agent's startup spinner; the hook lane re-sees the verdict. + dispatchTerminalNotification(WORKSPACE, { + source: 'agent-task-complete', + terminalTitle: 'Run delayed shell command', + paneKey: PANE + }) + dispatchTerminalNotification(WORKSPACE, { + source: 'agent-task-complete', + terminalTitle: agentType, + paneKey: PANE, + agentStatusSnapshot: { + state: 'done', + prompt: slept.prompt ?? '', + agentType, + interrupted: true, + stateStartedAt: slept.stateStartedAt + } + }) + await vi.advanceTimersByTimeAsync(2000) + expect(notifications).not.toHaveBeenCalled() + expect(useAppStore.getState().worktreesByRepo.repo1[0].isUnread).toBe(false) + + const turnAt = Date.now() + send({ ...working, receivedAt: turnAt, stateStartedAt: turnAt }) + send({ ...working, state: 'done', receivedAt: turnAt + 10, stateStartedAt: turnAt + 10 }) + vi.advanceTimersByTime(40) + dispatchTerminalNotification(WORKSPACE, { + source: 'agent-task-complete', + terminalTitle: 'Run delayed shell command', + paneKey: PANE + }) + await vi.advanceTimersByTimeAsync(2000) + expect(notifications).toHaveBeenCalledWith( + expect.objectContaining({ source: 'agent-task-complete', paneKey: PANE, agentType }) + ) + expect(useAppStore.getState().worktreesByRepo.repo1[0].isUnread).toBe(true) + } + ) +}) diff --git a/src/shared/agent-session/lifecycle/resume/promote-saved-live-resume-record.ts b/src/shared/agent-session/lifecycle/resume/promote-saved-live-resume-record.ts index 6b074603d2ee..5f97a54a064c 100644 --- a/src/shared/agent-session/lifecycle/resume/promote-saved-live-resume-record.ts +++ b/src/shared/agent-session/lifecycle/resume/promote-saved-live-resume-record.ts @@ -1,22 +1,30 @@ import { getAgentResumeArgv } from '../../../agent-launch/startup/agent-resume-argv' -import { isResumableTuiAgent, type SleepingAgentSessionRecord } from '../agent-session-resume' +import { + isPaneSleepRecord, + isResumableTuiAgent, + type SleepingAgentSessionRecord +} from '../agent-session-resume' /** Promote the pane's live checkpoint when its volatile status is missing. */ export function promoteSavedLiveResumeRecord(args: { record: SleepingAgentSessionRecord | undefined worktreeId: string capturedAt: number + includeSleepRecord?: boolean }): SleepingAgentSessionRecord | null { const { record, worktreeId, capturedAt } = args if ( !record || record.worktreeId !== worktreeId || - record.origin !== 'live' || + (record.origin !== 'live' && !(args.includeSleepRecord && isPaneSleepRecord(record))) || !isResumableTuiAgent(record.agent) || !getAgentResumeArgv(record.agent, record.providerSession) ) { return null } + if (record.origin !== 'live') { + return record + } return { ...record, state: 'working', From a9a8262753ad1ec438e84913fd6d209a25def01e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:14:58 -0800 Subject: [PATCH 021/125] Keep accepted turns through startup restatements and separate sleep from quit --- .../observations/local-hook-root-evidence.ts | 14 +- .../agent-hooks/server/agent-hook-server.ts | 38 ++++- .../server/cli-writer-observation.ts | 11 +- .../server/pane-agent-turn-continuity.ts | 22 ++- .../server/server-ingest-launch.ts | 83 +++++++++++ .../server/server-ingest-normalization.ts | 9 +- .../server/server-ingest-terminal.ts | 85 +---------- .../agent-hooks/server/server-pane-sleep.ts | 3 +- .../server/server-status-application.ts | 6 +- .../server/server-status-row-mutation.ts | 6 +- .../server/server-status-update.ts | 7 +- .../server-pane-saved-sleep.test.ts | 19 ++- .../persistence/server-pane-sleep.test.ts | 11 +- .../tmux/server-tmux-canonical.test.ts | 14 +- .../tmux/server-tmux-legacy-sleep.test.ts | 67 +++++++++ .../worktree-ps-saved-sleep.test.ts | 135 ++++++++++++++++++ ...agent-status-sleep-wake-completion.test.ts | 11 +- .../presence/hook-process-root-evidence.ts | 40 +++++- 18 files changed, 467 insertions(+), 114 deletions(-) create mode 100644 src/main/agent-hooks/server/server-ingest-launch.ts create mode 100644 src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts create mode 100644 src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts diff --git a/src/main/agent-hooks/observations/local-hook-root-evidence.ts b/src/main/agent-hooks/observations/local-hook-root-evidence.ts index 413ae59469b6..bfa53b8a9c4b 100644 --- a/src/main/agent-hooks/observations/local-hook-root-evidence.ts +++ b/src/main/agent-hooks/observations/local-hook-root-evidence.ts @@ -5,6 +5,8 @@ import { type LocalPtyInventoryReader } from './local-tmux-managed-pty' import { createLocalHookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' +import { readPaneTmuxHost } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import { readSelectedRows, readTerminalRows } from '../../../shared/tmux-host-attachment-probe' import { getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' @@ -16,8 +18,16 @@ export function installLocalHookRootEvidence(server: AgentHookServer): LocalPtyI listProcesses: () => getLocalPtyProvider().listProcesses() }) if (process.platform !== 'win32') { - server.setHookRootEvidenceReader( - createLocalHookRootEvidenceReader(createLocalHookPaneRootResolver(readInventory)) + const resolveRoot = createLocalHookPaneRootResolver(readInventory) + server.setHookRootEvidenceReader(createLocalHookRootEvidenceReader(resolveRoot), (request) => + readPaneTmuxHost( + { + resolveRoot, + readProcesses: (pids) => readSelectedRows(pids).catch(() => []), + readTerminal: (tty) => readTerminalRows(tty).catch(() => []) + }, + request + ) ) } return readInventory diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 69c74729a701..ee095e4d7b05 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -4,7 +4,11 @@ import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normal import { parseFormEncodedBody } from '../../../shared/agent-hook-listener/request-body' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' -import { cliWriterTopology, type CliWriterObservation } from './cli-writer-observation' +import { + cliWriterTopology, + retainTmuxWriterTopology, + type CliWriterObservation +} from './cli-writer-observation' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' import { @@ -114,7 +118,10 @@ export class AgentHookServer extends AgentHookServerLifecycle { paneKey: string, exitedSince: number ): Promise { - const verdict = await this.checkAgentPresence(paneKey) + const [verdict] = await Promise.all([ + this.checkAgentPresence(paneKey), + this.observeTmuxHostedWriter(paneKey) + ]) // A replaced owner's probe result counts only if its exit was retained. if (verdict !== null && verdict !== 'exited') { return verdict @@ -130,6 +137,33 @@ export class AgentHookServer extends AgentHookServerLifecycle { return exit !== undefined && exit.at >= exitedSince ? 'exited' : null } + /** Legacy hooks cannot say a tmux server hosts them; the pane's foreground client can, before + * a sleep or adoption captures the conversation as the pane's own. */ + private async observeTmuxHostedWriter(paneKey: string): Promise { + const resolved = this.resolvePaneKeyAlias(paneKey) + const row = this.state.lastStatusByPaneKey.get(resolved) + const binding = row?.providerSession + const read = this.readPaneTmuxHost + if ( + !read || + !row || + !binding || + row.connectionId !== null || + cliWriterTopology(row) !== 'pane-owned' + ) { + return + } + const presence = row.agentPresence + const hosted = await read({ + paneKey: resolved, + worktreeId: row.worktreeId, + ...(presence?.process && !presence.ended ? { process: presence.process } : {}) + }).catch(() => false) + if (hosted && this.state.lastStatusByPaneKey.get(resolved)?.providerSession === binding) { + retainTmuxWriterTopology(binding) + } + } + checkAgentPresence(paneKey: string): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) this.followClaudeSessionContinuation(resolved) diff --git a/src/main/agent-hooks/server/cli-writer-observation.ts b/src/main/agent-hooks/server/cli-writer-observation.ts index 8900969fb11b..b70d1d14e9e4 100644 --- a/src/main/agent-hooks/server/cli-writer-observation.ts +++ b/src/main/agent-hooks/server/cli-writer-observation.ts @@ -68,10 +68,19 @@ export function tmuxCliWriterEvent(row: T): T { return row } const providerSession = { ...row.providerSession } - Object.defineProperty(providerSession, OPEN_CODE_WRITER_TOPOLOGY, { value: 'shared' }) + retainTmuxWriterTopology(providerSession) return { ...row, providerSession } } +/** A binding the pane reaches through a tmux client; a decided binding keeps its topology. */ +export function retainTmuxWriterTopology( + binding: NonNullable +): void { + if (!(OPEN_CODE_WRITER_TOPOLOGY in binding) && Object.isExtensible(binding)) { + Object.defineProperty(binding, OPEN_CODE_WRITER_TOPOLOGY, { value: 'shared' }) + } +} + export type CliWriterExecutionMatches = ( row: AgentHookEventPayload, baseline?: AgentHookEventPayload diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index 30a22e40d935..5bdffca38f61 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -1,4 +1,5 @@ import type { EnrichedAgentHookEventPayload } from './server-types' +import type { AgentStatusObservationOrigin } from '../../../shared/agent-status/contracts/agent-status-observation' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' @@ -6,17 +7,18 @@ import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/ident /** A boundary for the conversation whose turn the pane last accepted keeps that turn's verdict. */ export function resumedAcceptedTurn( previous: EnrichedAgentHookEventPayload, - incoming: AgentHookEventPayload + incoming: AgentHookEventPayload, + origin: AgentStatusObservationOrigin ): EnrichedAgentHookEventPayload | null { const continuesTurn = - (incoming.payload.agentType === 'claude' || previous.payload.interrupted === true) && - incoming.payload.sessionBoundary === true && - incoming.hasExplicitPrompt !== true && + (incoming.payload.agentType === 'claude' || previous.observation?.origin === 'launch') && + (incoming.payload.sessionBoundary === true || + (origin === 'osc' && previous.observation?.origin === 'launch')) && + incoming.payload.state === 'done' && incoming.toolAgentId === undefined && previous.payload.state === 'done' && previous.payload.sessionBoundary !== true && previous.providerSessionOnly !== true && - previous.paneSleep === undefined && previous.providerSession !== undefined && previous.payload.agentType === incoming.payload.agentType && sameAgentStatusTerminalOwner(previous, incoming) && @@ -28,11 +30,17 @@ export function resumedAcceptedTurn( if (!continuesTurn) { return null } - const { agentPresence: _sleptOwner, restoredUnconfirmed: _restored, ...accepted } = previous + const { + agentPresence: _sleptOwner, + restoredUnconfirmed: _restored, + paneSleep: _sleep, + ...accepted + } = previous return { ...accepted, ...(incoming.providerSession ? { providerSession: incoming.providerSession } : {}), - ...(incoming.agentPresence ? { agentPresence: incoming.agentPresence } : {}) + ...(incoming.agentPresence ? { agentPresence: incoming.agentPresence } : {}), + ...(incoming.terminalHandle ? { terminalHandle: incoming.terminalHandle } : {}) } } diff --git a/src/main/agent-hooks/server/server-ingest-launch.ts b/src/main/agent-hooks/server/server-ingest-launch.ts new file mode 100644 index 000000000000..fd9cde1d57e0 --- /dev/null +++ b/src/main/agent-hooks/server/server-ingest-launch.ts @@ -0,0 +1,83 @@ +import type { LaunchResumeIdentityEvent } from './launch-resume-identity-event' +import { MAX_PANE_KEY_LEN } from '../../../shared/agent-hook-listener/listener-limits' +import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' +import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' +import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' +import { pickParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' +import type { EnrichedAgentHookEventPayload } from './server-types' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import { AgentHookServerIngestNormalization } from './server-ingest-normalization' + +export abstract class AgentHookServerIngestLaunch extends AgentHookServerIngestNormalization { + /** Seed resume identity before the first hook; Codex SessionStart waits for the first turn (#10923). */ + recordLaunchResumeIdentity(event: LaunchResumeIdentityEvent): void { + const paneKey = this.resolvePaneKeyAlias(event.paneKey.trim()) + const parsedPaneKey = parsePaneKey(paneKey) + if (!parsedPaneKey || paneKey.length > MAX_PANE_KEY_LEN) { + return + } + const previous = this.state.lastStatusByPaneKey.get(paneKey) + // Check saved turn authority before the new process forgets its predecessor's exit. + const savedIdentity = !previous ? this.paneAgentIdentity(paneKey) : null + this.forgetAgentExitBefore(paneKey, event.launchedAt) + const sameConversation = + previous?.payload.agentType === event.agentType && + agentProviderSessionsEqual(event.agentType, previous?.providerSession, event.providerSession) + if ( + previous && + !previous.agentPresence?.ended && + (sameConversation || + (previous.providerSessionOnly !== true && + 'receivedAt' in previous && + typeof previous.receivedAt === 'number' && + previous.receivedAt >= event.launchedAt)) + ) { + return + } + if ( + savedIdentity && + !savedIdentity.ended && + savedIdentity.status.agentType === event.agentType && + sameAgentStatusTerminalOwner(savedIdentity.status, { ...event, connectionId: null }) && + agentProviderSessionsEqual( + event.agentType, + savedIdentity.status.providerSession, + event.providerSession + ) + ) { + const status = savedIdentity.status + const recovered: EnrichedAgentHookEventPayload = { + paneKey, + tabId: parsedPaneKey.tabId, + worktreeId: status.worktreeId, + connectionId: status.connectionId, + providerSession: event.providerSession, + receivedAt: status.receivedAt, + stateStartedAt: status.stateStartedAt, + evidenceObservedAt: Date.now(), + payload: pickParsedAgentStatusPayload(status) + } + recovered.observation = this.stampObservation(recovered, 'launch', Date.now()) + if (this.writeLegacyStatusRow(recovered)) { + this.commitStatusRowMutation(undefined, recovered) + this.scheduleStatusPersist() + this.notifyStatusChangeListeners() + this.onAgentStatus?.({ ...recovered, isReplay: true }) + } + return + } + const identity: AgentHookEventPayload & + Pick = { + paneKey, + tabId: parsedPaneKey.tabId, + ...(event.worktreeId?.trim() ? { worktreeId: event.worktreeId.trim() } : {}), + connectionId: null, + providerSession: event.providerSession, + providerSessionOnly: true, + // Hydration must retain this identity even if no first turn occurs before restart. + retainedForLiveness: true, + payload: { state: 'done', prompt: '', agentType: event.agentType } + } + this.applyNormalizedStatus(identity, undefined, 'launch') + } +} diff --git a/src/main/agent-hooks/server/server-ingest-normalization.ts b/src/main/agent-hooks/server/server-ingest-normalization.ts index d9cd3dcd580d..1d1468308eef 100644 --- a/src/main/agent-hooks/server/server-ingest-normalization.ts +++ b/src/main/agent-hooks/server/server-ingest-normalization.ts @@ -8,7 +8,10 @@ import { checkHookOwnerPresence, restateHookRoot } from '../../../shared/agent-hook-listener/presence/agent-hook-owner-presence' -import type { HookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { + HookRootEvidenceReader, + PaneTmuxHostReader +} from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normalization/normalize-hook-payload' import { isAgentHookSource, @@ -26,9 +29,11 @@ export abstract class AgentHookServerIngestNormalization extends AgentHookServer protected readonly attributionDiagnostics = new AgentHookAttributionDiagnostics() /** Unset in tests and embedders without a process table: every acquisition reads as unknown. */ protected readHookRootEvidence: HookRootEvidenceReader | undefined + protected readPaneTmuxHost: PaneTmuxHostReader | undefined - setHookRootEvidenceReader(reader: HookRootEvidenceReader): void { + setHookRootEvidenceReader(reader: HookRootEvidenceReader, tmuxHost?: PaneTmuxHostReader): void { this.readHookRootEvidence = reader + this.readPaneTmuxHost = tmuxHost } /** Panes whose owner an undecided hook challenged: until that hook is admitted or refused, the diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index c1c6c40ba457..6afa7ab1a72b 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -1,4 +1,3 @@ -import type { LaunchResumeIdentityEvent } from './launch-resume-identity-event' import { trackEmptyPaneKeyHook } from './server-transport-rules' import { MAX_PANE_KEY_LEN } from '../../../shared/agent-hook-listener/listener-limits' import { @@ -6,95 +5,17 @@ import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { terminalStatusPayloadMatchesHook } from '../../../shared/agent-status/lifecycle/agent-terminal-status-equivalence' -import { - pickParsedAgentStatusPayload, - type ParsedAgentStatusPayload -} from '../../../shared/agent-status/contracts/agent-status-types' -import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' -import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' +import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' import type { EnrichedAgentHookEventPayload } from './server-types' -import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import { agentSubagentsEqual } from '../../../shared/agent-status/contracts/agent-status-subagent-snapshot' import { isAgentStatusHeldOpenByChildWork } from '../../../shared/agent-status/lifecycle/agent-lead-status-fold' -import { AgentHookServerIngestNormalization } from './server-ingest-normalization' +import { AgentHookServerIngestLaunch } from './server-ingest-launch' import { programStatusHookYieldEndsAt } from './program-status/hook-precedence' import type { ProgramStatusFacet } from '../../../shared/program-status/facet' const PROGRAM_STATUS_FACET_REPUBLISH_MS = 250 -export abstract class AgentHookServerIngestTerminal extends AgentHookServerIngestNormalization { - /** Seed resume identity before the first hook; Codex SessionStart waits for the first turn (#10923). */ - recordLaunchResumeIdentity(event: LaunchResumeIdentityEvent): void { - const paneKey = this.resolvePaneKeyAlias(event.paneKey.trim()) - const parsedPaneKey = parsePaneKey(paneKey) - if (!parsedPaneKey || paneKey.length > MAX_PANE_KEY_LEN) { - return - } - const previous = this.state.lastStatusByPaneKey.get(paneKey) - // Check saved turn authority before the new process forgets its predecessor's exit. - const savedIdentity = !previous ? this.paneAgentIdentity(paneKey) : null - this.forgetAgentExitBefore(paneKey, event.launchedAt) - const sameConversation = - previous?.payload.agentType === event.agentType && - agentProviderSessionsEqual(event.agentType, previous?.providerSession, event.providerSession) - if ( - previous && - !previous.agentPresence?.ended && - (sameConversation || - (previous.providerSessionOnly !== true && - 'receivedAt' in previous && - typeof previous.receivedAt === 'number' && - previous.receivedAt >= event.launchedAt)) - ) { - return - } - if ( - savedIdentity && - !savedIdentity.ended && - savedIdentity.status.agentType === event.agentType && - sameAgentStatusTerminalOwner(savedIdentity.status, { ...event, connectionId: null }) && - agentProviderSessionsEqual( - event.agentType, - savedIdentity.status.providerSession, - event.providerSession - ) - ) { - const status = savedIdentity.status - const recovered: EnrichedAgentHookEventPayload = { - paneKey, - tabId: parsedPaneKey.tabId, - worktreeId: status.worktreeId, - connectionId: status.connectionId, - providerSession: event.providerSession, - receivedAt: status.receivedAt, - stateStartedAt: status.stateStartedAt, - evidenceObservedAt: Date.now(), - payload: pickParsedAgentStatusPayload(status) - } - recovered.observation = this.stampObservation(recovered, 'launch', Date.now()) - if (this.writeLegacyStatusRow(recovered)) { - this.commitStatusRowMutation(undefined, recovered) - this.scheduleStatusPersist() - this.notifyStatusChangeListeners() - this.onAgentStatus?.({ ...recovered, isReplay: true }) - } - return - } - const identity: AgentHookEventPayload & - Pick = { - paneKey, - tabId: parsedPaneKey.tabId, - ...(event.worktreeId?.trim() ? { worktreeId: event.worktreeId.trim() } : {}), - connectionId: null, - providerSession: event.providerSession, - providerSessionOnly: true, - // Hydration must retain this identity even if no first turn occurs before restart. - retainedForLiveness: true, - payload: { state: 'done', prompt: '', agentType: event.agentType } - } - this.applyNormalizedStatus(identity, undefined, 'launch') - } - +export abstract class AgentHookServerIngestTerminal extends AgentHookServerIngestLaunch { ingestProgramStatusFacet(event: { paneKey: string; facet: ProgramStatusFacet | null }): void { const paneKey = this.resolvePaneKeyAlias(event.paneKey.trim()) if ( diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index 505e1fa72730..f2aff0fbc849 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -8,7 +8,7 @@ import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../../shared/agent-sta import { pickParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' import type { EnrichedAgentHookEventPayload } from './server-types' import { AgentHookServerAuthorityFences } from './server-authority-fences' -import { endedPresenceOf, recordAgentExit } from './agent-exit-evidence' +import { endedPresenceOf } from './agent-exit-evidence' import type { LaunchResumeIdentityEvent } from './launch-resume-identity-event' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' import { agentPaneSleepStatus } from '../../../shared/agent-status/lifecycle/agent-pane-sleep-status' @@ -171,7 +171,6 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF ) { return false } - recordAgentExit(this.agentExitedAtByPaneKey, [resolved], row.agentPresence, now) this.commitStatusRowMutation(previous, row) this.scheduleStatusPersist() this.notifyStatusChangeListeners() diff --git a/src/main/agent-hooks/server/server-status-application.ts b/src/main/agent-hooks/server/server-status-application.ts index f3a844b6f02a..283044d44fa3 100644 --- a/src/main/agent-hooks/server/server-status-application.ts +++ b/src/main/agent-hooks/server/server-status-application.ts @@ -86,7 +86,11 @@ export abstract class AgentHookServerStatusApplication extends AgentHookServerSt receivedAt: now, evidenceObservedAt: now, stateStartedAt, - observation: this.stampObservation(payload, 'osc', now) + observation: this.stampObservation( + payload, + previous.observation?.origin === 'launch' && !newRun ? 'launch' : 'osc', + now + ) }, mutationBefore ?? previous, this.cliWriterExecutionMatches, diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index 5404caa0e4b7..c6c6724c1ea8 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -1,3 +1,4 @@ +import type { AgentStatusObservationOrigin } from '../../../shared/agent-status/contracts/agent-status-observation' import { resumedAcceptedTurn } from './pane-agent-turn-continuity' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import { RelaySessionGenerations } from './server-relay-sessions' @@ -12,9 +13,10 @@ export abstract class AgentHookServerStatusRowMutation extends AgentHookServerSt protected preserveResumedAcceptedTurn( previous: EnrichedAgentHookEventPayload | undefined, incoming: AgentHookEventPayload, - before: EnrichedAgentHookEventPayload | undefined + before: EnrichedAgentHookEventPayload | undefined, + origin: AgentStatusObservationOrigin ): EnrichedAgentHookEventPayload | null | undefined { - const resumed = previous && resumedAcceptedTurn(previous, incoming) + const resumed = previous && resumedAcceptedTurn(previous, incoming, origin) if (!resumed) { return null } diff --git a/src/main/agent-hooks/server/server-status-update.ts b/src/main/agent-hooks/server/server-status-update.ts index 39366f40ca2a..7d8c6c17161a 100644 --- a/src/main/agent-hooks/server/server-status-update.ts +++ b/src/main/agent-hooks/server/server-status-update.ts @@ -196,7 +196,12 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusR if (previous && stateReconciledPayload === previous) { return previous } - const resumed = this.preserveResumedAcceptedTurn(previous, stateReconciledPayload, rowBefore) + const resumed = this.preserveResumedAcceptedTurn( + previous, + stateReconciledPayload, + rowBefore, + origin + ) if (resumed !== null) { return resumed } diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts index 33df954902f6..1e421832d9f6 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts @@ -1,4 +1,4 @@ -import { expect, it } from 'vitest' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' import { captureWorktreeSleepResumeRecords } from '../../../../runtime/terminal/stop/worktree-sleep-resume-records' import { AgentHookServer } from '../../agent-hook-server' @@ -7,6 +7,12 @@ import { resumeStatusFromHookRow } from '../../../../runtime/terminal/stop/hook- import { liveResumeRecord } from '../../../../../shared/agent-session/lifecycle/resume/agent-resume-record-from-status' import { agentEntryCompletionAt } from '../../../../../shared/agent-status/lifecycle/agent-completion-time' +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(1_000) +}) +afterEach(() => vi.useRealTimers()) + it.each(['claude', 'codex'] as const)( 'settles %s saved-only turns without inventing a completion', (agent) => { @@ -111,7 +117,7 @@ it.each(['claude', 'codex'] as const)( worktreeId: 'wt-1', agentType: agent, providerSession: saved.providerSession, - launchedAt: Date.now() + launchedAt: 1_000 }) const publish = (newTurn: boolean) => server.ingestRemote( @@ -152,7 +158,7 @@ it.each(['claude', 'codex'] as const)( launchByPtyId: new Map(), readRowsForPane: (paneKey) => server.getStatusSnapshotForPane(paneKey), checkAgentPresence: null, - capturedAt: Date.now() + capturedAt: 1_000 }) saved = capture.get('pty')!.records[0]! expect(saved).toMatchObject({ @@ -161,6 +167,11 @@ it.each(['claude', 'codex'] as const)( interrupted: true, providerSession: { key: 'session_id', id: `${agent}-saved-session` } }) + server.dropStatusEntry(PANE, { preserveResumeIdentity: false }) + expect(server.paneAgentIdentity(PANE)).toMatchObject({ + ended: false, + status: { state: 'done', interrupted: true } + }) server.retireSleepingPaneOnSpawn(PANE, { agentType: agent, providerSession: saved.providerSession @@ -214,7 +225,7 @@ it('does not recover a saved Interrupted turn after its conversation exited', () worktreeId: 'wt-1', agentType: 'codex', providerSession: saved.providerSession, - launchedAt: Date.now() + 1 + launchedAt: 1_001 }) expect(server.getPublicStatusSnapshotForPane(PANE)).toEqual([]) expect(server.paneAgentIdentity(PANE)?.status.interrupted).not.toBe(true) diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index e55e3185113a..0eed732d839e 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -173,7 +173,6 @@ it.each(['idle Codex', 'Claude hook', 'failed resume', 'ordinary exit'] as const stopping = true expect(server.settleTerminalPaneSleep(PANE, 'pty', 'birth')).toBe(true) } - expect(await server.checkAgentPresenceSince(PANE, 0)).toBe('exited') stopping = false server.retireSleepingPaneOnSpawn( @@ -306,6 +305,16 @@ it.each(['claude', 'codex'] as const)( await agentHook(agent, 'SessionStart', 4002) } expect(read()).toMatchObject({ state: 'done', interrupted: true }) + // Startup bytes restate the session before a new prompt; they do not finish another turn. + for (const sessionBoundary of [true, undefined]) { + server.ingestTerminalStatus({ + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'done', prompt: '', agentType: agent, sessionBoundary } + }) + expect(read()).toMatchObject({ state: 'done', interrupted: true }) + } emitted.mockClear() await sleepPane(agent, 'pty-2', 4002) expect(read()).toMatchObject({ diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts index a32c1e5bf987..ea89e6438e1b 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts @@ -2,6 +2,7 @@ import { createHash } from 'node:crypto' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AgentHookServer, _internals } from '../../agent-hook-server' import { captureWorktreeSleepResumeRecords } from '../../../../runtime/terminal/stop/worktree-sleep-resume-records' +import { TerminalIntentionalStops } from '../../../../runtime/terminal/stop/terminal-intentional-stops' import { postHookEvent } from '../server.test-fixtures' import { TMUX_TEST_PANE, @@ -61,10 +62,13 @@ describe('main canonical tmux projection', () => { }) it('does not resume an inner agent whose tmux server outlives the sleeping pane', async () => { await postHookEvent(server, tmuxTestBody(), '/hook/opencode') + const stops = new TerminalIntentionalStops() + const settle = stops.mark('pty', 'reversible', 'birth') + let bound = true server.setTerminalPaneLifecycle({ - ownsProcess: () => true, - isStopping: () => true, - isReversibleStop: () => true, + ownsProcess: () => bound, + isStopping: () => bound && stops.claimExit('pty', 'birth').includes('reversible'), + isReversibleStop: (pty, birth) => stops.claimExit(pty, birth).includes('reversible'), isPlaced: () => true }) const capture = await captureWorktreeSleepResumeRecords({ @@ -82,6 +86,10 @@ describe('main canonical tmux projection', () => { }) expect(server.settleTerminalPaneSleep(TMUX_TEST_PANE, 'pty', 'birth')).toBe(false) server.reconcileEndedProcessForPaneKeys([TMUX_TEST_PANE]) + expect(server.getStatusSnapshot()).toHaveLength(1) + bound = false + settle(true) + server.reconcileEndedProcessForPaneKeys([TMUX_TEST_PANE]) expect(server.getStatusSnapshot()).toHaveLength(0) }) it('removes canonical tmux status on certified retirement', async () => { diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts new file mode 100644 index 000000000000..793370f3151f --- /dev/null +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -0,0 +1,67 @@ +import { expect, it, vi } from 'vitest' +import { PANE } from '../server.test-fixtures' +import { + NOW, + TMUX, + TMUX_HINT, + codexTurn, + createServer, + hook, + io, + registerRootTestHarness, + runningPane, + type Proc, + type RootTestServer +} from '../presence/server-hook-root.test-fixtures' +import { + readHookRootEvidence, + readPaneTmuxHost +} from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import { captureWorktreeSleepResumeRecords } from '../../../../runtime/terminal/stop/worktree-sleep-resume-records' + +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ + probeAgentProcessPresence: vi.fn() +})) + +registerRootTestHarness() + +// The pane shows the tmux session through its foreground client. +const CLIENT: Proc = [4050, 101, 4050, 'tmux -L qa attach', 'S+'] + +it.each([ + [ + 'claude', + (server: RootTestServer) => + hook(server, 'UserPromptSubmit', { + session: 'tmux', + pid: 4043, + tmuxPane: TMUX_HINT, + prompt: 'In tmux' + }) + ], + ['codex', (server: RootTestServer) => codexTurn(server)] +] as const)( + 'does not capture a legacy %s whose tmux server outlives the sleeping pane', + async (_agent, turn) => { + const server = await createServer() + server.setHookRootEvidenceReader( + (request) => readHookRootEvidence(request, io), + (request) => readPaneTmuxHost(io, request) + ) + runningPane(4050, CLIENT, ...TMUX) + await turn(server) + expect(server.row()).toMatchObject({ state: 'working', providerSession: {} }) + const capture = await captureWorktreeSleepResumeRecords({ + worktreeId: 'wt-1', + paneKeysByPtyId: new Map([['pty', [PANE]]]), + launchByPtyId: new Map(), + readRowsForPane: (key) => server.getStatusSnapshotForPane(key), + readIdentity: (key, saved) => server.paneAgentIdentity(key, saved), + checkAgentPresence: (key, since) => server.checkAgentPresenceSince(key, since ?? 0), + capturedAt: NOW + }) + expect(capture.get('pty')).toEqual({ records: [], retiredPaneKeys: [PANE] }) + } +) diff --git a/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts b/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts new file mode 100644 index 000000000000..4642bc468b31 --- /dev/null +++ b/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts @@ -0,0 +1,135 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { OrcaRuntimeService } from '../../orca-runtime' +import { captureWorktreeSleepResumeRecords } from '../../terminal/stop/worktree-sleep-resume-records' +import { + partialRuntimeStore, + storeFolderWorkspace, + storeProjectGroup +} from '../../orca-runtime-tests/runtime-store-partial-fixture' + +vi.mock('electron', () => ({ + BrowserWindow: { fromId: vi.fn(() => null) }, + webContents: { fromId: vi.fn(() => null) }, + ipcMain: { on: vi.fn(), removeListener: vi.fn(), emit: vi.fn(() => true) }, + app: { getPath: vi.fn(() => '/tmp'), isPackaged: false } +})) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) + +const WORKTREE = 'folder:saved-sleep' +const TAB = 'tab-saved-sleep' +const PANE = makePaneKey(TAB, '11111111-1111-4111-8111-111111111111') +const servers: AgentHookServer[] = [] +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(1_000) +}) +afterEach(() => { + vi.useRealTimers() + for (const server of servers.splice(0)) { + server.stop() + } +}) + +it.each(['claude', 'codex'] as const)( + 'lists a slept %s from its saved record after every volatile row is evicted', + async (agent) => { + const session = getDefaultWorkspaceSession() + session.tabsByWorktree[WORKTREE] = [ + { + id: TAB, + worktreeId: WORKTREE, + ptyId: null, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 100 + } + ] + const server = new AgentHookServer() + servers.push(server) + server.setTerminalPaneLifecycle({ + readSavedRecord: (paneKey) => session.sleepingAgentSessionsByPaneKey?.[paneKey], + retireSavedRecord: (paneKey) => { + delete session.sleepingAgentSessionsByPaneKey?.[paneKey] + }, + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => true, + isPlaced: () => true + }) + server.ingestRemote( + { + paneKey: PANE, + tabId: TAB, + worktreeId: WORKTREE, + source: agent, + hookEventName: 'UserPromptSubmit', + hasExplicitPrompt: true, + providerSession: { key: 'session_id', id: `${agent}-conversation` }, + payload: { agentType: agent, state: 'working', prompt: 'Finish this task' } + }, + null + ) + const capture = await captureWorktreeSleepResumeRecords({ + worktreeId: WORKTREE, + paneKeysByPtyId: new Map([['pty', [PANE]]]), + launchByPtyId: new Map(), + readRowsForPane: (paneKey) => server.getStatusSnapshotForPane(paneKey), + readIdentity: (paneKey) => server.paneAgentIdentity(paneKey), + checkAgentPresence: null, + capturedAt: 1_000 + }) + session.sleepingAgentSessionsByPaneKey = Object.fromEntries( + capture.get('pty')!.records.map((record) => [record.paneKey, record]) + ) + expect(server.settleTerminalPaneSleep(PANE, 'pty', 'birth')).toBe(true) + server.dropStatusEntry(PANE, { preserveResumeIdentity: false }) + expect(server.getStatusSnapshotForPane(PANE)).toEqual([]) + + const runtime = new OrcaRuntimeService( + partialRuntimeStore({ + getWorkspaceSession: () => session, + getFolderWorkspaces: () => [ + storeFolderWorkspace({ + id: 'saved-sleep', + projectGroupId: 'group', + folderPath: '/tmp/saved-sleep' + }) + ], + getProjectGroups: () => [storeProjectGroup({ id: 'group' })] + }), + undefined, + { + getPaneAgentIdentity: (paneKey, saved) => server.paneAgentIdentity(paneKey, saved), + getAgentProviderSessionSnapshot: () => server.getStatusSnapshot() + } + ) + const listed = async () => + (await runtime.getWorktreePs(100, true, true)).worktrees.find( + (row) => row.worktreeId === WORKTREE + ) + const row = await listed() + expect(row).toMatchObject({ + liveTerminalCount: 0, + agents: [ + { + paneKey: PANE, + agentType: agent, + state: 'done', + interrupted: true, + prompt: 'Finish this task' + } + ] + }) + expect(row?.agents[0]?.hasLivePty).toBeUndefined() + expect(row?.agents[0]?.agentWait).toBeUndefined() + + server.retireProcessAuthority(PANE, { confirmedExit: true }) + expect((await listed())?.agents).toEqual([]) + } +) diff --git a/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts b/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts index 2ec255dc05fd..82262304370a 100644 --- a/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts +++ b/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentStatusSetData } from './ipc-events-agent-status-store-test-fixtures' import { buildWindowApi } from './ipc-events-agent-status-window-test-fixtures' import { makeTab } from '../store/terminals/testing/terminal-tab.test-fixture' @@ -20,6 +21,9 @@ vi.mock('./agent-hook-completion-notifications', () => ({ observeAgentHookCompletionForNotification: vi.fn(), syncAgentHookCompletionNotificationsForStoreUpdate: () => {} })) +vi.mock('../store/github/refresh/stale-worktree-refresh-actions', () => ({ + refreshGitHubForWorktreeIfStale: vi.fn() +})) vi.mock('@/lib/notifications/desktop-notification-sound', () => ({ playDesktopNotificationSound: vi.fn() })) @@ -109,7 +113,7 @@ describe('waking a pane slept mid-turn', () => { it.each(['claude', 'codex'] as const)( 'announces no %s finish until the pane runs a new turn', async (agentType) => { - const working: AgentStatusSetData = { + const working: AgentStatusIpcPayload = { paneKey: PANE, connectionId: null, tabId: 'tab-1', @@ -132,7 +136,7 @@ describe('waking a pane slept mid-turn', () => { vi.setSystemTime(NOW + 30_000) bindPty('pty-2') // Main hands the slept turn back to the resumed process. - send({ + const resumed: AgentStatusIpcPayload = { ...slept, isReplay: true, observation: { @@ -143,7 +147,8 @@ describe('waking a pane slept mid-turn', () => { observedAt: NOW + 30_000, kind: 'snapshot' } - }) + } + send(resumed) vi.advanceTimersByTime(40) // The title lane reads the resumed agent's startup spinner; the hook lane re-sees the verdict. diff --git a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts index b67f9a89bc6b..12709117d554 100644 --- a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts +++ b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts @@ -232,7 +232,7 @@ export function classifyPaneHookProcess(input: { } async function collectRows( - io: HookPaneProcessIo, + io: Pick, rootPid: number, senderPid: number ): Promise { @@ -295,6 +295,44 @@ export async function readHookRootEvidence( return verdict === 'root' && root ? { verdict, binding: root.incarnation } : { verdict } } +/** Whether a tmux server, not the pane, keeps the pane's agent alive: a tmux client holds the + * pane's foreground and the agent's known process runs outside the pane. */ +export type PaneTmuxHostReader = (request: { + paneKey: string + worktreeId: string | undefined + process?: AgentProcessIdentity +}) => Promise + +export async function readPaneTmuxHost( + io: Pick, + request: Parameters[0] +): Promise { + const root = await io.resolveRoot(request.paneKey, request.worktreeId) + if (!root || root === 'legacy') { + return false + } + const rows = await collectRows(io, root.pid, request.process?.pid ?? root.pid) + if (!rows) { + return false + } + const byPid = new Map(rows.map((row) => [row.pid, row])) + const rootRow = byPid.get(root.pid) + if (!rootRow?.tpgid || rootRow.tpgid <= 0) { + return false + } + const shown = rows.some( + (row) => row.tty === rootRow.tty && row.pgid === rootRow.tpgid && isTmuxServer(row) + ) + let agent = request.process ? byPid.get(request.process.pid) : undefined + for (let depth = 0; shown && agent && depth < MAX_ANCESTRY_DEPTH; depth++) { + if (agent.pid === root.pid) { + return false + } + agent = agent.ppid > 1 ? byPid.get(agent.ppid) : undefined + } + return shown +} + async function readAgainstRoot( request: HookRootEvidenceRequest, io: HookPaneProcessIo, From ea1d677504ecce47d232e7392ed8f6c7aaf58dec Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:18:28 -0800 Subject: [PATCH 022/125] Follow the process observation module moved on main --- .../agent-hooks/observations/local-hook-root-evidence.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/agent-hooks/observations/local-hook-root-evidence.ts b/src/main/agent-hooks/observations/local-hook-root-evidence.ts index bfa53b8a9c4b..ee083998a798 100644 --- a/src/main/agent-hooks/observations/local-hook-root-evidence.ts +++ b/src/main/agent-hooks/observations/local-hook-root-evidence.ts @@ -6,7 +6,10 @@ import { } from './local-tmux-managed-pty' import { createLocalHookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' import { readPaneTmuxHost } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import { readSelectedRows, readTerminalRows } from '../../../shared/tmux-host-attachment-probe' +import { + readSelectedRows, + readTerminalRows +} from '../../../shared/agent-hook-listener/presence/tmux-host-attachment-probe' import { getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' From 9072b20d4196991d00a7ccd5b2502bf62128e872 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:50:50 -0800 Subject: [PATCH 023/125] Keep status ingestion within the module size gate --- src/main/agent-hooks/server/server-status-row-mutation.ts | 2 +- src/main/agent-hooks/server/server-status-update.ts | 7 +------ .../presence/hook-process-root-evidence.ts | 7 +++---- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index c6c6724c1ea8..2c35e0acbb81 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -10,7 +10,7 @@ import { ClaudeOwedNotificationExpiryTimers } from '../../../shared/agent-hook-l import { AgentHookServerStatusApplication } from './server-status-application' export abstract class AgentHookServerStatusRowMutation extends AgentHookServerStatusApplication { - protected preserveResumedAcceptedTurn( + protected preserveAcceptedTurn( previous: EnrichedAgentHookEventPayload | undefined, incoming: AgentHookEventPayload, before: EnrichedAgentHookEventPayload | undefined, diff --git a/src/main/agent-hooks/server/server-status-update.ts b/src/main/agent-hooks/server/server-status-update.ts index 7d8c6c17161a..4bd51f962d9a 100644 --- a/src/main/agent-hooks/server/server-status-update.ts +++ b/src/main/agent-hooks/server/server-status-update.ts @@ -196,12 +196,7 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusR if (previous && stateReconciledPayload === previous) { return previous } - const resumed = this.preserveResumedAcceptedTurn( - previous, - stateReconciledPayload, - rowBefore, - origin - ) + const resumed = this.preserveAcceptedTurn(previous, stateReconciledPayload, rowBefore, origin) if (resumed !== null) { return resumed } diff --git a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts index 0d4e6cbcf081..f6cd4e326254 100644 --- a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts +++ b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts @@ -315,20 +315,19 @@ export async function readPaneTmuxHost( if (!rows) { return false } - const byPid = new Map(rows.map((row) => [row.pid, row])) - const rootRow = byPid.get(root.pid) + const rootRow = rows.find((row) => row.pid === root.pid) if (!rootRow?.tpgid || rootRow.tpgid <= 0) { return false } const shown = rows.some( (row) => row.tty === rootRow.tty && row.pgid === rootRow.tpgid && isTmuxServer(row) ) - let agent = request.process ? byPid.get(request.process.pid) : undefined + let agent = request.process ? rows.find((row) => row.pid === request.process?.pid) : undefined for (let depth = 0; shown && agent && depth < MAX_ANCESTRY_DEPTH; depth++) { if (agent.pid === root.pid) { return false } - agent = agent.ppid > 1 ? byPid.get(agent.ppid) : undefined + agent = agent.ppid > 1 ? rows.find((row) => row.pid === agent?.ppid) : undefined } return shown } From c317afe7cdeee4937864294790a198ff2894beef Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:23:08 -0800 Subject: [PATCH 024/125] Replace accepted rows when observing a surviving tmux host --- src/main/agent-hooks/server/agent-hook-server.ts | 15 +++++++++++---- .../agent-status-sleep-wake-completion.test.ts | 10 +++++----- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index ee095e4d7b05..999b29ae8208 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -6,11 +6,12 @@ import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/ import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { cliWriterTopology, - retainTmuxWriterTopology, + tmuxCliWriterEvent, type CliWriterObservation } from './cli-writer-observation' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' +import type { EnrichedAgentHookEventPayload } from './server-types' import { ClaudeSessionContinuationTracker, resolvePaneClaudeContinuation @@ -141,7 +142,10 @@ export class AgentHookServer extends AgentHookServerLifecycle { * a sleep or adoption captures the conversation as the pane's own. */ private async observeTmuxHostedWriter(paneKey: string): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) - const row = this.state.lastStatusByPaneKey.get(resolved) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: main stores enriched accepted rows in the base-typed cache. + const row = this.state.lastStatusByPaneKey.get(resolved) as + | EnrichedAgentHookEventPayload + | undefined const binding = row?.providerSession const read = this.readPaneTmuxHost if ( @@ -159,8 +163,11 @@ export class AgentHookServer extends AgentHookServerLifecycle { worktreeId: row.worktreeId, ...(presence?.process && !presence.ended ? { process: presence.process } : {}) }).catch(() => false) - if (hosted && this.state.lastStatusByPaneKey.get(resolved)?.providerSession === binding) { - retainTmuxWriterTopology(binding) + if (hosted && this.state.lastStatusByPaneKey.get(resolved) === row) { + const hostedRow = tmuxCliWriterEvent(row) + if (this.writeLegacyStatusRow(hostedRow)) { + this.commitStatusRowMutation(row, hostedRow) + } } } diff --git a/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts b/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts index 82262304370a..2069d2db1240 100644 --- a/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts +++ b/src/renderer/src/hooks/agent-status-sleep-wake-completion.test.ts @@ -22,7 +22,7 @@ vi.mock('./agent-hook-completion-notifications', () => ({ syncAgentHookCompletionNotificationsForStoreUpdate: () => {} })) vi.mock('../store/github/refresh/stale-worktree-refresh-actions', () => ({ - refreshGitHubForWorktreeIfStale: vi.fn() + createStaleWorktreeRefreshActions: () => ({ refreshGitHubForWorktreeIfStale: vi.fn() }) })) vi.mock('@/lib/notifications/desktop-notification-sound', () => ({ playDesktopNotificationSound: vi.fn() @@ -113,7 +113,7 @@ describe('waking a pane slept mid-turn', () => { it.each(['claude', 'codex'] as const)( 'announces no %s finish until the pane runs a new turn', async (agentType) => { - const working: AgentStatusIpcPayload = { + const working = { paneKey: PANE, connectionId: null, tabId: 'tab-1', @@ -123,7 +123,7 @@ describe('waking a pane slept mid-turn', () => { agentType, receivedAt: NOW, stateStartedAt: NOW - } + } satisfies AgentStatusIpcPayload send(working) const slept = { ...working, @@ -136,7 +136,7 @@ describe('waking a pane slept mid-turn', () => { vi.setSystemTime(NOW + 30_000) bindPty('pty-2') // Main hands the slept turn back to the resumed process. - const resumed: AgentStatusIpcPayload = { + const resumed = { ...slept, isReplay: true, observation: { @@ -147,7 +147,7 @@ describe('waking a pane slept mid-turn', () => { observedAt: NOW + 30_000, kind: 'snapshot' } - } + } satisfies AgentStatusIpcPayload send(resumed) vi.advanceTimersByTime(40) From 2990d8128e6a4aea8f37a7f47f284cc36e278116 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:56:57 -0800 Subject: [PATCH 025/125] Consult pane ownership before the hook-row restore fallback --- .../agent-session-resume-ownership.ts | 7 ++++++ .../restored-pane-hook-store-resume.test.ts | 23 +++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts b/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts index 89749ca934f7..b503700ca12e 100644 --- a/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts +++ b/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts @@ -70,6 +70,13 @@ export abstract class OrcaRuntimeWithAgentSessionResumeOwnership extends OrcaRun tab: RuntimeMobileSessionTerminalTab ): Promise | undefined> { const stored = this.getPaneSleepingAgentRecord(worktreeId, tab) + const identity = this.readPaneAgentIdentity( + makePaneKey(tab.parentTabId, tab.leafId), + stored ?? undefined + ) + if (identity?.ended || identity?.processTopology === 'shared') { + return {} + } const record = stored ? this.isPaneOwnedResumeRecord(stored) ? stored diff --git a/src/main/runtime/terminal/recovery/restored-pane-hook-store-resume.test.ts b/src/main/runtime/terminal/recovery/restored-pane-hook-store-resume.test.ts index 4e05260e1794..5f6234cc9eea 100644 --- a/src/main/runtime/terminal/recovery/restored-pane-hook-store-resume.test.ts +++ b/src/main/runtime/terminal/recovery/restored-pane-hook-store-resume.test.ts @@ -1,6 +1,7 @@ // verify-15a parity: a host whose daemon restarted resumed nothing and replayed the pane's launch. import { describe, expect, it, vi } from 'vitest' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { PaneAgentIdentity } from '../../../agent-hooks/server/pane-agent-identity' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' @@ -39,10 +40,12 @@ async function makeRuntime( launchAgent?: 'codex', { session: overrides = {}, - presence = 'exited' + presence = 'exited', + identity }: { session?: Partial presence?: 'live' | 'exited' + identity?: PaneAgentIdentity } = {} ) { const session = makeWorkspaceSessionWithHeadlessTerminal() @@ -61,7 +64,8 @@ async function makeRuntime( getAgentProviderSessionSnapshot: () => rows, getAgentProviderSessionRowsForPane: (paneKey: string) => rows.filter((row) => row.paneKey === paneKey), - checkHookAgentPresence: async () => presence + checkHookAgentPresence: async () => presence, + ...(identity ? { getPaneAgentIdentity: () => identity } : {}) }) runtime.setPtyController({ spawn: committingSpawn(runtime, spawn), @@ -88,6 +92,21 @@ async function restore(runtime: InstanceType): Promis } describe('restoring a pane its host recorded an agent in', () => { + it.each(['ended', 'shared'] as const)( + 'opens a shell when the pane owner says its conversation is %s', + async (ownership) => { + const { runtime, spawn } = await makeRuntime([codexRow()], 'codex', { + identity: { + status: codexRow(), + ended: ownership === 'ended', + processTopology: ownership === 'shared' ? 'shared' : 'pane-owned' + } + }) + await restore(runtime) + expect(spawn.mock.calls[0]![0].command ?? '').toBe('') + } + ) + it('ignores a row from another worktree, and launches the tab’s agent fresh', async () => { const { runtime, spawn } = await makeRuntime( [codexRow({ worktreeId: 'other-repo::/other' })], From 75ee24ca76d024237cfe69bb9bafb909e58f4720 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:22:35 -0800 Subject: [PATCH 026/125] Keep accepted turns and process ownership through startup reports --- .../server/cli-writer-observation.ts | 17 ++++ .../server/pane-agent-turn-continuity.ts | 5 +- .../persistence/server-pane-sleep.test.ts | 81 ++++++++++++++++++- .../tmux/server-tmux-legacy-sleep.test.ts | 25 ++++++ 4 files changed, 125 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/cli-writer-observation.ts b/src/main/agent-hooks/server/cli-writer-observation.ts index b70d1d14e9e4..9edce068dfb3 100644 --- a/src/main/agent-hooks/server/cli-writer-observation.ts +++ b/src/main/agent-hooks/server/cli-writer-observation.ts @@ -10,6 +10,8 @@ import { } from '../../../shared/agent-status/process/agent-process-presence' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' +import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' // Execution metadata follows the conversation binding and disappears at serialization. export const OPEN_CODE_WRITER_TOPOLOGY = Symbol('openCodeWriterTopology') @@ -120,6 +122,21 @@ export function deriveCliWriterTopology( ): T { const binding = row.providerSession if (!binding || !(OPEN_CODE_WRITER_TOPOLOGY in binding)) { + if ( + binding && + baseline && + cliWriterTopology(baseline) === 'shared' && + !newRun && + row.payload.agentType === baseline.payload.agentType && + sameAgentStatusTerminalOwner(baseline, row) && + agentProviderSessionsEqual(row.payload.agentType, baseline.providerSession, binding) && + (!sender || + !baseline.agentPresence?.process || + isSameAgentProcess(sender, baseline.agentPresence.process)) && + matches?.(row, baseline) + ) { + return tmuxCliWriterEvent(row) + } return row } const inherited = baseline?.providerSession === binding diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index 5bdffca38f61..94ad5946d951 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -4,7 +4,7 @@ import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/ import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' -/** A boundary for the conversation whose turn the pane last accepted keeps that turn's verdict. */ +/** Resume startup reports keep the conversation's accepted verdict until a new turn. */ export function resumedAcceptedTurn( previous: EnrichedAgentHookEventPayload, incoming: AgentHookEventPayload, @@ -14,7 +14,8 @@ export function resumedAcceptedTurn( (incoming.payload.agentType === 'claude' || previous.observation?.origin === 'launch') && (incoming.payload.sessionBoundary === true || (origin === 'osc' && previous.observation?.origin === 'launch')) && - incoming.payload.state === 'done' && + (incoming.payload.state === 'done' || + (origin === 'osc' && incoming.payload.state === 'working')) && incoming.toolAgentId === undefined && previous.payload.state === 'done' && previous.payload.sessionBoundary !== true && diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 0eed732d839e..86253f3a0927 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -15,7 +15,7 @@ import { nativeChatTranscriptPathOnExecutionHost } from '../../../../native-chat import { nativeChatTranscriptDistro } from '../../../../native-chat/transcript-discovery/native-chat-open-wake' import { WSL_HOOK_RELAY_CONNECTION_PREFIX } from '../../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { AgentHookServer, _internals } from '../../agent-hook-server' -import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { buildBody, ingestProgramStatusOsc, PANE, postHookEvent } from '../server.test-fixtures' vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) @@ -28,6 +28,7 @@ let server: AgentHookServer let stopping: boolean let placed: boolean let pty: { id: string; birth: string } +let saved: SleepingAgentSessionRecord | undefined const read = () => server.getStatusSnapshotForPane(PANE)[0] beforeEach(async () => { @@ -36,9 +37,11 @@ beforeEach(async () => { stopping = false placed = true pty = { id: 'pty', birth: 'birth' } + saved = undefined server = new AgentHookServer() const owns = (id: string, incarnation?: string) => id === pty.id && incarnation === pty.birth server.setTerminalPaneLifecycle({ + readSavedRecord: () => saved, ownsProcess: (_key, id, incarnation) => owns(id, incarnation), isStopping: () => stopping, isReversibleStop: (id, incarnation) => stopping && owns(id, incarnation), @@ -326,6 +329,82 @@ it.each(['claude', 'codex'] as const)( } ) +it.each(['retained', 'evicted'] as const)( + 'keeps Claude Interrupted through startup work before its verified root hook (%s row)', + async (row) => { + server.setHookRootEvidenceReader(async () => ({ verdict: 'root' })) + await agentHook('claude', 'UserPromptSubmit', 4001) + await sleepPane('claude', 'pty-1', 4001) + for (const pid of [4002, 4003]) { + const capture = await captureWorktreeSleepResumeRecords({ + worktreeId: 'wt-1', + paneKeysByPtyId: new Map([[pty.id, [PANE]]]), + launchByPtyId: new Map(), + readRowsForPane: (paneKey) => server.getStatusSnapshotForPane(paneKey), + checkAgentPresence: null, + capturedAt: Date.now() + }) + saved = capture.get(pty.id)!.records[0]! + if (row === 'evicted') { + server.dropStatusEntry(PANE, { preserveResumeIdentity: false }) + } + server.retireSleepingPaneOnSpawn(PANE, { + agentType: 'claude', + providerSession: { key: 'session_id', id: 'claude-session' } + }) + server.recordLaunchResumeIdentity({ + paneKey: PANE, + worktreeId: 'wt-1', + agentType: 'claude', + providerSession: { key: 'session_id', id: 'claude-session' }, + launchedAt: Date.now() + }) + // Startup work precedes SessionStart; neither report opens a user turn. + for (const state of ['working', 'idle']) { + ingestProgramStatusOsc(server, `\x1b]7501;app=claude-code:state=${state}\x1b\\`) + expect(read()).toMatchObject({ + state: 'done', + interrupted: true, + prompt: 'Finished work', + mainAgent: { state: 'done', outcome: 'cancellation' } + }) + } + const response = await postHookEvent( + server, + buildBody( + { hook_event_name: 'SessionStart', session_id: 'claude-session', source: 'resume' }, + { + launchToken: `wake-${pid}`, + agentProcess: JSON.stringify({ + pid, + platform: process.platform, + startTime: `birth-${pid}` + }) + } + ) + ) + expect(response.status).toBe(204) + expect(read()).toMatchObject({ + state: 'done', + interrupted: true, + mainAgent: { state: 'done', outcome: 'cancellation' } + }) + await sleepPane('claude', `pty-${pid}`, pid) + expect(read()).toMatchObject({ state: 'done', interrupted: true }) + } + server.retireSleepingPaneOnSpawn(PANE, { + agentType: 'claude', + providerSession: { key: 'session_id', id: 'claude-session' } + }) + await agentHook('claude', 'UserPromptSubmit', 4004) + expect(read()).toMatchObject({ state: 'working', prompt: 'Finished work' }) + expect(read()?.interrupted).not.toBe(true) + await agentHook('claude', 'Stop', 4004) + expect(read()).toMatchObject({ state: 'done' }) + expect(read()?.interrupted).not.toBe(true) + } +) + it.each(['claude', 'codex'] as const)( 'keeps a %s that never had a turn through sleep', async (agent) => { diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 793370f3151f..010d4e7637f6 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -13,6 +13,10 @@ import { type Proc, type RootTestServer } from '../presence/server-hook-root.test-fixtures' +import { + AgentStatusObservedPaneIdentities, + AgentStatusObservedPaneIdentityCapture +} from '../../../../runtime/terminal/identity/agent-status-observed-pane-identity' import { readHookRootEvidence, readPaneTmuxHost @@ -50,9 +54,30 @@ it.each([ (request) => readHookRootEvidence(request, io), (request) => readPaneTmuxHost(io, request) ) + const identities = new AgentStatusObservedPaneIdentities() + const observed = new AgentStatusObservedPaneIdentityCapture(identities) + const runtime = { + getAgentStatusTerminalHandleForPaneKey: () => 'terminal-a', + getTerminalProcessIncarnation: () => 'execution-a', + getAgentStatusOrchestrationContextForPaneKey: () => undefined + } + observed.attach(runtime) + server.subscribeEnrichedStatus((row) => observed.observe(row)) + server.setCliWriterExecutionMatcher(identities, runtime) runningPane(4050, CLIENT, ...TMUX) await turn(server) expect(server.row()).toMatchObject({ state: 'working', providerSession: {} }) + await server.checkAgentPresenceSince(PANE, 0) + // A fresh hook can land between capture's presence check and the PTY's physical stop. + await turn(server) + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => true, + isReversibleStop: () => true, + isPlaced: () => true + }) + expect(server.settleTerminalPaneSleep(PANE, 'pty')).toBe(false) + expect(server.row()).toMatchObject({ state: 'working' }) const capture = await captureWorktreeSleepResumeRecords({ worktreeId: 'wt-1', paneKeysByPtyId: new Map([['pty', [PANE]]]), From 504bd3cf49cc985c1f1929d5009be680a4c8898d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:16:20 -0800 Subject: [PATCH 027/125] Keep shared conversation ownership through both sleep cleanup paths --- src/main/agent-hooks/server/server-pane-sleep.ts | 11 ++++++++++- .../testing/tmux/server-tmux-legacy-sleep.test.ts | 8 +++++++- src/main/ipc/pty/provider/state-cleanup.ts | 8 ++++---- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index f2aff0fbc849..a63bc19793fd 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -35,6 +35,11 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF const row = this.state.lastStatusByPaneKey.get(resolved) as | EnrichedAgentHookEventPayload | undefined + if (this.paneAgentIdentity(resolved)?.processTopology === 'shared') { + this.dropStatusEntry(resolved, { preserveResumeIdentity: false }) + this.emitPaneStatusCleared({ paneKey: resolved }) + return + } if (!row?.paneSleep) { return } @@ -111,12 +116,16 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF !previous || !identity || identity.ended || - identity.processTopology === 'shared' || this.terminalPaneLifecycle?.isReversibleStop(ptyId, incarnationId) !== true || this.terminalPaneLifecycle.isPlaced(previous) !== true ) { return false } + // Keep shared ownership through provider cleanup, so later exit reconciliation cannot recover + // the stale saved record as a pane-owned agent and falsely interrupt its surviving process. + if (identity.processTopology === 'shared') { + return true + } const { launchToken: _launchToken, programStatus: _programStatus, diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 010d4e7637f6..ac3b21950ee7 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -76,7 +76,7 @@ it.each([ isReversibleStop: () => true, isPlaced: () => true }) - expect(server.settleTerminalPaneSleep(PANE, 'pty')).toBe(false) + expect(server.settleTerminalPaneSleep(PANE, 'pty')).toBe(true) expect(server.row()).toMatchObject({ state: 'working' }) const capture = await captureWorktreeSleepResumeRecords({ worktreeId: 'wt-1', @@ -88,5 +88,11 @@ it.each([ capturedAt: NOW }) expect(capture.get('pty')).toEqual({ records: [], retiredPaneKeys: [PANE] }) + // Provider cleanup keeps the row; the runtime's second exit settlement sees the same owner. + expect(server.settleTerminalPaneSleep(PANE, 'pty')).toBe(true) + expect(server.row()).toMatchObject({ state: 'working' }) + expect(server.row()?.interrupted).not.toBe(true) + server.retireSleepingPaneOnSpawn(PANE) + expect(server.row()).toBeUndefined() } ) diff --git a/src/main/ipc/pty/provider/state-cleanup.ts b/src/main/ipc/pty/provider/state-cleanup.ts index fee9905f03a0..71374e4e2bbb 100644 --- a/src/main/ipc/pty/provider/state-cleanup.ts +++ b/src/main/ipc/pty/provider/state-cleanup.ts @@ -37,7 +37,7 @@ export function clearProviderPtyState( ? agentHookServer.getStatusSnapshotForPane(paneKey)[0]?.paneSleep : undefined const stillOwnsPaneKey = paneKey ? paneKeyPtyId.get(paneKey) === id : false - const preserveSleepingDone = Boolean( + const preserveSleepingAgent = Boolean( stillOwnsPaneKey && paneKey && ((existingSleep?.ptyId === id && @@ -81,7 +81,7 @@ export function clearProviderPtyState( clearMigrationUnsupportedPty(id) agentHookServer.clearPaneKeyAliasesForPty(id, { shouldClearStablePaneKey: (stablePaneKey) => { - if (preserveSleepingDone && stablePaneKey === paneKey) { + if (preserveSleepingAgent && stablePaneKey === paneKey) { return false } // Without rebuilt spawn mapping, alias ownership must protect a newer PTY on the same stable pane. @@ -96,8 +96,8 @@ export function clearProviderPtyState( if (paneKey) { if (stillOwnsPaneKey) { // Preserve proven agent-exit evidence across reconnectable disconnects. - if (preserveSleepingDone) { - // Its accepted row now belongs to the sleeping pane, not this retired process. + if (preserveSleepingAgent) { + // Keep the sleeping turn or surviving shared conversation through runtime exit reconciliation. } else if (opts.preserveAgentSessionOwners) { agentHookServer.clearPaneState(paneKey) } else { From 803f8cd24547084fe08b4516098d9e70e8870d33 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:47:07 -0800 Subject: [PATCH 028/125] Record a shell-confirmed agent exit only for pane-owned processes, proven end to end Carries #42922's command-finished exit evidence through the pane identity owner. --- src/main/agent-hooks/server/server-cleanup.ts | 7 +- .../persistence/server-pane-sleep.test.ts | 59 +-------- .../worktree-sleep-resume-recording.test.ts | 119 ++++++++++++++++++ .../terminal-osc133-command-finished.ts | 1 + 4 files changed, 126 insertions(+), 60 deletions(-) diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 7080efcb2cb2..b0c3941815e1 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -131,8 +131,11 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { | undefined const endedPresence = options?.endedPresence ?? - // A proved process gets its exit from the presence probe, not a possibly newer row. - (options?.confirmedExit && !previous?.agentPresence?.process + // A proved process gets its exit from the presence probe, not a possibly newer row; a + // shared server (tmux, OpenCode) outlives the command that finished at the pane's shell. + (options?.confirmedExit && + !previous?.agentPresence?.process && + this.paneAgentIdentity(resolvedPaneKey)?.processTopology !== 'shared' ? previous ? endedPresenceOf(previous) : { diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 86253f3a0927..c18215b39b42 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -3,10 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { getDefaultWorkspaceSession } from '../../../../../shared/constants' -import type { - AgentProviderSessionMetadata, - SleepingAgentSessionRecord -} from '../../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' import { applyWorktreeSleepResumeRecords, captureWorktreeSleepResumeRecords @@ -431,60 +428,6 @@ it.each(['claude', 'codex'] as const)( }) } ) -it('retires a hookless resumed Codex quit to its shell, and keeps a later relaunch', async () => { - const providerSession: AgentProviderSessionMetadata = { key: 'session_id', id: 'woken-session' } - const saved: SleepingAgentSessionRecord = { - paneKey: PANE, - tabId: 'tab-1', - worktreeId: 'wt-1', - agent: 'codex', - providerSession, - prompt: '', - state: 'done', - capturedAt: 1, - updatedAt: 1, - origin: 'worktree-sleep', - restoreOnTabOpenOnly: true, - connectionId: null - } - const session = { - ...getDefaultWorkspaceSession(), - sleepingAgentSessionsByPaneKey: { [PANE]: saved } - } - const sleep = async () => { - const capture = await captureWorktreeSleepResumeRecords({ - worktreeId: 'wt-1', - paneKeysByPtyId: new Map([['pty', [PANE]]]), - launchByPtyId: new Map(), - readRowsForPane: (paneKey) => server.getStatusSnapshotForPane(paneKey), - checkAgentPresence: (paneKey, since) => server.checkAgentPresenceSince(paneKey, since ?? 0), - capturedAt: 2 - }) - return applyWorktreeSleepResumeRecords(session, capture, ['pty']) ?? session - } - const launch = () => - server.recordLaunchResumeIdentity({ - paneKey: PANE, - worktreeId: 'wt-1', - agentType: 'codex', - providerSession, - launchedAt: Date.now() - }) - vi.useFakeTimers({ toFake: ['Date'] }) - launch() - vi.setSystemTime(Date.now() + 1000) - // The launched command's shell-confirmed finish, which clears the pane's row. - server.retireProcessAuthority(PANE, { confirmedExit: true }) - expect((await sleep()).sleepingAgentSessionsByPaneKey?.[PANE]).toBeUndefined() - - vi.setSystemTime(Date.now() + 1000) - launch() - expect((await sleep()).sleepingAgentSessionsByPaneKey?.[PANE]).toMatchObject({ - agent: 'codex', - providerSession, - origin: 'worktree-sleep' - }) -}) it('does not restore a sleeping status whose exact placed pane is absent', async () => { server.ingestTerminalStatus({ diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 7bb925e2d016..95bce8aeb3dd 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -7,6 +7,10 @@ await import('../../orca-runtime-tests/runtime-test-module-registration.spec') const { OrcaRuntimeService } = await import('../../orca-runtime') await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec') const { AgentHookServer } = await import('../../../agent-hooks/server/agent-hook-server') +const { agentHookRuntimeDeps } = + await import('../../../agent-hooks/runtime/agent-hook-runtime-deps') +const { AgentStatusObservedPaneIdentities } = + await import('../identity/agent-status-observed-pane-identity') const { HEADLESS_LEAF_ID, TEST_WORKTREE_ID, @@ -215,3 +219,118 @@ it.each([100, 1000])( expect(durableMutation).not.toHaveBeenCalled() } ) + +describe('a hookless resumed Codex across wakes and shell-confirmed command finishes', () => { + const SESSION = { key: 'session_id', id: 'woken-codex' } + const SLEPT: SleepingAgentSessionRecord = { + paneKey: PANE_KEY, + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + agent: 'codex', + providerSession: SESSION, + prompt: '', + state: 'done', + capturedAt: 100, + updatedAt: 100, + origin: 'worktree-sleep', + restoreOnTabOpenOnly: true, + connectionId: null + } + + it.each([ + ['quit', ['0'], false], + ['suspended', ['148'], true], + ['suspended, then another command', ['148', '0'], true] + ] as const)('%s', async (_, finishes, keepsRecovery) => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(1_000) + const tick = () => vi.setSystemTime(Date.now() + 1_000) + const fixture = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + sleepingAgentSessionsByPaneKey: { [PANE_KEY]: SLEPT } + }) + ) + const server = new AgentHookServer() + const runtime = new OrcaRuntimeService(fixture.runtimeStore, undefined, { + ...agentHookRuntimeDeps(server, new AgentStatusObservedPaneIdentities(), () => ({})), + retireAgentHookCompatibilityAuthority: (paneKey, options) => + server.retireProcessAuthority(paneKey, options) + }) + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => false, + isPlaced: () => true, + readSavedRecord: (paneKey) => fixture.getSession().sleepingAgentSessionsByPaneKey?.[paneKey], + retireSavedRecord: (paneKey, at) => runtime.retireExitedPaneResume(paneKey, at) + }) + const live = new Set() + runtime.setPtyController({ + write: () => true, + kill: () => false, + stopAndWait: async (ptyId) => { + live.delete(ptyId) + runtime.onPtyExit(ptyId, -1) + return true + }, + getForegroundProcess: async () => null, + listProcesses: async () => + [...live].map((id) => ({ id, cwd: TEST_WORKTREE_PATH, title: 'codex' })) + }) + runtime.attachWindow(1) + // Orca's wake relaunches the saved conversation; Codex posts no hook until a new turn. + const wake = async (ptyId: string) => { + tick() + live.add(ptyId) + const binding = { tabId: 'host-tab', leafId: HEADLESS_LEAF_ID, incarnationId: ptyId } + await runtime.syncWindowGraph(1, { + tabs: [{ ...binding, worktreeId: TEST_WORKTREE_ID, title: 'codex', layout: null }], + leaves: [{ ...binding, worktreeId: TEST_WORKTREE_ID, ptyId, paneRuntimeId: 1 }] + }) + runtime.registerPty(ptyId, TEST_WORKTREE_ID, null, { + ...binding, + agentLaunchAuthority: { launchToken: `${ptyId}-launch`, launchAgent: 'codex' } + }) + server.recordLaunchResumeIdentity({ + paneKey: PANE_KEY, + worktreeId: TEST_WORKTREE_ID, + agentType: 'codex', + providerSession: SESSION, + launchedAt: Date.now() + }) + } + const saved = () => runtime.readSavedResumeSource(TEST_WORKTREE_ID, PANE_KEY) + const sleep = async () => { + tick() + await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) + return saved() + } + const resumable = { agent: 'codex', providerSession: SESSION, origin: 'worktree-sleep' } + try { + // #42864: an idle resumed Codex keeps its conversation across two sleeps. + await wake('pty-1') + expect(await sleep()).toMatchObject(resumable) + await wake('pty-2') + expect(await sleep()).toMatchObject(resumable) + + await wake('pty-3') + for (const status of finishes) { + tick() + runtime.onPtyData('pty-3', `\x1b]133;D;${status}\x07`, Date.now()) + } + // A quit retires the saved conversation itself, before its exit evidence can expire. + expect(await saved()).toEqual(keepsRecovery ? expect.objectContaining(resumable) : undefined) + server.forgetAgentExit(PANE_KEY) + expect(await sleep()).toEqual(keepsRecovery ? expect.objectContaining(resumable) : undefined) + + // Orca relaunching the same conversation owns the pane again through later sleeps. + await wake('pty-4') + expect(await sleep()).toMatchObject(resumable) + await wake('pty-5') + expect(await sleep()).toMatchObject(resumable) + } finally { + server.stop() + vi.useRealTimers() + } + }) +}) diff --git a/src/shared/terminal/output/terminal-osc133-command-finished.ts b/src/shared/terminal/output/terminal-osc133-command-finished.ts index 91b162b4a680..89f35a81aa71 100644 --- a/src/shared/terminal/output/terminal-osc133-command-finished.ts +++ b/src/shared/terminal/output/terminal-osc133-command-finished.ts @@ -9,6 +9,7 @@ type OscTerminator = { const OSC_133_PREFIX = '\x1b]133;' // 128 + SIGSTOP/SIGTSTP/SIGTTIN/SIGTTOU, as numbered on macOS (17, 18, 21, 22) and Linux (19, 20, 21, 22). +// Conservative ambiguity exception, not suspension proof: 145/146 are stops only on macOS (SIGSTOP/SIGTSTP). const JOB_STOP_STATUSES: ReadonlySet = new Set([145, 146, 147, 148, 149, 150]) const MAX_OSC_CARRY_LENGTH = 4096 From 90736df52ada16a54b68213682724e746d0ac154 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:33:38 -0800 Subject: [PATCH 029/125] Type the proving test's fixtures --- .../stop/worktree-sleep-resume-recording.test.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 95bce8aeb3dd..83210374d505 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -221,7 +221,7 @@ it.each([100, 1000])( ) describe('a hookless resumed Codex across wakes and shell-confirmed command finishes', () => { - const SESSION = { key: 'session_id', id: 'woken-codex' } + const SESSION = { key: 'session_id' as const, id: 'woken-codex' } const SLEPT: SleepingAgentSessionRecord = { paneKey: PANE_KEY, tabId: 'host-tab', @@ -284,7 +284,15 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini live.add(ptyId) const binding = { tabId: 'host-tab', leafId: HEADLESS_LEAF_ID, incarnationId: ptyId } await runtime.syncWindowGraph(1, { - tabs: [{ ...binding, worktreeId: TEST_WORKTREE_ID, title: 'codex', layout: null }], + tabs: [ + { + ...binding, + worktreeId: TEST_WORKTREE_ID, + title: 'codex', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], leaves: [{ ...binding, worktreeId: TEST_WORKTREE_ID, ptyId, paneRuntimeId: 1 }] }) runtime.registerPty(ptyId, TEST_WORKTREE_ID, null, { From 66a630c1327500eb75b853abb5730fbfc6c67893 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:25:56 -0800 Subject: [PATCH 030/125] Preserve stopped agent recovery and detached shared ownership --- .../agent-hooks/server/server-tab-cleanup.ts | 10 ++- .../tmux/server-tmux-legacy-sleep.test.ts | 63 +++++++++++++++++ .../terminal-agent-status-and-submission.ts | 6 +- .../worktree-sleep-resume-recording.test.ts | 37 +++++++++- .../agent-identity/pane-agent-identity.ts | 43 +++--------- .../pane-agent-shell-lifecycle.ts | 53 ++++++++++++++ ...onnection-command-finished-cleanup.spec.ts | 70 ++++++++++++++++++- 7 files changed, 239 insertions(+), 43 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 37b4b50ede31..979f3c81aff4 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -18,9 +18,15 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { paneKey: string, options?: Pick ): void { + const identity = this.paneAgentIdentity(paneKey) const { paneKeys, authorityChanged } = this.revokeProcessAuthority(paneKey) - const { untouched } = this.reconcileEndedProcess(paneKeys, options, (key) => - this.clearRevokedPaneState(key) + const { untouched } = this.reconcileEndedProcess( + paneKeys, + { + ...options, + preserveResumeIdentity: !options?.confirmedExit || identity?.processTopology === 'shared' + }, + (key) => this.clearRevokedPaneState(key) ) for (const key of untouched) { this.clearTmuxInnerSubjects(key) diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index ac3b21950ee7..44c6bd1cabdb 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -22,6 +22,7 @@ import { readPaneTmuxHost } from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' import { captureWorktreeSleepResumeRecords } from '../../../../runtime/terminal/stop/worktree-sleep-resume-records' +import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) @@ -96,3 +97,65 @@ it.each([ expect(server.row()).toBeUndefined() } ) + +it('does not recapture a detached tmux writer from its remaining live checkpoint', async () => { + const server = await createServer() + server.setHookRootEvidenceReader( + (request) => readHookRootEvidence(request, io), + (request) => readPaneTmuxHost(io, request) + ) + const identities = new AgentStatusObservedPaneIdentities() + const observed = new AgentStatusObservedPaneIdentityCapture(identities) + const runtime = { + getAgentStatusTerminalHandleForPaneKey: () => 'terminal-a', + getTerminalProcessIncarnation: () => 'execution-a', + getAgentStatusOrchestrationContextForPaneKey: () => undefined + } + observed.attach(runtime) + server.subscribeEnrichedStatus((row) => observed.observe(row)) + server.setCliWriterExecutionMatcher(identities, runtime) + runningPane(4050, CLIENT, ...TMUX) + await hook(server, 'UserPromptSubmit', { + session: 'detached-session', + pid: 4043, + tmuxPane: TMUX_HINT, + prompt: 'In tmux' + }) + await server.checkAgentPresenceSince(PANE, 0) + const saved: SleepingAgentSessionRecord = { + paneKey: PANE, + worktreeId: 'wt-1', + agent: 'claude', + providerSession: { key: 'session_id', id: 'detached-session' }, + prompt: 'In tmux', + state: 'done', + capturedAt: NOW, + updatedAt: NOW, + origin: 'live' + } + const retireSavedRecord = vi.fn() + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => false, + isPlaced: () => true, + readSavedRecord: () => saved, + retireSavedRecord + }) + // Detach ends the outer command, while the original agent remains under its server. + runningPane(101, ...TMUX) + server.retireProcessAuthority(PANE, { confirmedExit: true }) + expect(retireSavedRecord).not.toHaveBeenCalled() + expect(server.row()).toBeUndefined() + const capture = await captureWorktreeSleepResumeRecords({ + worktreeId: 'wt-1', + paneKeysByPtyId: new Map([['pty', [PANE]]]), + launchByPtyId: new Map(), + readRowsForPane: (key) => server.getStatusSnapshotForPane(key), + readSavedRecord: async () => saved, + readIdentity: (key, record) => server.paneAgentIdentity(key, record), + checkAgentPresence: (key, since) => server.checkAgentPresenceSince(key, since ?? 0), + capturedAt: NOW + 1_000 + }) + expect(capture.get('pty')).toEqual({ records: [], retiredPaneKeys: [PANE] }) +}) diff --git a/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts b/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts index e05302f6a55d..d732739c8f56 100644 --- a/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts +++ b/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts @@ -106,8 +106,10 @@ export abstract class OrcaRuntimeWithSerializeAgentPromptSubmission extends Orca return } // No identified owner keeps legacy rules; an unverifiable owned process cannot be declared exited from silence. - if (verdict === null || verdict === 'unverifiable') { - this.confirmLegacyPtyAgentExit(ptyId, recoverCompletedHook, verdict === 'unverifiable') + if (verdict === null) { + this.confirmLegacyPtyAgentExit(ptyId, recoverCompletedHook, false) + } else if (verdict === 'unverifiable') { + this.ptyTitleTrackersByPtyId.get(ptyId)?.tracker.restoreLastAgentExit() } else if (verdict === 'exited' && !recoverCompletedHook) { this.recordTerminalSideEffectFact(ptyId, { kind: 'agent-exited' }) } else if (verdict === 'live') { diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 83210374d505..f88de13def66 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -16,6 +16,7 @@ const { TEST_WORKTREE_ID, TEST_WORKTREE_PATH, deferred, + syncSinglePty, makeRuntimeStoreWithWorkspaceSession, makeWorkspaceSessionWithHeadlessTerminal } = await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') @@ -240,7 +241,9 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini it.each([ ['quit', ['0'], false], ['suspended', ['148'], true], - ['suspended, then another command', ['148', '0'], true] + ['macOS suspended', ['146'], true], + ['suspended, then another command', ['148', '0'], true], + ['macOS suspended, then another command', ['146', '0'], true] ] as const)('%s', async (_, finishes, keepsRecovery) => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(1_000) @@ -324,7 +327,7 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini await wake('pty-3') for (const status of finishes) { tick() - runtime.onPtyData('pty-3', `\x1b]133;D;${status}\x07`, Date.now()) + runtime.onPtyData('pty-3', `\x1b]133;C\x07\x1b]133;D;${status}\x07`, Date.now()) } // A quit retires the saved conversation itself, before its exit evidence can expire. expect(await saved()).toEqual(keepsRecovery ? expect.objectContaining(resumable) : undefined) @@ -342,3 +345,33 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini } }) }) + +it('does not declare an identified stopped process ended when its title returns to the shell', async () => { + const fixture = makeRuntimeStoreWithWorkspaceSession(makeWorkspaceSessionWithHeadlessTerminal()) + const exits: string[] = [] + const checked = deferred() + const runtime = new OrcaRuntimeService(fixture.runtimeStore, undefined, { + checkHookAgentPresence: async () => { + checked.resolve() + return 'unverifiable' + }, + onTerminalSideEffects: (batch) => { + for (const fact of batch.facts) { + if (fact.kind === 'agent-exited') { + exits.push(fact.kind) + } + } + } + }) + runtime.setPtyController({ + write: () => true, + kill: () => false, + getForegroundProcess: async () => 'zsh' + }) + await syncSinglePty(runtime) + runtime.onPtyData('pty-1', '\x1b]0;✳ Claude Code\x07', 100) + runtime.onPtyData('pty-1', '\x1b]0;zsh\x07\x1b]133;D;146\x07', 101) + await checked.promise + await new Promise((resolve) => setImmediate(resolve)) + expect(exits).toEqual([]) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-identity.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-identity.ts index 1acb63276cec..bb245b76f400 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-identity.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-identity.ts @@ -1,8 +1,9 @@ +import { settlePaneShellForeground } from './pane-agent-shell-lifecycle' +import { isJobStopStatus } from '../../../../../../shared/terminal/output/terminal-osc133-command-finished' import { agentTypeToIconAgent } from '../../../../../../shared/agent-status/presentation/agent-type-icon-agent' import { dismissRetainedProgramResult } from '@/lib/program-status/result-retention' import { isRetainedProgramResult } from '@/lib/program-status/row' import { useAppStore } from '@/store/index' -import { CONFIRMED_SHELL_MODE_RESET } from '../../../../../../shared/terminal/protocol/input-modes/terminal-mode-reset-profiles' import { isLocalNativeWindowsConpty, resolveWindowsShellOverride @@ -156,38 +157,7 @@ export function installPaneAgentIdentity(session: ConnectPanePtySession): void { onAgentProcessRead: (process) => session.agentCompletionCoordinator?.observeForegroundAgentProcess(process), hasKnownAgentIdentity: session.paneHasKnownAgentIdentity, - onConfirmedShellForeground: (reason) => { - // Retire stale agent occupancy when a normal exit returns to the shell. - const state = useAppStore.getState() - const sleepingRecord = session.getSleepingRecordForPane(state) - const ptyId = session.transport.getPtyId() - const wake = session.hibernatedWakeTarget - // A delayed shell read can settle after exit consumes suppression; preserve only that PTY's exact wake record. - const isHibernationWakeRecord = - (ptyId && state.suppressedPtyExitIds[ptyId]) || - (wake && wake.record === sleepingRecord?.record && (ptyId === null || wake.ptyId === ptyId)) - if (sleepingRecord && !isHibernationWakeRecord) { - session.clearSleepingRecordProviderDuplicates(state, sleepingRecord) - } - session.clearStaleAgentTabTitleOnConfirmedShell() - // Confirmed hard-kill exit must disarm leftover mouse/focus/Kitty modes; guard reset auto-replies from reaching the shell. - session.writeInputModeGround(CONFIRMED_SHELL_MODE_RESET) - // Agents that leave their OSC title (grok, codex) never trip the title exit; Orca's own hibernation stop keeps its chat. - if (!isHibernationWakeRecord) { - session.deps.onAgentExitedRef.current(session.pane.leafId) - } - // Why: no 133;D backs these proofs, so a deferred command-finished drop keeps its own read. - if (reason === 'process-exit') { - // Why: reopen the one-shot visible sample so the next agent typed here is identified. - session.visibleForegroundSamplePending = false - session.visibleForegroundSampleSettled = false - } - if (reason === 'visible-pty' || reason === 'process-exit') { - state.clearAgentLaunchConfig(session.cacheKey) - return - } - session.settleDeferredCommandFinishedStatusDrop({ confirmedShell: true }) - }, + onConfirmedShellForeground: (reason) => settlePaneShellForeground(session, reason), // Wrap callbacks so caller arguments cannot become options that reconcile an unproven exit. onCommandFinishedUnavailable: () => session.settleDeferredCommandFinishedStatusDrop(), onVisibleForegroundSettled: (outcome) => { @@ -212,9 +182,14 @@ export function installPaneAgentIdentity(session: ConnectPanePtySession): void { session.handleCommandFinished = (bestEffortExitCode: number | null): void => { session.clearCommandInferredPaneAgentAfterPtySideEffects() session.visibleForegroundSamplePending = false - const shouldDeferStatusDrop = session.paneForegroundAgentTracker.onCommandFinished() // Commands can change HEAD/index; nudge git UI immediately instead of waiting for polling. dispatchTerminalCommandFinishedEvent(session.deps.worktreeId, bestEffortExitCode) + if (isJobStopStatus(bestEffortExitCode)) { + session.deferredCommandFinishedStatusDrop = null + session.deferredConfirmedShellReconcile = null + return + } + const shouldDeferStatusDrop = session.paneForegroundAgentTracker.onCommandFinished() const state = useAppStore.getState() const entry = state.agentStatusByPaneKey.get(session.cacheKey) const inferenceResult = session.flushPendingInterruptInference() diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts new file mode 100644 index 000000000000..73f8899a9523 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts @@ -0,0 +1,53 @@ +import { useAppStore } from '@/store/index' +import { CONFIRMED_SHELL_MODE_RESET } from '../../../../../../shared/terminal/protocol/input-modes/terminal-mode-reset-profiles' +import type { ConnectPanePtySession } from '../connect-pane-pty-session' + +/** Shell foreground and agent process lifetime are separate observations. */ +export function settlePaneShellForeground( + session: ConnectPanePtySession, + reason: 'visible-pty' | 'command-finished' | 'process-exit' +): void { + // The shell owns input even when a stopped job still exists. + session.writeInputModeGround(CONFIRMED_SHELL_MODE_RESET) + const ptyId = session.transport.getPtyId() + const acceptedStatusSeq = useAppStore + .getState() + .agentStatusByPaneKey.get(session.cacheKey)?.acceptedStatusSeq + // Foreground shell ownership cannot prove that a stopped agent process ended. + void Promise.resolve(window.api?.agentStatus?.hasVerifiableAgentProcess?.(session.cacheKey)) + .then((verifiable) => { + if ( + verifiable === true || + session.transport.getPtyId() !== ptyId || + useAppStore.getState().agentStatusByPaneKey.get(session.cacheKey)?.acceptedStatusSeq !== + acceptedStatusSeq + ) { + return + } + // Retire stale agent occupancy when a normal exit returns to the shell. + const state = useAppStore.getState() + const sleepingRecord = session.getSleepingRecordForPane(state) + const wake = session.hibernatedWakeTarget + // A delayed shell read can settle after exit consumes suppression; preserve only that PTY's exact wake record. + const isHibernationWakeRecord = + (ptyId && state.suppressedPtyExitIds[ptyId]) || + (wake && wake.record === sleepingRecord?.record && (ptyId === null || wake.ptyId === ptyId)) + session.clearStaleAgentTabTitleOnConfirmedShell() + // Agents that leave their OSC title (grok, codex) never trip the title exit; Orca's own hibernation stop keeps its chat. + if (!isHibernationWakeRecord) { + session.deps.onAgentExitedRef.current(session.pane.leafId) + } + // Why: no 133;D backs these proofs, so a deferred command-finished drop keeps its own read. + if (reason === 'process-exit') { + // Why: reopen the one-shot visible sample so the next agent typed here is identified. + session.visibleForegroundSamplePending = false + session.visibleForegroundSampleSettled = false + } + if (reason === 'visible-pty' || reason === 'process-exit') { + state.clearAgentLaunchConfig(session.cacheKey) + return + } + session.settleDeferredCommandFinishedStatusDrop({ confirmedShell: true }) + }) + .catch(console.warn) +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-cleanup.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-cleanup.spec.ts index 22190f92a999..c829a721823c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-cleanup.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-cleanup.spec.ts @@ -62,7 +62,7 @@ export function registerPtyConnectionCommandFinishedCleanupTests(): void { }) it.each([ - ['clears stale sleeping identity after a confirmed return to shell', false], + ['keeps recovery until main proves the owning agent ended', false], // Hibernation records resume before kill; the exposed shell is Orca’s own stop rather than an independent agent exit. ['keeps sleeping identity when the shell surfaces during an intentional stop', true] ])('%s', async (_label, stoppingOnPurpose) => { @@ -120,8 +120,10 @@ export function registerPtyConnectionCommandFinishedCleanupTests(): void { }) expect(deps.onAgentExitedRef.current).not.toHaveBeenCalled() } else { - expect(mockStoreState.clearSleepingAgentSession).toHaveBeenCalledExactlyOnceWith(paneKey) - expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toBeUndefined() + expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toMatchObject({ + agent: 'codex', + providerSession: { key: 'session_id', id: 'sess-1' } + }) expect(deps.onAgentExitedRef.current).toHaveBeenCalledWith(LEAF_1) } expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ @@ -130,6 +132,68 @@ export function registerPtyConnectionCommandFinishedCleanupTests(): void { }) }) + it.each([ + ['hand-launched Claude stops', 'claude', [[146, 'zsh']], true], + [ + 'wake-resumed Codex stops then runs ls', + 'codex', + [ + [146, 'codex'], + [0, 'zsh'] + ], + false + ] + ] as const)('keeps recovery when %s', async (_label, agent, finishes, verifiable) => { + vi.useFakeTimers() + const { connectPanePty } = await import('../connect-pane-pty') + const agentTitleMocks = await vi.importMock( + '@/lib/agent-status/aggregation/worktree-agent-status' + ) + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('zsh') + window.api.agentStatus.hasVerifiableAgentProcess = vi.fn(async () => verifiable) + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const transport = createMockTransport('pty-suspended-agent') + transport.connect.mockImplementation( + async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: 'pty-suspended-agent' } + } + ) + transportFactoryQueue.push(transport) + const paneKey = makePaneKey('tab-1', LEAF_1) + connectPanePty( + ...mockPanePtyArgs( + createPane(1), + createManager(1), + bindPaneAgentTitleMocks(createDeps({ isVisibleRef: { current: false } }), agentTitleMocks) + ) + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + mockStoreState.agentLaunchConfigByPaneKey[paneKey] = { + launchConfig: { agentArgs: '', agentEnv: {} }, + identity: { agentType: agent } + } + mockStoreState.sleepingAgentSessionsByPaneKey[paneKey] = { + paneKey, + worktreeId: 'wt-1', + agent, + providerSession: { key: 'session_id', id: 'stopped-session' }, + capturedAt: 1, + updatedAt: 1 + } + for (const [status, foreground] of finishes) { + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue(foreground) + vi.mocked(window.api.pty.getForegroundProcess).mockResolvedValue(foreground) + dataCallbackRef.current?.(`\x1b]133;C\x07\x1b]133;D;${status}\x07`) + await vi.advanceTimersByTimeAsync(1_000) + expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toMatchObject({ + agent, + providerSession: { key: 'session_id', id: 'stopped-session' } + }) + } + }) + it('keeps sleeping identity when the foreground check still sees the agent', async () => { vi.useFakeTimers() const { connectPanePty } = await import('../connect-pane-pty') From 3b33928819f4a20ecfc9213f8d1600f75b9c9a3d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:54:38 -0800 Subject: [PATCH 031/125] Retire quit agent recovery without conflating shell foreground and exit --- .../agent-hooks/server/agent-hook-server.ts | 19 +++ .../agent-hooks/server/pane-agent-identity.ts | 2 + src/main/agent-hooks/server/server-state.ts | 38 ++++++ .../server-idle-process-owner.test.ts | 2 + src/main/ipc/agent-status-row-teardown-ipc.ts | 7 +- .../terminal-pane-status-lifecycle.test.ts | 48 +++++++ .../pane/terminal-pane-status-lifecycle.ts | 32 +++++ .../terminal-agent-status-and-submission.ts | 10 +- .../worktree-sleep-resume-recording.test.ts | 95 +++++++++---- .../pane-agent-shell-lifecycle.ts | 59 +++++---- ...onnection-command-finished-cleanup.spec.ts | 8 +- ...connection-process-exit-row-retire.test.ts | 54 +++++--- ...status-listeners-resume-retirement.test.ts | 125 ++++++++++++++++++ .../resume/forget-refused-pane-resume.ts | 20 ++- .../contracts/agent-status-ipc-payload.ts | 2 +- 15 files changed, 419 insertions(+), 102 deletions(-) create mode 100644 src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts create mode 100644 src/renderer/src/hooks/ipc-events/agent-status-listeners-resume-retirement.test.ts diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 999b29ae8208..80bbbd537692 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -78,6 +78,25 @@ export class AgentHookServer extends AgentHookServerLifecycle { return presence?.process !== undefined && !presence.ended } + /** Shells without command marks need the owning host's process-tree proof. */ + async reconcilePaneProcessExit(paneKey: string): Promise { + const resolved = this.resolvePaneKeyAlias(paneKey) + const row = this.state.lastStatusByPaneKey.get(resolved) + const identity = this.paneAgentIdentity(resolved) + const confirmedExit = + identity && + identity.processTopology !== 'shared' && + !this.hasVerifiableAgentProcess(resolved) && + (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, identity.status.agentType)) + if (this.state.lastStatusByPaneKey.get(resolved) !== row) { + return + } + this.reconcileEndedProcessForPaneKeys([resolved], { + preserveResumeIdentity: true, + confirmedExit: confirmedExit === true + }) + } + /** Pin inspection to this row so a replacement owner cannot become its subject. */ readCliWriterObservation(expected: AgentStatusIpcPayload): CliWriterObservation | null { const resolved = this.resolvePaneKeyAlias(expected.paneKey) diff --git a/src/main/agent-hooks/server/pane-agent-identity.ts b/src/main/agent-hooks/server/pane-agent-identity.ts index cff960a67231..76bbb2444ecb 100644 --- a/src/main/agent-hooks/server/pane-agent-identity.ts +++ b/src/main/agent-hooks/server/pane-agent-identity.ts @@ -7,6 +7,8 @@ export type PaneAgentIdentity = { status: AgentStatusIpcPayload /** The agent left the pane; its identity names what to retire, not what to resume. */ ended: boolean + /** Positive local process observation; shell foreground does not end a stopped job. */ + suspended?: true /** Shared servers survive the pane; their conversation must not be launched again on wake. */ processTopology?: 'pane-owned' | 'shared' | 'unverifiable' } diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 34ed484e26b0..4b0c0e9e4d94 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -53,6 +53,7 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract protected terminalPaneLifecycle: { retireSavedRecord?(paneKey: string, exitedAt: number): void readSavedRecord?(paneKey: string): SleepingAgentSessionRecord | undefined + confirmProcessExit?(paneKey: string, agent: string): Promise ownsProcess(paneKey: string, ptyId: string, incarnationId?: string): boolean isStopping(paneKey: string): boolean isReversibleStop(ptyId: string, incarnationId?: string): boolean @@ -94,6 +95,12 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract return identity ? { ...identity, + ...(row?.connectionId === null && + row.agentPresence?.process && + row.agentPresence.suspended && + !row.agentPresence.ended + ? { suspended: true as const } + : {}), processTopology: row ? (legacy ? cliWriterTopology(row) : 'shared') : 'pane-owned' } : null @@ -107,9 +114,40 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract } } const exitedAt = Date.now() + const status = this.paneAgentIdentity(paneKey)?.status recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, endedPresence, exitedAt) for (const key of paneKeys) { + const saved = this.terminalPaneLifecycle?.readSavedRecord?.(key) this.terminalPaneLifecycle?.retireSavedRecord?.(key, exitedAt) + const agent = status?.agentType ?? saved?.agent + const providerSession = status?.providerSession ?? saved?.providerSession + if (agent && providerSession) { + this.emitPaneStatusCleared({ + paneKey: key, + refusedResume: { + agent, + providerSession, + ...(status + ? { + expectedStatus: { + paneKey: key, + receivedAt: status.receivedAt, + stateStartedAt: status.stateStartedAt + } + } + : {}), + ...(saved && saved.updatedAt <= exitedAt + ? { + expectedSavedRecord: { + paneKey: key, + capturedAt: saved.capturedAt, + updatedAt: saved.updatedAt + } + } + : {}) + } + }) + } } this.scheduleStatusPersist() } diff --git a/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts index f16f83c8204f..4e542c8b617c 100644 --- a/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts @@ -109,6 +109,7 @@ describe('idle foreground process owns its provider session', () => { }) await server.checkAgentPresence(PANE) expect(emitted.mock.lastCall?.[0].agentPresence?.suspended).toBe(true) + expect(server.paneAgentIdentity(PANE)?.suspended).toBe(true) probe.mockImplementation(async (_identity, _read, _platform, observe) => { if (verdict === 'live') { observe?.(false) @@ -127,6 +128,7 @@ describe('idle foreground process owns its provider session', () => { expect(probe).toHaveBeenCalledTimes(2) assertClaudeSession(server) expect(emitted.mock.lastCall?.[0].agentPresence?.suspended).toBeUndefined() + expect(server.paneAgentIdentity(PANE)?.suspended).toBeUndefined() } ) diff --git a/src/main/ipc/agent-status-row-teardown-ipc.ts b/src/main/ipc/agent-status-row-teardown-ipc.ts index 264f44a3dc2e..acbd5a6a7405 100644 --- a/src/main/ipc/agent-status-row-teardown-ipc.ts +++ b/src/main/ipc/agent-status-row-teardown-ipc.ts @@ -72,10 +72,9 @@ export function registerAgentStatusRowTeardownIpcHandlers(): void { } try { // Confirmed process exit must clear latches with the row (STA-4612). - agentHookServer.reconcileEndedProcessForPaneKeys([paneKey], { - // The shell still owns the PTY, so keep its usable resume identity. - preserveResumeIdentity: true - }) + void agentHookServer + .reconcilePaneProcessExit(paneKey) + .catch((err) => console.warn('[agent-hooks] reconcilePaneProcessExit failed:', err)) clearMigrationUnsupportedPtysForPaneKey(paneKey) } catch (err) { console.warn('[agent-hooks] reconcileEndedProcessForPaneKeys failed:', err) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts new file mode 100644 index 000000000000..f1570d0e01c8 --- /dev/null +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -0,0 +1,48 @@ +import { expect, it, vi } from 'vitest' +import type { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { bindTerminalPaneStatusLifecycle } from './terminal-pane-status-lifecycle' + +const { setTerminalPaneLifecycle, getProviderForPty } = vi.hoisted(() => ({ + setTerminalPaneLifecycle: vi.fn(), + getProviderForPty: vi.fn() +})) +vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ + agentHookServer: { setTerminalPaneLifecycle, pruneUnplacedSleepingPanes: () => {} } +})) +vi.mock('../provider/registry', () => ({ getProviderForPty })) + +it.each([ + ['quit at cmd', false, 'cmd.exe', true, false, true], + ['quit at Git Bash', false, 'bash', true, false, true], + ['stopped child', true, 'bash', true, false, false], + ['agent foreground', false, 'codex', true, false, false], + ['unanswered shell', false, null, true, false, false], + ['intervening command revoked launch', false, 'bash', false, false, false], + ['successor launch during inspection', false, 'cmd.exe', true, true, false] +] as const)( + 'proves an unmarked process exit only for the current launch: %s', + async (_, children, foreground, held, replaced, expected) => { + const launch = { agentArgs: '', agentEnv: {} } + let currentLaunch = held ? launch : null + getProviderForPty.mockReturnValue({ + hasChildProcesses: async () => children, + confirmForegroundProcess: async () => { + if (replaced) { + currentLaunch = { agentArgs: '--resume next', agentEnv: {} } + } + return foreground + } + }) + // SAFETY: This binding's exit probe only reads these two runtime capabilities. + const runtime = { + resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }), + getLaunchStatementForPaneKey: () => currentLaunch + } as unknown as OrcaRuntimeService + bindTerminalPaneStatusLifecycle(runtime, undefined) + const lifecycle = setTerminalPaneLifecycle.mock.lastCall![0] + expect( + await lifecycle.confirmProcessExit?.('tab:11111111-1111-4111-8111-111111111111', 'codex') + ).toBe(expected) + } +) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 05bd36664b77..de6e688a2ca4 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -7,6 +7,9 @@ import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-top import { paneKeyPtyId } from './key-state' import { ptyIncarnationById } from '../provider/ownership-state' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' +import { getProviderForPty } from '../provider/registry' +import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' +import { isRemoteExecutionHostPtyId } from '../../../../shared/execution-host/remote-execution-host-pty-id' export function bindTerminalPaneStatusLifecycle( runtime: OrcaRuntimeService | undefined, @@ -14,6 +17,35 @@ export function bindTerminalPaneStatusLifecycle( ): void { agentHookServer.setTerminalPaneLifecycle({ retireSavedRecord: (paneKey, exitedAt) => runtime?.retireExitedPaneResume(paneKey, exitedAt), + confirmProcessExit: async (paneKey, agent) => { + if (!runtime) { + return false + } + try { + const pane = runtime.resolveTerminalPane(paneKey) + const launch = runtime.getLaunchStatementForPaneKey(paneKey, agent) + // A finished/intervening command has already revoked this launch's authority. + if (!pane.ptyId || isRemoteExecutionHostPtyId(pane.ptyId) || !launch) { + return false + } + const provider = getProviderForPty(pane.ptyId) + const [children, foreground] = await Promise.all([ + provider.hasChildProcesses(pane.ptyId), + provider.confirmForegroundProcess?.(pane.ptyId) + ]) + const current = runtime.resolveTerminalPane(paneKey) + return ( + children === false && + typeof foreground === 'string' && + isShellProcess(foreground) && + current.ptyId === pane.ptyId && + current.incarnationId === pane.incarnationId && + runtime.getLaunchStatementForPaneKey(paneKey, agent) === launch + ) + } catch { + return false + } + }, readSavedRecord: (paneKey) => { try { const worktreeId = runtime?.getTerminalWorktreeIdForPaneKey(paneKey) diff --git a/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts b/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts index d732739c8f56..58a614f5124b 100644 --- a/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts +++ b/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts @@ -105,11 +105,13 @@ export abstract class OrcaRuntimeWithSerializeAgentPromptSubmission extends Orca if (this.ptysById.get(ptyId) !== current || current?.incarnationId !== incarnation) { return } - // No identified owner keeps legacy rules; an unverifiable owned process cannot be declared exited from silence. - if (verdict === null) { - this.confirmLegacyPtyAgentExit(ptyId, recoverCompletedHook, false) - } else if (verdict === 'unverifiable') { + const suspended = Array.from(this.collectAgentStatusPaneKeysForPty(ptyId)).some( + (paneKey) => this.readPaneAgentIdentity(paneKey)?.suspended === true + ) + if (verdict === 'unverifiable' && suspended) { this.ptyTitleTrackersByPtyId.get(ptyId)?.tracker.restoreLastAgentExit() + } else if (verdict === null || verdict === 'unverifiable') { + this.confirmLegacyPtyAgentExit(ptyId, recoverCompletedHook, verdict === 'unverifiable') } else if (verdict === 'exited' && !recoverCompletedHook) { this.recordTerminalSideEffectFact(ptyId, { kind: 'agent-exited' }) } else if (verdict === 'live') { diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index f88de13def66..b7638d4bd536 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it, vi } from 'vitest' import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' -import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { + AgentStatusClearIpcPayload, + AgentStatusIpcPayload +} from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' // Preserve side-effect order: mocks, lifecycle, fixtures. await import('../../orca-runtime-tests/runtime-test-module-registration.spec') @@ -240,6 +243,7 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini it.each([ ['quit', ['0'], false], + ['quit without command marks', ['unmarked'], false], ['suspended', ['148'], true], ['macOS suspended', ['146'], true], ['suspended, then another command', ['148', '0'], true], @@ -265,8 +269,11 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini isReversibleStop: () => false, isPlaced: () => true, readSavedRecord: (paneKey) => fixture.getSession().sleepingAgentSessionsByPaneKey?.[paneKey], + confirmProcessExit: async () => true, retireSavedRecord: (paneKey, at) => runtime.retireExitedPaneResume(paneKey, at) }) + const clears: AgentStatusClearIpcPayload[] = [] + server.subscribePaneStatusClear((clear) => clears.push(clear)) const live = new Set() runtime.setPtyController({ write: () => true, @@ -327,8 +334,25 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini await wake('pty-3') for (const status of finishes) { tick() - runtime.onPtyData('pty-3', `\x1b]133;C\x07\x1b]133;D;${status}\x07`, Date.now()) + if (status === 'unmarked') { + await server.reconcilePaneProcessExit(PANE_KEY) + } else { + runtime.onPtyData('pty-3', `\x1b]133;C\x07\x1b]133;D;${status}\x07`, Date.now()) + } } + expect(clears.filter((clear) => 'paneKey' in clear && clear.refusedResume)).toEqual( + keepsRecovery + ? [] + : [ + expect.objectContaining({ + paneKey: PANE_KEY, + refusedResume: expect.objectContaining({ + agent: 'codex', + providerSession: { key: 'session_id', id: 'woken-codex' } + }) + }) + ] + ) // A quit retires the saved conversation itself, before its exit evidence can expire. expect(await saved()).toEqual(keepsRecovery ? expect.objectContaining(resumable) : undefined) server.forgetAgentExit(PANE_KEY) @@ -346,32 +370,45 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini }) }) -it('does not declare an identified stopped process ended when its title returns to the shell', async () => { - const fixture = makeRuntimeStoreWithWorkspaceSession(makeWorkspaceSessionWithHeadlessTerminal()) - const exits: string[] = [] - const checked = deferred() - const runtime = new OrcaRuntimeService(fixture.runtimeStore, undefined, { - checkHookAgentPresence: async () => { - checked.resolve() - return 'unverifiable' - }, - onTerminalSideEffects: (batch) => { - for (const fact of batch.facts) { - if (fact.kind === 'agent-exited') { - exits.push(fact.kind) +it.each([ + ['locally suspended', true, 'zsh', []], + ['SSH or undecided owner at the shell', false, 'zsh', ['agent-exited']], + ['unanswered foreground', false, null, []], + ['agent still foreground', false, 'claude', []] +] as const)( + 'confirms title exit using process evidence: %s', + async (_, suspended, foreground, expected) => { + const fixture = makeRuntimeStoreWithWorkspaceSession(makeWorkspaceSessionWithHeadlessTerminal()) + const exits: string[] = [] + const checked = deferred() + const runtime = new OrcaRuntimeService(fixture.runtimeStore, undefined, { + checkHookAgentPresence: async () => { + checked.resolve() + return 'unverifiable' + }, + getPaneAgentIdentity: () => ({ + status: NEWER_STATUS, + ended: false, + ...(suspended ? { suspended: true } : {}) + }), + onTerminalSideEffects: (batch) => { + for (const fact of batch.facts) { + if (fact.kind === 'agent-exited') { + exits.push(fact.kind) + } } } - } - }) - runtime.setPtyController({ - write: () => true, - kill: () => false, - getForegroundProcess: async () => 'zsh' - }) - await syncSinglePty(runtime) - runtime.onPtyData('pty-1', '\x1b]0;✳ Claude Code\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;zsh\x07\x1b]133;D;146\x07', 101) - await checked.promise - await new Promise((resolve) => setImmediate(resolve)) - expect(exits).toEqual([]) -}) + }) + runtime.setPtyController({ + write: () => true, + kill: () => false, + getForegroundProcess: async () => foreground + }) + await syncSinglePty(runtime) + runtime.onPtyData('pty-1', '\x1b]0;✳ Claude Code\x07', 100) + runtime.onPtyData('pty-1', '\x1b]0;zsh\x07', 101) + await checked.promise + await new Promise((resolve) => setImmediate(resolve)) + expect(exits).toEqual(expected) + } +) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts index 73f8899a9523..0699562d6242 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts @@ -7,47 +7,48 @@ export function settlePaneShellForeground( session: ConnectPanePtySession, reason: 'visible-pty' | 'command-finished' | 'process-exit' ): void { - // The shell owns input even when a stopped job still exists. - session.writeInputModeGround(CONFIRMED_SHELL_MODE_RESET) + const state = useAppStore.getState() const ptyId = session.transport.getPtyId() + const sleepingRecord = session.getSleepingRecordForPane(state) + const wake = session.hibernatedWakeTarget + const isHibernationWakeRecord = + (ptyId && state.suppressedPtyExitIds[ptyId]) || + (wake && wake.record === sleepingRecord?.record && (ptyId === null || wake.ptyId === ptyId)) + session.clearStaleAgentTabTitleOnConfirmedShell() + session.writeInputModeGround(CONFIRMED_SHELL_MODE_RESET) + if (!isHibernationWakeRecord) { + session.deps.onAgentExitedRef.current(session.pane.leafId) + } + if (reason === 'process-exit') { + session.visibleForegroundSamplePending = false + session.visibleForegroundSampleSettled = false + } + if (reason === 'visible-pty' || reason === 'process-exit') { + state.clearAgentLaunchConfig(session.cacheKey) + } else { + session.settleDeferredCommandFinishedStatusDrop({ confirmedShell: true }) + } + // Only the monitor's settled no-agent/no-children proof can retire recovery without command marks. + if (reason !== 'process-exit' || !sleepingRecord || isHibernationWakeRecord) { + return + } const acceptedStatusSeq = useAppStore .getState() .agentStatusByPaneKey.get(session.cacheKey)?.acceptedStatusSeq - // Foreground shell ownership cannot prove that a stopped agent process ended. void Promise.resolve(window.api?.agentStatus?.hasVerifiableAgentProcess?.(session.cacheKey)) .then((verifiable) => { + const current = useAppStore.getState() if ( verifiable === true || session.transport.getPtyId() !== ptyId || - useAppStore.getState().agentStatusByPaneKey.get(session.cacheKey)?.acceptedStatusSeq !== - acceptedStatusSeq + current.agentStatusByPaneKey.get(session.cacheKey)?.acceptedStatusSeq !== + acceptedStatusSeq || + session.getSleepingRecordForPane(current)?.record !== sleepingRecord.record || + (ptyId && current.suppressedPtyExitIds[ptyId]) ) { return } - // Retire stale agent occupancy when a normal exit returns to the shell. - const state = useAppStore.getState() - const sleepingRecord = session.getSleepingRecordForPane(state) - const wake = session.hibernatedWakeTarget - // A delayed shell read can settle after exit consumes suppression; preserve only that PTY's exact wake record. - const isHibernationWakeRecord = - (ptyId && state.suppressedPtyExitIds[ptyId]) || - (wake && wake.record === sleepingRecord?.record && (ptyId === null || wake.ptyId === ptyId)) - session.clearStaleAgentTabTitleOnConfirmedShell() - // Agents that leave their OSC title (grok, codex) never trip the title exit; Orca's own hibernation stop keeps its chat. - if (!isHibernationWakeRecord) { - session.deps.onAgentExitedRef.current(session.pane.leafId) - } - // Why: no 133;D backs these proofs, so a deferred command-finished drop keeps its own read. - if (reason === 'process-exit') { - // Why: reopen the one-shot visible sample so the next agent typed here is identified. - session.visibleForegroundSamplePending = false - session.visibleForegroundSampleSettled = false - } - if (reason === 'visible-pty' || reason === 'process-exit') { - state.clearAgentLaunchConfig(session.cacheKey) - return - } - session.settleDeferredCommandFinishedStatusDrop({ confirmedShell: true }) + session.clearSleepingRecordProviderDuplicates(current, sleepingRecord) }) .catch(console.warn) } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-cleanup.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-cleanup.spec.ts index c829a721823c..125b7bde6c57 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-cleanup.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-cleanup.spec.ts @@ -62,15 +62,17 @@ export function registerPtyConnectionCommandFinishedCleanupTests(): void { }) it.each([ - ['keeps recovery until main proves the owning agent ended', false], + ['keeps recovery until main proves the owning agent ended', false, false], + ['settles shell UI even when main has a process identity', false, true], // Hibernation records resume before kill; the exposed shell is Orca’s own stop rather than an independent agent exit. - ['keeps sleeping identity when the shell surfaces during an intentional stop', true] - ])('%s', async (_label, stoppingOnPurpose) => { + ['keeps sleeping identity when the shell surfaces during an intentional stop', true, false] + ])('%s', async (_label, stoppingOnPurpose, verifiable) => { vi.useFakeTimers() const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks5 = await vi.importMock( '@/lib/agent-status/aggregation/worktree-agent-status' ) + window.api.agentStatus.hasVerifiableAgentProcess = vi.fn(async () => verifiable) vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('zsh') const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } const ptyId = 'pty-sleeping-confirmed-shell' diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts index ad5a5d2b769b..d76d52891f2f 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts @@ -185,7 +185,7 @@ async function connectAgentPane(args: { async function seedHookRow( paneKey: string, - agentType: 'claude' | 'codex', + agentType: 'claude' | 'codex' | 'gemini' | 'opencode', state: 'working' | 'done' = 'done' ): Promise { // Why the real slice: the row must carry the acceptedStatusSeq a real accepted hook stamps. @@ -252,28 +252,40 @@ describe('connectPanePty confirmed process exit retires the live agent row', () ) }) - it('drops the row and retires main latches when Claude exits in a pane without command marks', async () => { - let foreground: string | null = 'claude' - let children = true - vi.mocked(window.api.pty.getForegroundProcess).mockImplementation(async () => foreground) - vi.mocked(window.api.pty.hasChildProcesses).mockImplementation(async () => children) - const { paneKey } = await connectAgentPane({ ptyId: 'pty-cmd-claude', visible: true }) - await seedHookRow(paneKey, 'claude') - await vi.advanceTimersByTimeAsync(3_000) - expect(mockStoreState.agentStatusByPaneKey.get(paneKey)!).toBeDefined() + it.each(['claude', 'codex', 'gemini', 'opencode'] as const)( + 'retires %s recovery and row after a process exit without command marks', + async (agent) => { + let foreground: string | null = agent + let children = true + vi.mocked(window.api.pty.getForegroundProcess).mockImplementation(async () => foreground) + vi.mocked(window.api.pty.hasChildProcesses).mockImplementation(async () => children) + const { paneKey } = await connectAgentPane({ ptyId: 'pty-cmd-claude', visible: true }) + await seedHookRow(paneKey, agent) + mockStoreState.sleepingAgentSessionsByPaneKey[paneKey] = { + paneKey, + worktreeId: 'wt-1', + agent, + providerSession: { key: 'session_id', id: 'quit-session' }, + capturedAt: 1, + updatedAt: 1 + } + await vi.advanceTimersByTimeAsync(3_000) + expect(mockStoreState.agentStatusByPaneKey.get(paneKey)!).toBeDefined() - // `/exit` in cmd.exe: the shell is back and no 133;D ever arrives. - foreground = 'cmd.exe' - children = false - await vi.advanceTimersByTimeAsync(10_000) - await flushAsyncTicks() + // `/exit` in cmd.exe: the shell is back and no 133;D ever arrives. + foreground = 'cmd.exe' + children = false + await vi.advanceTimersByTimeAsync(10_000) + await flushAsyncTicks() - expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey) - // No `paneRemoved`: the pane outlived the agent, so main keeps the resume identity. - expect(mockStoreState.dropAgentStatus.mock.calls).toEqual([[paneKey]]) - expect(window.api.agentStatus.reconcileEndedProcess).toHaveBeenCalledWith(paneKey) - expect(mockStoreState.agentStatusByPaneKey.get(paneKey)!).toBeUndefined() - }) + expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toBeUndefined() + expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey) + // No `paneRemoved`: the pane outlived the agent, so main keeps the resume identity. + expect(mockStoreState.dropAgentStatus.mock.calls).toEqual([[paneKey]]) + expect(window.api.agentStatus.reconcileEndedProcess).toHaveBeenCalledWith(paneKey) + expect(mockStoreState.agentStatusByPaneKey.get(paneKey)!).toBeUndefined() + } + ) it('keeps the row when the agent is relaunched before the exit settles', async () => { const hostAnswer = createDeferred() diff --git a/src/renderer/src/hooks/ipc-events/agent-status-listeners-resume-retirement.test.ts b/src/renderer/src/hooks/ipc-events/agent-status-listeners-resume-retirement.test.ts new file mode 100644 index 000000000000..b88faf085103 --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/agent-status-listeners-resume-retirement.test.ts @@ -0,0 +1,125 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type { AppState } from '@/store/types' +import { createTestStore } from '@/store/testing/app-store-test-fixture' +import { registerAgentStatusListeners } from './agent-status-listeners' +import { buildSleepingAgentSessionData } from '@/lib/workspace/persistence/workspace-session-sleeping-agents' +import type { + AgentStatusClearIpcPayload, + AgentStatusIpcPayload +} from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { PendingAgentStatusEvent } from './agent-status-bridge-types' + +let store: ReturnType +vi.mock('@/store/index', () => ({ useAppStore: { getState: (): AppState => store.getState() } })) + +afterEach(() => vi.unstubAllGlobals()) + +it.each(['live', 'quit'] as const)( + 'keeps a retired %s record out of the next window save, including queued status', + (origin) => { + store = createTestStore() + const paneKey = 'tab-1:11111111-1111-4111-8111-111111111111' + store.setState({ + sleepingAgentSessionsByPaneKey: { + [paneKey]: { + paneKey, + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'quit-codex' }, + prompt: '', + state: 'done', + capturedAt: 250, + updatedAt: 200, + origin + }, + 'other-pane': { + paneKey: 'other-pane', + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'other-codex' }, + prompt: '', + state: 'done', + capturedAt: 250, + updatedAt: 200, + origin + } + } + }) + let clear: (data: AgentStatusClearIpcPayload) => void = () => { + throw new Error('No clear listener') + } + vi.stubGlobal('window', { + api: { + agentStatus: { + onSet: () => () => {}, + onClear: (listener: typeof clear) => { + clear = listener + return () => {} + } + } + } + }) + const status: AgentStatusIpcPayload = { + paneKey, + worktreeId: 'wt-1', + agentType: 'codex', + state: 'done', + prompt: '', + providerSession: { key: 'session_id', id: 'quit-codex' }, + connectionId: null, + receivedAt: 200, + stateStartedAt: 150 + } + const liveAgentStatusBurstQueue = [status] + const pendingAgentStatusEvents: PendingAgentStatusEvent[] = [ + { data: status, firstSeenAt: 201, replay: false } + ] + registerAgentStatusListeners({ + unsubs: [], + enqueueLiveAgentStatus: () => {}, + drainQueuedLiveAgentStatusesForPane: () => {}, + pendingAgentStatusEvents, + liveAgentStatusBurstQueue, + transientClearWatermarkByConnectionId: new Map() + }) + clear({ + paneKey, + refusedResume: { + agent: 'codex', + providerSession: { key: 'session_id', id: 'quit-codex' }, + expectedStatus: { paneKey, receivedAt: 200, stateStartedAt: 150 }, + expectedSavedRecord: { paneKey, capturedAt: 200, updatedAt: 200 } + } + }) + const saved = buildSleepingAgentSessionData(store.getState()).sleepingAgentSessionsByPaneKey + expect(saved?.[paneKey]).toBeUndefined() + expect(saved?.['other-pane']?.providerSession.id).toBe('other-codex') + expect(liveAgentStatusBurstQueue).toEqual([]) + expect(pendingAgentStatusEvents).toEqual([]) + // A later observation of the same conversation is a successor, not the retired checkpoint. + store.setState({ + sleepingAgentSessionsByPaneKey: { + [paneKey]: { + paneKey, + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'quit-codex' }, + prompt: '', + state: 'working', + capturedAt: 300, + updatedAt: 300, + origin + } + } + }) + clear({ + paneKey, + refusedResume: { + agent: 'codex', + providerSession: { key: 'session_id', id: 'quit-codex' }, + expectedStatus: { paneKey, receivedAt: 200, stateStartedAt: 150 } + } + }) + expect(store.getState().sleepingAgentSessionsByPaneKey[paneKey]?.state).toBe('working') + } +) diff --git a/src/renderer/src/lib/agent-session/resume/forget-refused-pane-resume.ts b/src/renderer/src/lib/agent-session/resume/forget-refused-pane-resume.ts index 7e2320809d43..07eb529e74eb 100644 --- a/src/renderer/src/lib/agent-session/resume/forget-refused-pane-resume.ts +++ b/src/renderer/src/lib/agent-session/resume/forget-refused-pane-resume.ts @@ -21,27 +21,25 @@ export function namesRefusedResume( ) } -/** - * Main refused `paneKey`'s saved resume because a native chat owns that conversation. Forgets it as - * this pane's, whether or not the pane is mounted, so nothing offers or retries it here. Another - * pane holding the same conversation is refused and forgotten at its own restore. Main already - * forgot its own copy, so nothing is sent back. - */ +/** Forget the host-retired conversation even in unmounted panes; newer observations survive. */ export function forgetRefusedPaneResume( state: AppState, paneKey: string, refused: RefusedPaneResume ): void { const expected = refused.expectedSavedRecord - const saved = expected && state.sleepingAgentSessionsByPaneKey[expected.paneKey] + const savedKey = expected?.paneKey ?? paneKey + const saved = state.sleepingAgentSessionsByPaneKey[savedKey] if ( - expected && saved && - saved.capturedAt === expected.capturedAt && - saved.updatedAt === expected.updatedAt && + ((expected && + saved.capturedAt === expected.capturedAt && + saved.updatedAt === expected.updatedAt) || + // Main and window may capture the same accepted status at different times. + (refused.expectedStatus && saved.updatedAt <= refused.expectedStatus.receivedAt)) && namesRefusedResume(refused, saved) ) { - state.clearSleepingAgentSession(expected.paneKey) + state.clearSleepingAgentSession(savedKey) } const identity = refused.expectedStatus if (!identity) { diff --git a/src/shared/agent-status/contracts/agent-status-ipc-payload.ts b/src/shared/agent-status/contracts/agent-status-ipc-payload.ts index 40ccc227bd9d..38ff4de41a25 100644 --- a/src/shared/agent-status/contracts/agent-status-ipc-payload.ts +++ b/src/shared/agent-status/contracts/agent-status-ipc-payload.ts @@ -116,7 +116,7 @@ export type AgentStatusCacheIdentity = { stateStartedAt: number } -/** A pane's saved resume the host refused because a native chat is that conversation's home. */ +/** A pane's resume identity the host retired after an exit or refused restore. */ export type RefusedPaneResume = { expectedStatus?: AgentStatusCacheIdentity expectedSavedRecord?: { paneKey: string; capturedAt: number; updatedAt: number } From 75c61adfa11436f524e1e1d5d08465aef1ca7565 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:18:38 -0800 Subject: [PATCH 032/125] Route quiet shell confirmation through the current launch owner --- .../agent-hooks/server/agent-hook-server.ts | 4 ++- .../pane-agent-shell-lifecycle.ts | 30 +++++-------------- ...nnection-foreground-agent-sampling.spec.ts | 1 + ...connection-process-exit-row-retire.test.ts | 5 +++- 4 files changed, 15 insertions(+), 25 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 80bbbd537692..190b5398e697 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -83,11 +83,13 @@ export class AgentHookServer extends AgentHookServerLifecycle { const resolved = this.resolvePaneKeyAlias(paneKey) const row = this.state.lastStatusByPaneKey.get(resolved) const identity = this.paneAgentIdentity(resolved) + const agent = identity?.status.agentType const confirmedExit = identity && + agent && identity.processTopology !== 'shared' && !this.hasVerifiableAgentProcess(resolved) && - (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, identity.status.agentType)) + (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, agent)) if (this.state.lastStatusByPaneKey.get(resolved) !== row) { return } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts index 0699562d6242..a1ae2139e21e 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts @@ -1,6 +1,7 @@ import { useAppStore } from '@/store/index' import { CONFIRMED_SHELL_MODE_RESET } from '../../../../../../shared/terminal/protocol/input-modes/terminal-mode-reset-profiles' import type { ConnectPanePtySession } from '../connect-pane-pty-session' +import { isRemoteExecutionHostPtyId } from '../../../../../../shared/execution-host/remote-execution-host-pty-id' /** Shell foreground and agent process lifetime are separate observations. */ export function settlePaneShellForeground( @@ -25,30 +26,13 @@ export function settlePaneShellForeground( } if (reason === 'visible-pty' || reason === 'process-exit') { state.clearAgentLaunchConfig(session.cacheKey) + if (ptyId && !isRemoteExecutionHostPtyId(ptyId) && !isHibernationWakeRecord) { + // Quiet wake launches can exit without ever posting a hook row or command mark. + session.reconcileEndedProcessIfPaneQuiet( + state.agentStatusByPaneKey.get(session.cacheKey)?.acceptedStatusSeq + ) + } } else { session.settleDeferredCommandFinishedStatusDrop({ confirmedShell: true }) } - // Only the monitor's settled no-agent/no-children proof can retire recovery without command marks. - if (reason !== 'process-exit' || !sleepingRecord || isHibernationWakeRecord) { - return - } - const acceptedStatusSeq = useAppStore - .getState() - .agentStatusByPaneKey.get(session.cacheKey)?.acceptedStatusSeq - void Promise.resolve(window.api?.agentStatus?.hasVerifiableAgentProcess?.(session.cacheKey)) - .then((verifiable) => { - const current = useAppStore.getState() - if ( - verifiable === true || - session.transport.getPtyId() !== ptyId || - current.agentStatusByPaneKey.get(session.cacheKey)?.acceptedStatusSeq !== - acceptedStatusSeq || - session.getSleepingRecordForPane(current)?.record !== sleepingRecord.record || - (ptyId && current.suppressedPtyExitIds[ptyId]) - ) { - return - } - session.clearSleepingRecordProviderDuplicates(current, sleepingRecord) - }) - .catch(console.warn) } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-sampling.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-sampling.spec.ts index 781c9e5e5776..4c3a69258b55 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-sampling.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-sampling.spec.ts @@ -483,6 +483,7 @@ export function registerPtyConnectionForegroundAgentSamplingTests(): void { shellForeground: true }) expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledWith(cacheKey) + expect(window.api.agentStatus.reconcileEndedProcess).toHaveBeenCalledWith(cacheKey) mockStoreState.paneForegroundAgentByPaneKey[cacheKey] = { agent: null, diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts index d76d52891f2f..4228f2c4f82c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts @@ -278,7 +278,10 @@ describe('connectPanePty confirmed process exit retires the live agent row', () await vi.advanceTimersByTimeAsync(10_000) await flushAsyncTicks() - expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toBeUndefined() + // Main owns retirement; a process exit requests its proof rather than deleting recovery here. + expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]?.providerSession.id).toBe( + 'quit-session' + ) expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey) // No `paneRemoved`: the pane outlived the agent, so main keeps the resume identity. expect(mockStoreState.dropAgentStatus.mock.calls).toEqual([[paneKey]]) From f7f808423a1bbdb60e04f673c2e1039431dcb8f6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:07:29 -0800 Subject: [PATCH 033/125] Keep suspended Codex recovery through listings and release detached tmux conversations A listing re-mints a restored surface's receipt after Ctrl-Z already retired its launch, so the next unrelated command read as the agent's exit. Only a launch no finish has retired names one now. A tmux client's detach left only the pane's saved checkpoint, which sleep re-promoted as pane-owned and woke as a duplicate resume; the shared conversation now releases that checkpoint when its client leaves the pane. --- src/main/agent-hooks/server/server-state.ts | 29 +++++++++++++++---- .../agent-hooks/server/server-tab-cleanup.ts | 9 +++--- .../agent-hooks/server/server-tmux-status.ts | 5 ++++ .../tmux/server-tmux-legacy-sleep.test.ts | 17 ++++++----- .../terminal-orchestration-authority.ts | 10 +++---- .../worktree-sleep-resume-recording.test.ts | 14 ++++++++- 6 files changed, 61 insertions(+), 23 deletions(-) diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 4b0c0e9e4d94..1f66e89b9b8b 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -107,15 +107,32 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract } protected recordPaneAgentExit(paneKey: string, endedPresence: AgentProcessPresence): void { - const paneKeys = new Set([this.resolvePaneKeyAlias(paneKey), paneKey]) - for (const [aliasKey, alias] of this.legacyPaneKeyAliases) { - if (alias.stablePaneKey === this.resolvePaneKeyAlias(paneKey)) { - paneKeys.add(aliasKey) - } - } + const paneKeys = this.paneKeysWithAliases(paneKey) const exitedAt = Date.now() const status = this.paneAgentIdentity(paneKey)?.status recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, endedPresence, exitedAt) + this.retirePaneResume(paneKeys, status, exitedAt) + } + + /** A shared server's client left the pane; its conversation lives on there, never resumed here. */ + protected releaseSharedPaneConversation( + paneKey: string, + status: PaneAgentIdentity['status'] + ): void { + this.retirePaneResume(this.paneKeysWithAliases(paneKey), status, Date.now()) + } + + private paneKeysWithAliases(paneKey: string): Set { + const stable = this.resolvePaneKeyAlias(paneKey) + const aliases = [...this.legacyPaneKeyAliases].filter(([, a]) => a.stablePaneKey === stable) + return new Set([stable, paneKey, ...aliases.map(([aliasKey]) => aliasKey)]) + } + + private retirePaneResume( + paneKeys: Set, + status: PaneAgentIdentity['status'] | undefined, + exitedAt: number + ): void { for (const key of paneKeys) { const saved = this.terminalPaneLifecycle?.readSavedRecord?.(key) this.terminalPaneLifecycle?.retireSavedRecord?.(key, exitedAt) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 979f3c81aff4..2d329c6ead1a 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -19,15 +19,16 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { options?: Pick ): void { const identity = this.paneAgentIdentity(paneKey) + const shared = identity?.processTopology === 'shared' const { paneKeys, authorityChanged } = this.revokeProcessAuthority(paneKey) const { untouched } = this.reconcileEndedProcess( paneKeys, - { - ...options, - preserveResumeIdentity: !options?.confirmedExit || identity?.processTopology === 'shared' - }, + { ...options, preserveResumeIdentity: !options?.confirmedExit && !shared }, (key) => this.clearRevokedPaneState(key) ) + if (shared) { + this.releaseSharedPaneConversation(paneKey, identity.status) + } for (const key of untouched) { this.clearTmuxInnerSubjects(key) this.clearPaneProcessState(key) diff --git a/src/main/agent-hooks/server/server-tmux-status.ts b/src/main/agent-hooks/server/server-tmux-status.ts index b36432f05bc0..0ecd457d80f4 100644 --- a/src/main/agent-hooks/server/server-tmux-status.ts +++ b/src/main/agent-hooks/server/server-tmux-status.ts @@ -32,6 +32,8 @@ export abstract class AgentHookServerTmuxStatus extends AgentHookServerOpenCodeB if (this.getAgentStatusDisposition(paneKey) === 'suppress') { return } + // Read before the clear below drops the selected row, the only mark that it's shared. + const identity = this.paneAgentIdentity(paneKey) if (subject && !this.canonicalSubjectsByPane.has(paneKey)) { this.canonicalSubjectsByPane.set( paneKey, @@ -41,6 +43,9 @@ export abstract class AgentHookServerTmuxStatus extends AgentHookServerOpenCodeB } this.clearTmuxSelectedStatus(paneKey, true) this.clearPaneState(paneKey, { preserveTmuxInnerSubjects: true, statusUnavailable: true }) + if (identity?.processTopology === 'shared') { + this.releaseSharedPaneConversation(paneKey, identity.status) + } } }) return this.tmuxOwner diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 44c6bd1cabdb..9e1855de8e99 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -122,7 +122,7 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint prompt: 'In tmux' }) await server.checkAgentPresenceSince(PANE, 0) - const saved: SleepingAgentSessionRecord = { + let saved: SleepingAgentSessionRecord | undefined = { paneKey: PANE, worktreeId: 'wt-1', agent: 'claude', @@ -133,20 +133,23 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint updatedAt: NOW, origin: 'live' } - const retireSavedRecord = vi.fn() server.setTerminalPaneLifecycle({ ownsProcess: () => true, - isStopping: () => false, - isReversibleStop: () => false, + isStopping: () => true, + isReversibleStop: () => true, isPlaced: () => true, readSavedRecord: () => saved, - retireSavedRecord + retireSavedRecord: () => { + saved = undefined + } }) // Detach ends the outer command, while the original agent remains under its server. runningPane(101, ...TMUX) server.retireProcessAuthority(PANE, { confirmedExit: true }) - expect(retireSavedRecord).not.toHaveBeenCalled() + expect(saved).toBeUndefined() expect(server.row()).toBeUndefined() + // The sleep's physical stop must not promote a stale checkpoint into a pane-owned agent. + expect(server.settleTerminalPaneSleep(PANE, 'pty')).toBe(false) const capture = await captureWorktreeSleepResumeRecords({ worktreeId: 'wt-1', paneKeysByPtyId: new Map([['pty', [PANE]]]), @@ -157,5 +160,5 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint checkAgentPresence: (key, since) => server.checkAgentPresenceSince(key, since ?? 0), capturedAt: NOW + 1_000 }) - expect(capture.get('pty')).toEqual({ records: [], retiredPaneKeys: [PANE] }) + expect(capture.get('pty')?.records).toEqual([]) }) diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 0179538b57a7..4bfdfdd2d7fc 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -181,14 +181,14 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O /** `confirmedExit`: the launched command finished at the shell, so its agent ended. */ protected retirePtyAgentLaunchAuthority(ptyId: string, confirmedExit = false): void { + const finishedBefore = this.ptysById.get(ptyId)?.launchEvidence?.kind === 'gone' const pty = this.retireHeldLaunch(ptyId) - if (!pty) { - return - } const receipt = this.restoredOrchestrationAuthorityByPtyId.get(ptyId) - if (!pty.launchToken && !receipt && !pty.launchAgent && !pty.launchCommandAgent) { + const launch = pty && (pty.launchToken || pty.launchAgent || pty.launchCommandAgent) + if (!pty || (!launch && !receipt)) { return } + const exited = confirmedExit && Boolean(launch || (receipt && !finishedBefore)) // Why: collect before the delete below, which drops the restored-authority receipt a // receipt-only pane's key comes from. const paneKeys = this.collectPaneKeysForPty(ptyId) @@ -199,7 +199,7 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O pty.launchAgent = null pty.launchCommandAgent = null for (const paneKey of paneKeys) { - this.retireAgentHookCompatibilityAuthorityFn?.(paneKey, { confirmedExit }) + this.retireAgentHookCompatibilityAuthorityFn?.(paneKey, { confirmedExit: exited }) } if (changed) { void this.refreshAgentSenderAssociations().catch(console.warn) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index b7638d4bd536..5bb7bacd9f81 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -247,7 +247,8 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini ['suspended', ['148'], true], ['macOS suspended', ['146'], true], ['suspended, then another command', ['148', '0'], true], - ['macOS suspended, then another command', ['146', '0'], true] + ['macOS suspended, then another command', ['146', '0'], true], + ['macOS suspended, then a listing and another command', ['146', 'listing', '0'], true] ] as const)('%s', async (_, finishes, keepsRecovery) => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(1_000) @@ -336,6 +337,17 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini tick() if (status === 'unmarked') { await server.reconcilePaneProcessExit(PANE_KEY) + } else if (status === 'listing') { + // An inventory refresh (`orca worktree ps`) re-mints the restored surface's receipt. + const internals = runtime as unknown as { + ptysById: Map + rememberRestoredOrchestrationAuthority(pty: unknown, handle: string, id: string): void + } + internals.rememberRestoredOrchestrationAuthority( + internals.ptysById.get('pty-3'), + 'term-3', + 'pty-3' + ) } else { runtime.onPtyData('pty-3', `\x1b]133;C\x07\x1b]133;D;${status}\x07`, Date.now()) } From d130f34654a948ba6ea1677bb5fbc40c417f1f39 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:19:19 -0800 Subject: [PATCH 034/125] Release tmux-hosted checkpoints after a restart and leave verifiable owners to their own exit After a restart the tmux row is gone until the inner agent hooks again, so a sleep read the saved checkpoint as the pane's own; the pane's tmux client now releases it. A stopped hooked agent's shell foreground no longer clears its live row, since its process answers for its exit. --- .../agent-hooks/server/agent-hook-server.ts | 8 +++- .../server/server-ingest-normalization.ts | 20 +++++++++ .../server-idle-process-owner.test.ts | 18 ++++++++ .../tmux/server-tmux-legacy-sleep.test.ts | 43 +++++++++++++++++++ 4 files changed, 88 insertions(+), 1 deletion(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 190b5398e697..14a2da56ac7e 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -81,6 +81,10 @@ export class AgentHookServer extends AgentHookServerLifecycle { /** Shells without command marks need the owning host's process-tree proof. */ async reconcilePaneProcessExit(paneKey: string): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) + // A verifiable process (e.g. a stopped job) owns its own exit; the quiet shell proves nothing. + if (this.hasVerifiableAgentProcess(resolved)) { + return + } const row = this.state.lastStatusByPaneKey.get(resolved) const identity = this.paneAgentIdentity(resolved) const agent = identity?.status.agentType @@ -88,7 +92,6 @@ export class AgentHookServer extends AgentHookServerLifecycle { identity && agent && identity.processTopology !== 'shared' && - !this.hasVerifiableAgentProcess(resolved) && (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, agent)) if (this.state.lastStatusByPaneKey.get(resolved) !== row) { return @@ -169,6 +172,9 @@ export class AgentHookServer extends AgentHookServerLifecycle { | undefined const binding = row?.providerSession const read = this.readPaneTmuxHost + if (!row) { + return this.releaseTmuxHostedCheckpoint(resolved) + } if ( !read || !row || diff --git a/src/main/agent-hooks/server/server-ingest-normalization.ts b/src/main/agent-hooks/server/server-ingest-normalization.ts index 1d1468308eef..d1efe9d71062 100644 --- a/src/main/agent-hooks/server/server-ingest-normalization.ts +++ b/src/main/agent-hooks/server/server-ingest-normalization.ts @@ -36,6 +36,26 @@ export abstract class AgentHookServerIngestNormalization extends AgentHookServer this.readPaneTmuxHost = tmuxHost } + /** A restart forgets the tmux-selected row; a checkpoint shown through the pane's tmux client was + * never the pane's own process. */ + protected async releaseTmuxHostedCheckpoint(paneKey: string): Promise { + const read = this.readPaneTmuxHost + const identity = read && !this.getTmuxSelectedStatus(paneKey) && this.paneAgentIdentity(paneKey) + if ( + !read || + !identity || + identity.ended || + identity.status.connectionId !== null || + !identity.status.worktreeId || + !(await read({ paneKey, worktreeId: identity.status.worktreeId }).catch(() => false)) || + this.state.lastStatusByPaneKey.has(paneKey) || + this.getTmuxSelectedStatus(paneKey) + ) { + return + } + this.releaseSharedPaneConversation(paneKey, identity.status) + } + /** Panes whose owner an undecided hook challenged: until that hook is admitted or refused, the * owner's exit neither answers for the pane nor is forgotten. */ protected readonly undecidedOwnerChallenges = new Map() diff --git a/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts index 4e542c8b617c..10473861f864 100644 --- a/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts @@ -266,6 +266,24 @@ describe('idle foreground process owns its provider session', () => { }) }) + it('keeps a verifiable owner when its shell takes the foreground', async () => { + const server = await start() + await idleClaude(server) + const before = server.getStatusSnapshot() + const confirmProcessExit = vi.fn(async () => true) + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => false, + isPlaced: () => true, + confirmProcessExit + }) + // Ctrl-Z returns the shell; the stopped process still answers for itself. + await server.reconcilePaneProcessExit(PANE) + expect(server.getStatusSnapshot()).toEqual(before) + expect(confirmProcessExit).not.toHaveBeenCalled() + }) + it.each(['live', 'unverifiable'] as const)( 'retains mobile and resume selection after turn completion when owner is %s', async (verdict) => { diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 9e1855de8e99..5af49e8f47b2 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -162,3 +162,46 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint }) expect(capture.get('pty')?.records).toEqual([]) }) + +it('does not resume a checkpoint the pane reaches through its tmux client after a restart', async () => { + // A restart forgot the tmux row; the client still shows the agent before it hooks again. + const server = await createServer() + server.setHookRootEvidenceReader( + (request) => readHookRootEvidence(request, io), + (request) => readPaneTmuxHost(io, request) + ) + runningPane(4050, CLIENT, ...TMUX) + let saved: SleepingAgentSessionRecord | undefined = { + paneKey: PANE, + worktreeId: 'wt-1', + agent: 'claude', + providerSession: { key: 'session_id', id: 'restarted-session' }, + prompt: 'In tmux', + state: 'done', + capturedAt: NOW, + updatedAt: NOW, + origin: 'live' + } + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => true, + isPlaced: () => true, + readSavedRecord: () => saved, + retireSavedRecord: () => { + saved = undefined + } + }) + const capture = await captureWorktreeSleepResumeRecords({ + worktreeId: 'wt-1', + paneKeysByPtyId: new Map([['pty', [PANE]]]), + launchByPtyId: new Map(), + readRowsForPane: (key) => server.getStatusSnapshotForPane(key), + readSavedRecord: async () => saved, + readIdentity: (key, record) => server.paneAgentIdentity(key, record), + checkAgentPresence: (key, since) => server.checkAgentPresenceSince(key, since ?? 0), + capturedAt: NOW + 1_000 + }) + expect(saved).toBeUndefined() + expect(capture.get('pty')?.records).toEqual([]) +}) From 7443f5eb6e8fe2c3bc2e39caf8b6fa3ea518cc49 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:25:29 -0800 Subject: [PATCH 035/125] Prove unmarked exits with the host's shell-alone check and retire shared and SSH recovery on every path The daemon's child check reads the foreground name, so a stopped hookless agent looked exited; the host's shell-alone proof rejects stopped jobs, and an unknown (reattached) launch may use it while a gone launch stays refused. The unmarked-exit path releases a shared conversation's checkpoint like the other two. Retirements pinned to the pane's exact record or turn clear SSH claims too. Pane clears look up their one remembered status instead of scanning all of them. --- .../agent-hooks/server/agent-hook-server.ts | 31 -------------- .../agent-hooks/server/server-tab-cleanup.ts | 35 ++++++++++++++++ .../tmux/server-tmux-legacy-sleep.test.ts | 4 +- .../terminal-pane-status-lifecycle.test.ts | 21 ++++------ .../pane/terminal-pane-status-lifecycle.ts | 16 +++----- .../stop/worktree-sleep-resume-recording.ts | 40 ++++++++++-------- ...connection-process-exit-row-retire.test.ts | 6 +-- ...status-listeners-resume-retirement.test.ts | 17 +++++--- .../ipc-events/agent-status-listeners.ts | 4 +- .../resume/forget-refused-pane-resume.ts | 41 +++++++++++-------- 10 files changed, 114 insertions(+), 101 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 14a2da56ac7e..48ca1e419a70 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -71,37 +71,6 @@ export class AgentHookServer extends AgentHookServerLifecycle { // A live sender means the owner's exit cannot establish pane exit. private readonly ownerChallengesByLiveSender = new Map() - hasVerifiableAgentProcess(paneKey: string): boolean { - const presence = this.state.lastStatusByPaneKey.get( - this.resolvePaneKeyAlias(paneKey) - )?.agentPresence - return presence?.process !== undefined && !presence.ended - } - - /** Shells without command marks need the owning host's process-tree proof. */ - async reconcilePaneProcessExit(paneKey: string): Promise { - const resolved = this.resolvePaneKeyAlias(paneKey) - // A verifiable process (e.g. a stopped job) owns its own exit; the quiet shell proves nothing. - if (this.hasVerifiableAgentProcess(resolved)) { - return - } - const row = this.state.lastStatusByPaneKey.get(resolved) - const identity = this.paneAgentIdentity(resolved) - const agent = identity?.status.agentType - const confirmedExit = - identity && - agent && - identity.processTopology !== 'shared' && - (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, agent)) - if (this.state.lastStatusByPaneKey.get(resolved) !== row) { - return - } - this.reconcileEndedProcessForPaneKeys([resolved], { - preserveResumeIdentity: true, - confirmedExit: confirmedExit === true - }) - } - /** Pin inspection to this row so a replacement owner cannot become its subject. */ readCliWriterObservation(expected: AgentStatusIpcPayload): CliWriterObservation | null { const resolved = this.resolvePaneKeyAlias(expected.paneKey) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 2d329c6ead1a..9608681b616b 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -39,6 +39,41 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } } + hasVerifiableAgentProcess(paneKey: string): boolean { + const presence = this.state.lastStatusByPaneKey.get( + this.resolvePaneKeyAlias(paneKey) + )?.agentPresence + return presence?.process !== undefined && !presence.ended + } + + /** Shells without command marks need the owning host's process-tree proof. */ + async reconcilePaneProcessExit(paneKey: string): Promise { + const resolved = this.resolvePaneKeyAlias(paneKey) + // A verifiable process (e.g. a stopped job) owns its own exit; the quiet shell proves nothing. + if (this.hasVerifiableAgentProcess(resolved)) { + return + } + const row = this.state.lastStatusByPaneKey.get(resolved) + const identity = this.paneAgentIdentity(resolved) + const agent = identity?.status.agentType + const shared = identity?.processTopology === 'shared' + const confirmedExit = + identity && + agent && + !shared && + (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, agent)) + if (this.state.lastStatusByPaneKey.get(resolved) !== row) { + return + } + this.reconcileEndedProcessForPaneKeys([resolved], { + preserveResumeIdentity: true, + confirmedExit: confirmedExit === true + }) + if (shared) { + this.releaseSharedPaneConversation(resolved, identity.status) + } + } + dropPersistedStatusEntry(identity: AgentStatusCacheIdentity): boolean { return this.dropPersistedStatusEntries([identity]).length > 0 } diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 5af49e8f47b2..e9ff439531b5 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -133,9 +133,10 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint updatedAt: NOW, origin: 'live' } + let stopping = false server.setTerminalPaneLifecycle({ ownsProcess: () => true, - isStopping: () => true, + isStopping: () => stopping, isReversibleStop: () => true, isPlaced: () => true, readSavedRecord: () => saved, @@ -149,6 +150,7 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint expect(saved).toBeUndefined() expect(server.row()).toBeUndefined() // The sleep's physical stop must not promote a stale checkpoint into a pane-owned agent. + stopping = true expect(server.settleTerminalPaneSleep(PANE, 'pty')).toBe(false) const capture = await captureWorktreeSleepResumeRecords({ worktreeId: 'wt-1', diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index f1570d0e01c8..d276859b9bd9 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -13,25 +13,22 @@ vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ vi.mock('../provider/registry', () => ({ getProviderForPty })) it.each([ - ['quit at cmd', false, 'cmd.exe', true, false, true], - ['quit at Git Bash', false, 'bash', true, false, true], - ['stopped child', true, 'bash', true, false, false], - ['agent foreground', false, 'codex', true, false, false], - ['unanswered shell', false, null, true, false, false], - ['intervening command revoked launch', false, 'bash', false, false, false], - ['successor launch during inspection', false, 'cmd.exe', true, true, false] + ['shell alone after the launched agent quit', true, 'held', false, true], + ['shell alone after a reattach left the launch unknown', true, 'unknown', false, true], + ['no shell-alone proof (stopped job, agent foreground, unanswered)', false, 'held', false, false], + ['intervening command retired the launch', true, 'gone', false, false], + ['successor launch during inspection', true, 'held', true, false] ] as const)( 'proves an unmarked process exit only for the current launch: %s', - async (_, children, foreground, held, replaced, expected) => { + async (_, shellAlone, evidence, replaced, expected) => { const launch = { agentArgs: '', agentEnv: {} } - let currentLaunch = held ? launch : null + let currentLaunch = evidence === 'held' ? launch : evidence === 'gone' ? null : undefined getProviderForPty.mockReturnValue({ - hasChildProcesses: async () => children, - confirmForegroundProcess: async () => { + confirmShellForeground: async () => { if (replaced) { currentLaunch = { agentArgs: '--resume next', agentEnv: {} } } - return foreground + return shellAlone } }) // SAFETY: This binding's exit probe only reads these two runtime capabilities. diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index de6e688a2ca4..fa8a24580dfc 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -8,7 +8,6 @@ import { paneKeyPtyId } from './key-state' import { ptyIncarnationById } from '../provider/ownership-state' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { getProviderForPty } from '../provider/registry' -import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import { isRemoteExecutionHostPtyId } from '../../../../shared/execution-host/remote-execution-host-pty-id' export function bindTerminalPaneStatusLifecycle( @@ -24,20 +23,15 @@ export function bindTerminalPaneStatusLifecycle( try { const pane = runtime.resolveTerminalPane(paneKey) const launch = runtime.getLaunchStatementForPaneKey(paneKey, agent) - // A finished/intervening command has already revoked this launch's authority. - if (!pane.ptyId || isRemoteExecutionHostPtyId(pane.ptyId) || !launch) { + // A finished command already retired a gone launch; an unknown one (reattach) needs the proof. + if (!pane.ptyId || isRemoteExecutionHostPtyId(pane.ptyId) || launch === null) { return false } - const provider = getProviderForPty(pane.ptyId) - const [children, foreground] = await Promise.all([ - provider.hasChildProcesses(pane.ptyId), - provider.confirmForegroundProcess?.(pane.ptyId) - ]) + // Host proof: the shell alone holds the PTY, with no stopped job behind it. + const shellAlone = await getProviderForPty(pane.ptyId).confirmShellForeground?.(pane.ptyId) const current = runtime.resolveTerminalPane(paneKey) return ( - children === false && - typeof foreground === 'string' && - isShellProcess(foreground) && + shellAlone === true && current.ptyId === pane.ptyId && current.incarnationId === pane.incarnationId && runtime.getLaunchStatementForPaneKey(paneKey, agent) === launch diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 2b4e2e7f6583..09c528bed26b 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -191,24 +191,30 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu /** A cleared status leaves the record alone (lost contact is no evidence), as in the window. */ forgetHookStatusResume(clear: AgentStatusClearIpcPayload): void { - for (const [paneKey, status] of this.previousHookStatusByPaneKey) { - if ( - 'paneKey' in clear - ? paneKey === clear.paneKey && - (!clear.refusedResume || - (!!clear.refusedResume.expectedStatus && - status.updatedAt <= clear.refusedResume.expectedStatus.receivedAt && - status.stateStartedAt === clear.refusedResume.expectedStatus.stateStartedAt && - status.agentType === clear.refusedResume.agent && - agentProviderSessionsEqual( - status.agentType, - status.providerSession, - clear.refusedResume.providerSession - ))) - : status.connectionId === clear.connectionId - ) { - this.previousHookStatusByPaneKey.delete(paneKey) + if (!('paneKey' in clear)) { + for (const [paneKey, status] of this.previousHookStatusByPaneKey) { + if (status.connectionId === clear.connectionId) { + this.previousHookStatusByPaneKey.delete(paneKey) + } } + return + } + const status = this.previousHookStatusByPaneKey.get(clear.paneKey) + const refused = clear.refusedResume + if ( + status && + (!refused || + (!!refused.expectedStatus && + status.updatedAt <= refused.expectedStatus.receivedAt && + status.stateStartedAt === refused.expectedStatus.stateStartedAt && + status.agentType === refused.agent && + agentProviderSessionsEqual( + status.agentType, + status.providerSession, + refused.providerSession + ))) + ) { + this.previousHookStatusByPaneKey.delete(clear.paneKey) } } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts index 4228f2c4f82c..ff780ce8022b 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts @@ -185,7 +185,7 @@ async function connectAgentPane(args: { async function seedHookRow( paneKey: string, - agentType: 'claude' | 'codex' | 'gemini' | 'opencode', + agentType: 'claude' | 'codex', state: 'working' | 'done' = 'done' ): Promise { // Why the real slice: the row must carry the acceptedStatusSeq a real accepted hook stamps. @@ -252,8 +252,8 @@ describe('connectPanePty confirmed process exit retires the live agent row', () ) }) - it.each(['claude', 'codex', 'gemini', 'opencode'] as const)( - 'retires %s recovery and row after a process exit without command marks', + it.each(['codex'] as const)( + 'asks main to retire %s recovery after a process exit without command marks', async (agent) => { let foreground: string | null = agent let children = true diff --git a/src/renderer/src/hooks/ipc-events/agent-status-listeners-resume-retirement.test.ts b/src/renderer/src/hooks/ipc-events/agent-status-listeners-resume-retirement.test.ts index b88faf085103..4021b1c05edc 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status-listeners-resume-retirement.test.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status-listeners-resume-retirement.test.ts @@ -14,9 +14,13 @@ vi.mock('@/store/index', () => ({ useAppStore: { getState: (): AppState => store afterEach(() => vi.unstubAllGlobals()) -it.each(['live', 'quit'] as const)( - 'keeps a retired %s record out of the next window save, including queued status', - (origin) => { +it.each([ + ['live', null], + ['quit', null], + ['live', 'ssh-1'] +] as const)( + 'keeps a retired %s record (connection %s) out of the next window save, including queued status', + (origin, connectionId) => { store = createTestStore() const paneKey = 'tab-1:11111111-1111-4111-8111-111111111111' store.setState({ @@ -30,7 +34,8 @@ it.each(['live', 'quit'] as const)( state: 'done', capturedAt: 250, updatedAt: 200, - origin + origin, + connectionId }, 'other-pane': { paneKey: 'other-pane', @@ -66,7 +71,7 @@ it.each(['live', 'quit'] as const)( state: 'done', prompt: '', providerSession: { key: 'session_id', id: 'quit-codex' }, - connectionId: null, + connectionId, receivedAt: 200, stateStartedAt: 150 } @@ -88,7 +93,7 @@ it.each(['live', 'quit'] as const)( agent: 'codex', providerSession: { key: 'session_id', id: 'quit-codex' }, expectedStatus: { paneKey, receivedAt: 200, stateStartedAt: 150 }, - expectedSavedRecord: { paneKey, capturedAt: 200, updatedAt: 200 } + expectedSavedRecord: { paneKey, capturedAt: 250, updatedAt: 200 } } }) const saved = buildSleepingAgentSessionData(store.getState()).sleepingAgentSessionsByPaneKey diff --git a/src/renderer/src/hooks/ipc-events/agent-status-listeners.ts b/src/renderer/src/hooks/ipc-events/agent-status-listeners.ts index e70da85f7d87..a5f53ee79d03 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status-listeners.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status-listeners.ts @@ -6,7 +6,7 @@ import { import { useAppStore } from '../../store/index' import { forgetRefusedPaneResume, - namesRefusedResume + namesConversation } from '@/lib/agent-session/resume/forget-refused-pane-resume' import { resolveAgentPaneAuthorityKey } from '@/store/slices/agent-status/agent-pane-authority' import { resolvePaneKey } from '../../lib/agent-status/ownership/agent-status-pane-ownership' @@ -31,7 +31,7 @@ function dropEventsRestoringRefused( event.receivedAt <= refused.expectedStatus.receivedAt && event.stateStartedAt === refused.expectedStatus.stateStartedAt && resolveAgentPaneAuthorityKey(event.paneKey) === paneKey && - namesRefusedResume(refused, { ...event, agent: event.agentType }) + namesConversation(refused, { ...event, agent: event.agentType }) const pending = queues.pendingAgentStatusEvents for (let index = pending.length - 1; index >= 0; index -= 1) { if (restores(pending[index].data)) { diff --git a/src/renderer/src/lib/agent-session/resume/forget-refused-pane-resume.ts b/src/renderer/src/lib/agent-session/resume/forget-refused-pane-resume.ts index 07eb529e74eb..18cc6618e5c0 100644 --- a/src/renderer/src/lib/agent-session/resume/forget-refused-pane-resume.ts +++ b/src/renderer/src/lib/agent-session/resume/forget-refused-pane-resume.ts @@ -4,23 +4,26 @@ import type { AgentProviderSessionMetadata } from '../../../../../shared/agent-s import type { AppState } from '@/store/types' import type { RefusedPaneResume } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' -/** Whether a saved claim names the refused conversation. Only local claims can: the host judged - * its own chats, and a remote host's same id is a different conversation. */ -export function namesRefusedResume( - refused: RefusedPaneResume, - claim: { - agent?: string - providerSession?: AgentProviderSessionMetadata - connectionId?: string | null - } -): boolean { +type ResumeClaim = { + agent?: string + providerSession?: AgentProviderSessionMetadata + connectionId?: string | null +} + +/** For claims pinned to the pane's exact record or turn, which host it names doesn't matter. */ +export function namesConversation(refused: RefusedPaneResume, claim: ResumeClaim): boolean { return ( - !claim.connectionId && claim.agent === refused.agent && agentProviderSessionsEqual(refused.agent, claim.providerSession, refused.providerSession) ) } +/** Whether a saved claim names the refused conversation. Only local claims can: the host judged + * its own chats, and a remote host's same id is a different conversation. */ +function namesRefusedResume(refused: RefusedPaneResume, claim: ResumeClaim): boolean { + return !claim.connectionId && namesConversation(refused, claim) +} + /** Forget the host-retired conversation even in unmounted panes; newer observations survive. */ export function forgetRefusedPaneResume( state: AppState, @@ -30,14 +33,16 @@ export function forgetRefusedPaneResume( const expected = refused.expectedSavedRecord const savedKey = expected?.paneKey ?? paneKey const saved = state.sleepingAgentSessionsByPaneKey[savedKey] + const exact = + expected && saved?.capturedAt === expected.capturedAt && saved.updatedAt === expected.updatedAt if ( saved && - ((expected && - saved.capturedAt === expected.capturedAt && - saved.updatedAt === expected.updatedAt) || - // Main and window may capture the same accepted status at different times. - (refused.expectedStatus && saved.updatedAt <= refused.expectedStatus.receivedAt)) && - namesRefusedResume(refused, saved) + (exact + ? namesConversation(refused, saved) + : // Main and window may capture the same accepted status at different times. + refused.expectedStatus && + saved.updatedAt <= refused.expectedStatus.receivedAt && + namesRefusedResume(refused, saved)) ) { state.clearSleepingAgentSession(savedKey) } @@ -51,7 +56,7 @@ export function forgetRefusedPaneResume( !live || live.updatedAt > identity.receivedAt || live.stateStartedAt !== identity.stateStartedAt || - !namesRefusedResume(refused, { ...live, agent: live.agentType }) + !namesConversation(refused, { ...live, agent: live.agentType }) ) { return current } From e767c7faa1c14f8a51022ef00a9b2283253df34a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:34:06 -0800 Subject: [PATCH 036/125] Let a verifiable owner's presence probe answer a quiet shell A hooked agent that quit without a session end kept its live row on main until something probed it; the shell's foreground now triggers that probe, which retires an exited owner and keeps a stopped one. --- .../agent-hooks/server/server-tab-cleanup.ts | 6 ++- .../server-idle-process-owner.test.ts | 40 +++++++++++-------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 9608681b616b..d865ded30279 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -6,6 +6,7 @@ import { paneCacheKeyMatchesTab } from './server-status-identity' import { AgentHookServerCleanup, type EndedProcessReconciliationOptions } from './server-cleanup' import type { EnrichedAgentHookEventPayload } from './server-types' import { releaseAgentExitKey } from './agent-exit-evidence' +import type { AgentProcessVerdict } from '../../../shared/agent-status/process/agent-process-presence' import { paneHasStateClaims } from '../../../shared/agent-hook-listener/pane-state-claims' import type { AgentStatusCacheIdentity, @@ -14,6 +15,8 @@ import type { import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { + abstract checkAgentPresence(paneKey: string): Promise + retireProcessAuthority( paneKey: string, options?: Pick @@ -49,8 +52,9 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { /** Shells without command marks need the owning host's process-tree proof. */ async reconcilePaneProcessExit(paneKey: string): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) - // A verifiable process (e.g. a stopped job) owns its own exit; the quiet shell proves nothing. + // A verifiable process answers for itself (exited, stopped or live); the quiet shell proves nothing. if (this.hasVerifiableAgentProcess(resolved)) { + await this.checkAgentPresence(resolved) return } const row = this.state.lastStatusByPaneKey.get(resolved) diff --git a/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts index 10473861f864..354c5c7d1466 100644 --- a/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts @@ -266,23 +266,29 @@ describe('idle foreground process owns its provider session', () => { }) }) - it('keeps a verifiable owner when its shell takes the foreground', async () => { - const server = await start() - await idleClaude(server) - const before = server.getStatusSnapshot() - const confirmProcessExit = vi.fn(async () => true) - server.setTerminalPaneLifecycle({ - ownsProcess: () => true, - isStopping: () => false, - isReversibleStop: () => false, - isPlaced: () => true, - confirmProcessExit - }) - // Ctrl-Z returns the shell; the stopped process still answers for itself. - await server.reconcilePaneProcessExit(PANE) - expect(server.getStatusSnapshot()).toEqual(before) - expect(confirmProcessExit).not.toHaveBeenCalled() - }) + it.each([ + ['stopped', 'unverifiable', true], + ['still running', 'live', true], + ['exited without a session end', 'exited', false] + ] as const)( + 'lets a verifiable owner answer when its shell takes the foreground: %s', + async (_, verdict, keepsOwner) => { + const server = await start() + await idleClaude(server) + const confirmProcessExit = vi.fn(async () => true) + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => false, + isPlaced: () => true, + confirmProcessExit + }) + probe.mockResolvedValue(verdict) + await server.reconcilePaneProcessExit(PANE) + expect(server.hasVerifiableAgentProcess(PANE)).toBe(keepsOwner) + expect(confirmProcessExit).not.toHaveBeenCalled() + } + ) it.each(['live', 'unverifiable'] as const)( 'retains mobile and resume selection after turn completion when owner is %s', From de0164b11526414d847ed10ab576ffd760e05ae5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:37:59 -0800 Subject: [PATCH 037/125] Keep Windows unmarked quits provable and probe tmux-shown checkpoints only at sleep capture The daemon's shell proof follows prompt marks that cmd and Git Bash often lack; Windows shells stop no jobs, so a childless shell foreground suffices there. The rowless tmux checkpoint probe ran on every fleet presence read; only a sleep capture asks for it now. --- .../runtime/agent-hook-runtime-deps.ts | 4 +- .../agent-hooks/server/agent-hook-server.ts | 9 +++-- .../tmux/server-tmux-legacy-sleep.test.ts | 3 +- .../terminal-pane-status-lifecycle.test.ts | 40 +++++++++++++++---- .../pane/terminal-pane-status-lifecycle.ts | 22 +++++++++- .../runtime-construction-dependencies.ts | 4 +- .../stop/worktree-sleep-resume-recording.ts | 4 +- 7 files changed, 67 insertions(+), 19 deletions(-) diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index 6b90d687ab5a..075e5167f275 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -79,10 +79,10 @@ export function agentHookRuntimeDeps( readChildWorkHandles: (subject) => server.getStructuredChildWorkHandles(subject) }, readHookCliWriterObservation: (row) => server.readCliWriterObservation(row), - checkHookAgentPresence: (paneKey, exitedSince) => + checkHookAgentPresence: (paneKey, exitedSince, options) => exitedSince === undefined ? server.checkAgentPresence(paneKey) - : server.checkAgentPresenceSince(paneKey, exitedSince), + : server.checkAgentPresenceSince(paneKey, exitedSince, options), reconcileAgentStatusForEndedProcess: (paneKeys, sleep) => { const keys = [...paneKeys] if (sleep) { diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 48ca1e419a70..50f4ecc8d7f5 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -110,11 +110,12 @@ export class AgentHookServer extends AgentHookServerLifecycle { /** Include retained exits proven at or after `exitedSince`. */ async checkAgentPresenceSince( paneKey: string, - exitedSince: number + exitedSince: number, + options?: { sleepCapture?: true } ): Promise { const [verdict] = await Promise.all([ this.checkAgentPresence(paneKey), - this.observeTmuxHostedWriter(paneKey) + this.observeTmuxHostedWriter(paneKey, options?.sleepCapture === true) ]) // A replaced owner's probe result counts only if its exit was retained. if (verdict !== null && verdict !== 'exited') { @@ -133,7 +134,7 @@ export class AgentHookServer extends AgentHookServerLifecycle { /** Legacy hooks cannot say a tmux server hosts them; the pane's foreground client can, before * a sleep or adoption captures the conversation as the pane's own. */ - private async observeTmuxHostedWriter(paneKey: string): Promise { + private async observeTmuxHostedWriter(paneKey: string, sleepCapture: boolean): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: main stores enriched accepted rows in the base-typed cache. const row = this.state.lastStatusByPaneKey.get(resolved) as @@ -142,7 +143,7 @@ export class AgentHookServer extends AgentHookServerLifecycle { const binding = row?.providerSession const read = this.readPaneTmuxHost if (!row) { - return this.releaseTmuxHostedCheckpoint(resolved) + return sleepCapture ? this.releaseTmuxHostedCheckpoint(resolved) : undefined } if ( !read || diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index e9ff439531b5..8bcc2a4c8d38 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -201,7 +201,8 @@ it('does not resume a checkpoint the pane reaches through its tmux client after readRowsForPane: (key) => server.getStatusSnapshotForPane(key), readSavedRecord: async () => saved, readIdentity: (key, record) => server.paneAgentIdentity(key, record), - checkAgentPresence: (key, since) => server.checkAgentPresenceSince(key, since ?? 0), + checkAgentPresence: (key, since) => + server.checkAgentPresenceSince(key, since ?? 0, { sleepCapture: true }), capturedAt: NOW + 1_000 }) expect(saved).toBeUndefined() diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index d276859b9bd9..26d9351096d4 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -1,4 +1,4 @@ -import { expect, it, vi } from 'vitest' +import { afterEach, expect, it, vi } from 'vitest' import type { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { bindTerminalPaneStatusLifecycle } from './terminal-pane-status-lifecycle' @@ -12,15 +12,37 @@ vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ })) vi.mock('../provider/registry', () => ({ getProviderForPty })) +const platform = process.platform +afterEach(() => Object.defineProperty(process, 'platform', { value: platform })) + it.each([ - ['shell alone after the launched agent quit', true, 'held', false, true], - ['shell alone after a reattach left the launch unknown', true, 'unknown', false, true], - ['no shell-alone proof (stopped job, agent foreground, unanswered)', false, 'held', false, false], - ['intervening command retired the launch', true, 'gone', false, false], - ['successor launch during inspection', true, 'held', true, false] + ['shell alone after the launched agent quit', 'darwin', true, 'zsh', 'held', false, true], + [ + 'shell alone after a reattach left the launch unknown', + 'darwin', + true, + 'zsh', + 'unknown', + false, + true + ], + [ + 'no shell-alone proof (stopped job, agent foreground)', + 'darwin', + false, + 'zsh', + 'held', + false, + false + ], + ['intervening command retired the launch', 'darwin', true, 'zsh', 'gone', false, false], + ['successor launch during inspection', 'darwin', true, 'zsh', 'held', true, false], + ['unmarked cmd.exe back alone on Windows', 'win32', false, 'cmd.exe', 'held', false, true], + ['agent still foreground on Windows', 'win32', false, 'codex.exe', 'held', false, false] ] as const)( 'proves an unmarked process exit only for the current launch: %s', - async (_, shellAlone, evidence, replaced, expected) => { + async (_, os, shellAlone, foreground, evidence, replaced, expected) => { + Object.defineProperty(process, 'platform', { value: os }) const launch = { agentArgs: '', agentEnv: {} } let currentLaunch = evidence === 'held' ? launch : evidence === 'gone' ? null : undefined getProviderForPty.mockReturnValue({ @@ -29,7 +51,9 @@ it.each([ currentLaunch = { agentArgs: '--resume next', agentEnv: {} } } return shellAlone - } + }, + hasChildProcesses: async () => foreground !== 'cmd.exe', + confirmForegroundProcess: async () => foreground }) // SAFETY: This binding's exit probe only reads these two runtime capabilities. const runtime = { diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index fa8a24580dfc..fe3090b7ae56 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -8,6 +8,7 @@ import { paneKeyPtyId } from './key-state' import { ptyIncarnationById } from '../provider/ownership-state' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { getProviderForPty } from '../provider/registry' +import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import { isRemoteExecutionHostPtyId } from '../../../../shared/execution-host/remote-execution-host-pty-id' export function bindTerminalPaneStatusLifecycle( @@ -27,8 +28,7 @@ export function bindTerminalPaneStatusLifecycle( if (!pane.ptyId || isRemoteExecutionHostPtyId(pane.ptyId) || launch === null) { return false } - // Host proof: the shell alone holds the PTY, with no stopped job behind it. - const shellAlone = await getProviderForPty(pane.ptyId).confirmShellForeground?.(pane.ptyId) + const shellAlone = await confirmShellAlone(pane.ptyId) const current = runtime.resolveTerminalPane(paneKey) return ( shellAlone === true && @@ -108,3 +108,21 @@ export function bindTerminalPaneStatusLifecycle( }) agentHookServer.pruneUnplacedSleepingPanes() } + +/** The shell alone holds the PTY, with no stopped job behind it. The daemon's proof needs prompt + * marks, which cmd and Git Bash often lack; Windows shells stop no jobs, so their quiet foreground + * and childless tree suffice there. */ +async function confirmShellAlone(ptyId: string): Promise { + const provider = getProviderForPty(ptyId) + if ((await provider.confirmShellForeground?.(ptyId)) === true) { + return true + } + if (process.platform !== 'win32') { + return false + } + const [children, foreground] = await Promise.all([ + provider.hasChildProcesses(ptyId), + provider.confirmForegroundProcess?.(ptyId) + ]) + return children === false && typeof foreground === 'string' && isShellProcess(foreground) +} diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index c6dff2661269..391368f08928 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -78,7 +78,9 @@ export type RuntimeConstructionDependencies = { /** `exitedSince`: also answer `exited` for an exit the hook store proved at or after it. */ checkHookAgentPresence?: ( paneKey: string, - exitedSince?: number + exitedSince?: number, + /** A sleep capture also releases checkpoints a tmux client shows; other reads skip that probe. */ + options?: { sleepCapture?: true } ) => Promise<'live' | 'unverifiable' | 'exited' | null> reconcileAgentStatusForEndedProcess?: ( paneKeys: Iterable, diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 09c528bed26b..6ea15f13ba40 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -131,7 +131,9 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu readRowsForPane: (paneKey) => this.getAgentProviderSessionRowsForPaneFn?.(paneKey) ?? [], readSavedRecord: (paneKey) => this.readSavedResumeSource(worktreeId, paneKey), readIdentity: (paneKey, savedRecord) => this.readPaneAgentIdentity(paneKey, savedRecord), - checkAgentPresence: this.checkHookAgentPresenceFn, + checkAgentPresence: (paneKey, since) => + this.checkHookAgentPresenceFn?.(paneKey, since, { sleepCapture: true }) ?? + Promise.resolve(null), capturedAt: Date.now() }) }, From 611e3b5479b08e9d4fe1156a3d768e88f60d2e05 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:42:58 -0800 Subject: [PATCH 038/125] Prove Windows unmarked quits from the host's job census The Windows fallback read the same agent-name signal that asked for the proof; a decision-time inspection's child census is independent evidence. Ordinary presence reads now provably skip the sleep-capture tmux probe. --- .../tmux/server-tmux-legacy-sleep.test.ts | 3 +++ .../terminal-pane-status-lifecycle.test.ts | 8 +++++-- .../pane/terminal-pane-status-lifecycle.ts | 23 +++++++++++-------- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 8bcc2a4c8d38..f1de2bb7d0f5 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -194,6 +194,9 @@ it('does not resume a checkpoint the pane reaches through its tmux client after saved = undefined } }) + // Ordinary presence reads (fleet status) don't pay for the tmux probe. + await server.checkAgentPresenceSince(PANE, 0) + expect(saved).toBeDefined() const capture = await captureWorktreeSleepResumeRecords({ worktreeId: 'wt-1', paneKeysByPtyId: new Map([['pty', [PANE]]]), diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index 26d9351096d4..c336712e143d 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -52,8 +52,12 @@ it.each([ } return shellAlone }, - hasChildProcesses: async () => foreground !== 'cmd.exe', - confirmForegroundProcess: async () => foreground + // Windows answers from its job census; a scan that names no agent is not that census. + inspectProcess: async () => ({ + foregroundProcess: foreground, + hasChildProcesses: foreground !== 'cmd.exe', + childProcessEvidence: foreground === 'cmd.exe' ? 'no-children' : 'children' + }) }) // SAFETY: This binding's exit probe only reads these two runtime capabilities. const runtime = { diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index fe3090b7ae56..9fd2a8fccbd1 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -8,6 +8,7 @@ import { paneKeyPtyId } from './key-state' import { ptyIncarnationById } from '../provider/ownership-state' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { getProviderForPty } from '../provider/registry' +import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import { isRemoteExecutionHostPtyId } from '../../../../shared/execution-host/remote-execution-host-pty-id' @@ -28,7 +29,7 @@ export function bindTerminalPaneStatusLifecycle( if (!pane.ptyId || isRemoteExecutionHostPtyId(pane.ptyId) || launch === null) { return false } - const shellAlone = await confirmShellAlone(pane.ptyId) + const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined) const current = runtime.resolveTerminalPane(paneKey) return ( shellAlone === true && @@ -110,9 +111,9 @@ export function bindTerminalPaneStatusLifecycle( } /** The shell alone holds the PTY, with no stopped job behind it. The daemon's proof needs prompt - * marks, which cmd and Git Bash often lack; Windows shells stop no jobs, so their quiet foreground - * and childless tree suffice there. */ -async function confirmShellAlone(ptyId: string): Promise { + * marks, which cmd and Git Bash often lack; Windows shells stop no jobs, so the host's job census + * finding no child beside a shell foreground suffices there. */ +async function confirmShellAlone(ptyId: string, incarnationId?: string): Promise { const provider = getProviderForPty(ptyId) if ((await provider.confirmShellForeground?.(ptyId)) === true) { return true @@ -120,9 +121,13 @@ async function confirmShellAlone(ptyId: string): Promise { if (process.platform !== 'win32') { return false } - const [children, foreground] = await Promise.all([ - provider.hasChildProcesses(ptyId), - provider.confirmForegroundProcess?.(ptyId) - ]) - return children === false && typeof foreground === 'string' && isShellProcess(foreground) + const inspection = await inspectPtyProviderProcess(provider, ptyId, { + scanChildProcesses: true, + ...(incarnationId ? { expectedIncarnationId: incarnationId } : {}) + }) + return ( + inspection.childProcessEvidence === 'no-children' && + typeof inspection.foregroundProcess === 'string' && + isShellProcess(inspection.foregroundProcess) + ) } From fe98eeddd3f794ffb4ce9dd9b1ad86aee4eb3672 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:47:46 -0800 Subject: [PATCH 039/125] Pin the Windows exit proof to an explicit child census Per the council ruling (A): an older daemon's answer without a census, or a census that still finds a child, never proves the agent ended. --- .../terminal-pane-status-lifecycle.test.ts | 66 ++++++++++++++++--- .../pane/terminal-pane-status-lifecycle.ts | 3 +- 2 files changed, 59 insertions(+), 10 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index c336712e143d..50a494fc8d38 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -16,12 +16,22 @@ const platform = process.platform afterEach(() => Object.defineProperty(process, 'platform', { value: platform })) it.each([ - ['shell alone after the launched agent quit', 'darwin', true, 'zsh', 'held', false, true], + [ + 'shell alone after the launched agent quit', + 'darwin', + true, + 'zsh', + undefined, + 'held', + false, + true + ], [ 'shell alone after a reattach left the launch unknown', 'darwin', true, 'zsh', + undefined, 'unknown', false, true @@ -31,17 +41,55 @@ it.each([ 'darwin', false, 'zsh', + 'no-children', + 'held', + false, + false + ], + [ + 'intervening command retired the launch', + 'darwin', + true, + 'zsh', + undefined, + 'gone', + false, + false + ], + ['successor launch during inspection', 'darwin', true, 'zsh', undefined, 'held', true, false], + [ + 'unmarked cmd.exe back alone in its job on Windows', + 'win32', + false, + 'cmd.exe', + 'no-children', + 'held', + false, + true + ], + [ + 'unnamed agent still in the job on Windows', + 'win32', + false, + 'cmd.exe', + 'children', 'held', false, false ], - ['intervening command retired the launch', 'darwin', true, 'zsh', 'gone', false, false], - ['successor launch during inspection', 'darwin', true, 'zsh', 'held', true, false], - ['unmarked cmd.exe back alone on Windows', 'win32', false, 'cmd.exe', 'held', false, true], - ['agent still foreground on Windows', 'win32', false, 'codex.exe', 'held', false, false] + [ + 'older daemon without a child census on Windows', + 'win32', + false, + 'cmd.exe', + undefined, + 'held', + false, + false + ] ] as const)( 'proves an unmarked process exit only for the current launch: %s', - async (_, os, shellAlone, foreground, evidence, replaced, expected) => { + async (_, os, shellAlone, foreground, census, evidence, replaced, expected) => { Object.defineProperty(process, 'platform', { value: os }) const launch = { agentArgs: '', agentEnv: {} } let currentLaunch = evidence === 'held' ? launch : evidence === 'gone' ? null : undefined @@ -52,11 +100,11 @@ it.each([ } return shellAlone }, - // Windows answers from its job census; a scan that names no agent is not that census. + // Windows answers from its job census; a foreground name alone is not that census. inspectProcess: async () => ({ foregroundProcess: foreground, - hasChildProcesses: foreground !== 'cmd.exe', - childProcessEvidence: foreground === 'cmd.exe' ? 'no-children' : 'children' + hasChildProcesses: false, + ...(census ? { childProcessEvidence: census } : {}) }) }) // SAFETY: This binding's exit probe only reads these two runtime capabilities. diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 9fd2a8fccbd1..286626ba238b 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -112,7 +112,8 @@ export function bindTerminalPaneStatusLifecycle( /** The shell alone holds the PTY, with no stopped job behind it. The daemon's proof needs prompt * marks, which cmd and Git Bash often lack; Windows shells stop no jobs, so the host's job census - * finding no child beside a shell foreground suffices there. */ + * finding no child beside a shell foreground suffices there. Elsewhere only the host's shell-alone + * proof counts; never fall back to a foreground name, which a live unrecognized agent shares. */ async function confirmShellAlone(ptyId: string, incarnationId?: string): Promise { const provider = getProviderForPty(ptyId) if ((await provider.confirmShellForeground?.(ptyId)) === true) { From 6b4b56e53e58502500ffb12cd7f53b6207145756 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:49:08 -0800 Subject: [PATCH 040/125] Refuse a running background job as exit proof on the local shell check Council follow-up: Ctrl-Z then bg leaves the agent running beside a foreground shell; the exit proof now also requires no live descendant of that shell, leaving ordinary foreground reads unchanged. --- .../pane/terminal-pane-status-lifecycle.ts | 2 +- .../agent-process-shell-alone.test.ts | 36 +++++++++++++++++++ .../providers/foreground/agent-process.ts | 7 ++++ .../local-pty-foreground-inspection.ts | 7 ++-- .../providers/local-pty/local-pty-provider.ts | 4 +-- src/main/providers/pty/provider-contract.ts | 8 +++-- 6 files changed, 57 insertions(+), 7 deletions(-) create mode 100644 src/main/providers/foreground/agent-process-shell-alone.test.ts diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 286626ba238b..386393203416 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -116,7 +116,7 @@ export function bindTerminalPaneStatusLifecycle( * proof counts; never fall back to a foreground name, which a live unrecognized agent shares. */ async function confirmShellAlone(ptyId: string, incarnationId?: string): Promise { const provider = getProviderForPty(ptyId) - if ((await provider.confirmShellForeground?.(ptyId)) === true) { + if ((await provider.confirmShellForeground?.(ptyId, { noLiveDescendants: true })) === true) { return true } if (process.platform !== 'win32') { diff --git a/src/main/providers/foreground/agent-process-shell-alone.test.ts b/src/main/providers/foreground/agent-process-shell-alone.test.ts new file mode 100644 index 000000000000..393f1c6f1e2e --- /dev/null +++ b/src/main/providers/foreground/agent-process-shell-alone.test.ts @@ -0,0 +1,36 @@ +import { expect, it, vi } from 'vitest' +import type { ProcessTableRow } from '../../../shared/process-observation/tables/process-table-snapshot' + +const { snapshot } = vi.hoisted(() => ({ snapshot: vi.fn<() => Promise>() })) +vi.mock( + '../../../shared/process-observation/tables/process-table-snapshot-reader', + async (load) => ({ + ...(await load()), + getFreshShellForegroundSnapshot: snapshot + }) +) + +const { confirmShellForegroundProcess } = await import('./agent-process') + +const SHELL: ProcessTableRow = { pid: 100, ppid: 1, stat: 'Ss+', command: '/bin/zsh' } + +it.skipIf(process.platform === 'win32').each([ + ['shell alone', [], false, true], + ['stopped agent (Ctrl-Z)', [{ pid: 101, ppid: 100, stat: 'T', command: 'codex' }], false, false], + [ + 'background agent (Ctrl-Z, then bg), foreground read', + [{ pid: 101, ppid: 100, stat: 'S', command: 'codex' }], + false, + true + ], + [ + 'background agent (Ctrl-Z, then bg), exit proof', + [{ pid: 101, ppid: 100, stat: 'S', command: 'codex' }], + true, + false + ], + ['reaped zombie, exit proof', [{ pid: 101, ppid: 100, stat: 'Z', command: 'codex' }], true, true] +] as const)('confirms the shell alone: %s', async (_, children, noLiveDescendants, expected) => { + snapshot.mockResolvedValue([SHELL, ...children]) + expect(await confirmShellForegroundProcess(100, '/bin/zsh', { noLiveDescendants })).toBe(expected) +}) diff --git a/src/main/providers/foreground/agent-process.ts b/src/main/providers/foreground/agent-process.ts index 836ae680cf13..3ca3bd876809 100644 --- a/src/main/providers/foreground/agent-process.ts +++ b/src/main/providers/foreground/agent-process.ts @@ -46,6 +46,8 @@ type ShellForegroundConfirmationOptions = { | null | Promise | null> readWindowsProcessIdentityTable?: () => Promise + /** Exit proof: a running background job (Ctrl-Z, then bg) also keeps the agent alive. */ + noLiveDescendants?: boolean } function commandExecutable(command: string): string { @@ -102,6 +104,11 @@ export async function confirmShellForegroundProcess( return false } const confirmed = foregroundShell?.stat.includes('+') === true + if (confirmed && foregroundShell && options.noLiveDescendants) { + return !collectDescendantsFromIndex(index, foregroundShell.pid).some( + (row) => !row.stat.includes('Z') + ) + } return confirmed } catch { return false diff --git a/src/main/providers/local-pty/local-pty-foreground-inspection.ts b/src/main/providers/local-pty/local-pty-foreground-inspection.ts index 0ccc207228c3..032b7719f254 100644 --- a/src/main/providers/local-pty/local-pty-foreground-inspection.ts +++ b/src/main/providers/local-pty/local-pty-foreground-inspection.ts @@ -291,7 +291,10 @@ export async function confirmLocalPtyForegroundProcess( } } -export async function confirmLocalPtyShellForeground(id: string): Promise { +export async function confirmLocalPtyShellForeground( + id: string, + options?: { noLiveDescendants?: boolean } +): Promise { const proc = ptyProcesses.get(id) if (!proc) { return false @@ -301,7 +304,7 @@ export async function confirmLocalPtyShellForeground(id: string): Promise readWindowsPtyJobProcessIds(proc) } - : {} + : { noLiveDescendants: options?.noLiveDescendants === true } ) return ptyProcesses.get(id) === proc && confirmed } diff --git a/src/main/providers/local-pty/local-pty-provider.ts b/src/main/providers/local-pty/local-pty-provider.ts index ba301fbcfad2..819fa0c1d19f 100644 --- a/src/main/providers/local-pty/local-pty-provider.ts +++ b/src/main/providers/local-pty/local-pty-provider.ts @@ -210,8 +210,8 @@ export class LocalPtyProvider implements IPtyProvider { return confirmLocalPtyForegroundProcess(id) } - confirmShellForeground(id: string): Promise { - return confirmLocalPtyShellForeground(id) + confirmShellForeground(id: string, options?: { noLiveDescendants?: boolean }): Promise { + return confirmLocalPtyShellForeground(id, options) } async serialize(_ids: string[]): Promise { diff --git a/src/main/providers/pty/provider-contract.ts b/src/main/providers/pty/provider-contract.ts index 19510b493232..91e7d56f562c 100644 --- a/src/main/providers/pty/provider-contract.ts +++ b/src/main/providers/pty/provider-contract.ts @@ -198,8 +198,12 @@ export type IPtyProvider = { getForegroundProcess(id: string): Promise /** Strong process evidence captured after the caller's command boundary. */ confirmForegroundProcess?: (id: string) => Promise - /** Fresh execution-host proof that the spawned shell owns the PTY foreground. */ - confirmShellForeground?: (id: string) => Promise + /** Fresh execution-host proof that the spawned shell owns the PTY foreground. `noLiveDescendants` + * (exit proof) also refuses a running background job where the host can see one. */ + confirmShellForeground?: ( + id: string, + options?: { noLiveDescendants?: boolean } + ) => Promise /** Persist main's live launch where the PTY outlives main; only the daemon keeps one. */ setLaunchNote?: (id: string, change: DaemonLaunchNoteChange) => void serialize(ids: string[]): Promise From 86ac1eb737a36bb6b5bcb1befe72e83c572519e8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:40:59 -0800 Subject: [PATCH 041/125] Mark a tmux-hosted conversation shared from its own hook A Claude inside tmux posts ordinary pane hook rows, and the only shared marker came from a sleep-time probe of the pane's foreground, which a detached client no longer shows; each wake then resumed a duplicate beside the live tmux agent. A hook carrying a real tmux pane (not Orca's inherited one) now marks its conversation shared at admission, so detach and sleep release it. --- .../server/cli-writer-observation.ts | 26 +++++++++++++++++++ .../server/server-ingest-normalization.ts | 15 ++++++++++- .../tmux/server-tmux-legacy-sleep.test.ts | 5 ++-- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/cli-writer-observation.ts b/src/main/agent-hooks/server/cli-writer-observation.ts index 9edce068dfb3..aa7ef7674635 100644 --- a/src/main/agent-hooks/server/cli-writer-observation.ts +++ b/src/main/agent-hooks/server/cli-writer-observation.ts @@ -12,6 +12,10 @@ import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/ import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' +import { + readTmuxHookPane, + readTmuxHookPaneHint +} from '../../../shared/agent-hook-listener/presence/tmux-client-attachment' // Execution metadata follows the conversation binding and disappears at serialization. export const OPEN_CODE_WRITER_TOPOLOGY = Symbol('openCodeWriterTopology') @@ -74,6 +78,28 @@ export function tmuxCliWriterEvent(row: T): T { return { ...row, providerSession } } +/** A hook that ran inside a tmux pane reaches this pane through a client; its server outlives the + * pane even after the client detaches, when the pane's foreground no longer shows tmux. A pane + * that only inherited Orca's own tmux environment hosts nothing. */ +export function retainTmuxHookWriterTopology( + event: AgentHookEventPayload | null, + body: unknown, + env: NodeJS.ProcessEnv = process.env +): void { + if (!event?.providerSession || !body || typeof body !== 'object') { + return + } + const tmux = + readTmuxHookPane('tmux' in body ? body.tmux : undefined) ?? + readTmuxHookPaneHint('tmuxPane' in body ? body.tmuxPane : undefined) + const inherited = readTmuxHookPaneHint( + env.TMUX_PANE && env.TMUX ? `${env.TMUX_PANE} ${env.TMUX.split(',')[0]}` : undefined + ) + if (tmux && !(inherited?.pane === tmux.pane && inherited.socket === tmux.socket)) { + retainTmuxWriterTopology(event.providerSession) + } +} + /** A binding the pane reaches through a tmux client; a decided binding keeps its topology. */ export function retainTmuxWriterTopology( binding: NonNullable diff --git a/src/main/agent-hooks/server/server-ingest-normalization.ts b/src/main/agent-hooks/server/server-ingest-normalization.ts index d1efe9d71062..4786e821dd41 100644 --- a/src/main/agent-hooks/server/server-ingest-normalization.ts +++ b/src/main/agent-hooks/server/server-ingest-normalization.ts @@ -1,4 +1,7 @@ -import { retainOpenCodeWriterTopology } from './cli-writer-observation' +import { + retainOpenCodeWriterTopology, + retainTmuxHookWriterTopology +} from './cli-writer-observation' import { AgentHookAttributionDiagnostics } from '../../../shared/agent-hook-listener/state/agent-hook-attribution-diagnostics' import { buildSpoolHookBody, @@ -146,6 +149,16 @@ export abstract class AgentHookServerIngestNormalization extends AgentHookServer source: AgentHookSource, body: unknown, isReplay = false + ): NormalizedLocalHook { + const normalized = this.normalizeLocalHookPayloadFor(source, body, isReplay) + retainTmuxHookWriterTopology(normalized.event, body) + return normalized + } + + private normalizeLocalHookPayloadFor( + source: AgentHookSource, + body: unknown, + isReplay: boolean ): NormalizedLocalHook { if (source !== 'claude' || typeof body !== 'object' || body === null) { const event = normalizeHookPayload(this.state, source, body, this.env, { diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index f1de2bb7d0f5..6a85a05044c0 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -121,7 +121,7 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint tmuxPane: TMUX_HINT, prompt: 'In tmux' }) - await server.checkAgentPresenceSince(PANE, 0) + // Nothing probes the pane while the client is attached; only the hook says it ran in tmux. let saved: SleepingAgentSessionRecord | undefined = { paneKey: PANE, worktreeId: 'wt-1', @@ -146,7 +146,8 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint }) // Detach ends the outer command, while the original agent remains under its server. runningPane(101, ...TMUX) - server.retireProcessAuthority(PANE, { confirmedExit: true }) + // The tmux client's command finished after an earlier finish retired the launch: no exit named. + server.retireProcessAuthority(PANE, { confirmedExit: false }) expect(saved).toBeUndefined() expect(server.row()).toBeUndefined() // The sleep's physical stop must not promote a stale checkpoint into a pane-owned agent. From 11d85c4fff40008a789b90ffbf7cc13ec684e4be Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:33:22 -0800 Subject: [PATCH 042/125] Fix gate findings: pin test clock, drop renderer-clearing tests the main owner replaced The worktree sleep recording regression test comes from #42391. Co-authored-by: d.bondarev --- .../persistence/server-pane-sleep.test.ts | 24 ++++++++++++ .../terminal-pane-status-lifecycle.test.ts | 2 +- .../worktree-sleep-resume-recording.test.ts | 1 + ...connection-process-exit-row-retire.test.ts | 6 +-- ...-hibernation-kill-shell-foreground.test.ts | 38 ------------------- 5 files changed, 29 insertions(+), 42 deletions(-) diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 071abf7f7aa0..0c60973bba3c 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -28,6 +28,8 @@ const read = () => server.getStatusSnapshotForPane(PANE)[0] beforeEach(async () => { _internals.resetCachesForTests() + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(1_000_000) home = mkdtempSync(join(tmpdir(), 'orca-sleep-status-')) stopping = false placed = true @@ -71,6 +73,28 @@ it('accepts a genuine providerless completion after stop intent and preserves it expect(read()).toBeUndefined() }) +const agentHook = (agent: 'claude' | 'codex', event: string, pid: number, source = 'resume') => + postHookEvent( + server, + buildBody( + { hook_event_name: event, session_id: `${agent}-session`, source, prompt: 'Finished work' }, + { + agentProcess: JSON.stringify({ pid, platform: process.platform, startTime: `birth-${pid}` }) + } + ), + `/hook/${agent}` + ) + +async function sleepPane(agent: 'claude' | 'codex', id: string, pid: number): Promise { + pty = { id, birth: `birth-${id}` } + stopping = true + if (agent === 'claude') { + await agentHook(agent, 'SessionEnd', pid) + } + expect(server.settleTerminalPaneSleep(PANE, pty.id, pty.birth)).toBe(true) + stopping = false +} + it.each(['claude', 'codex'] as const)( 'keeps %s Done through sleep, idle wake and sleep again', async (agent) => { diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index 50a494fc8d38..f018cf4fb905 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -107,7 +107,7 @@ it.each([ ...(census ? { childProcessEvidence: census } : {}) }) }) - // SAFETY: This binding's exit probe only reads these two runtime capabilities. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this exit probe only reads these two runtime capabilities. const runtime = { resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }), getLaunchStatementForPaneKey: () => currentLaunch diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 5bb7bacd9f81..e7e0bc26cb5c 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -339,6 +339,7 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini await server.reconcilePaneProcessExit(PANE_KEY) } else if (status === 'listing') { // An inventory refresh (`orca worktree ps`) re-mints the restored surface's receipt. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reaches the protected receipt minter the listing path calls. const internals = runtime as unknown as { ptysById: Map rememberRestoredOrchestrationAuthority(pty: unknown, handle: string, id: string): void diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts index ff780ce8022b..ff614fa182c5 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-process-exit-row-retire.test.ts @@ -279,9 +279,9 @@ describe('connectPanePty confirmed process exit retires the live agent row', () await flushAsyncTicks() // Main owns retirement; a process exit requests its proof rather than deleting recovery here. - expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]?.providerSession.id).toBe( - 'quit-session' - ) + expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toMatchObject({ + providerSession: { id: 'quit-session' } + }) expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey) // No `paneRemoved`: the pane outlived the agent, so main keeps the resume identity. expect(mockStoreState.dropAgentStatus.mock.calls).toEqual([[paneKey]]) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/lifecycle/pty-connection-hibernation-kill-shell-foreground.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/lifecycle/pty-connection-hibernation-kill-shell-foreground.test.ts index fe82eb9fb79d..305582cbdd67 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/lifecycle/pty-connection-hibernation-kill-shell-foreground.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/lifecycle/pty-connection-hibernation-kill-shell-foreground.test.ts @@ -265,42 +265,4 @@ describe('shell showing through a hibernation kill', () => { }) } ) - - it('clears the record once another PTY is bound in place of the hibernated one', async () => { - const pane = await connectHibernatingPane(true) - - pane.exitPty() - await flushAsyncTicks() - expect(mockStoreState.clearSleepingAgentSession).not.toHaveBeenCalled() - // A restart binds a new PTY without consuming the armed wake. - pane.rebindPty('pty-restarted') - pane.finishCommand() - await vi.advanceTimersByTimeAsync(350) - - expect(mockStoreState.clearSleepingAgentSession).toHaveBeenCalledExactlyOnceWith(pane.paneKey) - }) - - it('still clears a record beside a PTY that is not being hibernated', async () => { - const pane = await connectHibernatingPane(false) - - pane.finishCommand() - await vi.advanceTimersByTimeAsync(350) - - expect(mockStoreState.clearSleepingAgentSession).toHaveBeenCalledExactlyOnceWith(pane.paneKey) - }) - - it('does not protect a replacement record with the old wake target', async () => { - const pane = await connectHibernatingPane(true) - - pane.exitPty() - await flushAsyncTicks() - mockStoreState.sleepingAgentSessionsByPaneKey[pane.paneKey] = { - ...pane.record, - updatedAt: 2 - } - pane.finishCommand() - await vi.advanceTimersByTimeAsync(350) - - expect(mockStoreState.clearSleepingAgentSession).toHaveBeenCalledExactlyOnceWith(pane.paneKey) - }) }) From 0407041d1162e1240bfb27f5df8258321f7649a5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:48:47 -0800 Subject: [PATCH 043/125] Retire an exited record without copying the session; probe tmux hosts only at sleep capture A confirmed exit deep-cloned the whole host session twice to delete one saved record; it now patches that record and rolls back only it. Ordinary presence reads (fleet snapshots, holder checks) no longer run tmux-host discovery for row-present panes. --- .../agent-hooks/server/agent-hook-server.ts | 15 +++---- .../tmux/server-tmux-legacy-sleep.test.ts | 8 ++-- .../construction/runtime-store-contract.ts | 1 + .../orca-runtime-test-fixtures.spec.ts | 3 ++ .../terminal/stop/sleeping-record-removal.ts | 44 +++++++++++++++++++ .../worktree-sleep-resume-recording.test.ts | 25 +++++++++++ .../stop/worktree-sleep-resume-recording.ts | 16 +++---- 7 files changed, 90 insertions(+), 22 deletions(-) create mode 100644 src/main/runtime/terminal/stop/sleeping-record-removal.ts diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 50f4ecc8d7f5..8318f626abbf 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -133,8 +133,11 @@ export class AgentHookServer extends AgentHookServerLifecycle { } /** Legacy hooks cannot say a tmux server hosts them; the pane's foreground client can, before - * a sleep or adoption captures the conversation as the pane's own. */ + * a sleep captures the conversation as the pane's own. Other presence reads never probe. */ private async observeTmuxHostedWriter(paneKey: string, sleepCapture: boolean): Promise { + if (!sleepCapture) { + return + } const resolved = this.resolvePaneKeyAlias(paneKey) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: main stores enriched accepted rows in the base-typed cache. const row = this.state.lastStatusByPaneKey.get(resolved) as @@ -143,15 +146,9 @@ export class AgentHookServer extends AgentHookServerLifecycle { const binding = row?.providerSession const read = this.readPaneTmuxHost if (!row) { - return sleepCapture ? this.releaseTmuxHostedCheckpoint(resolved) : undefined + return this.releaseTmuxHostedCheckpoint(resolved) } - if ( - !read || - !row || - !binding || - row.connectionId !== null || - cliWriterTopology(row) !== 'pane-owned' - ) { + if (!read || !binding || row.connectionId !== null || cliWriterTopology(row) !== 'pane-owned') { return } const presence = row.agentPresence diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 6a85a05044c0..47626442573e 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -68,7 +68,7 @@ it.each([ runningPane(4050, CLIENT, ...TMUX) await turn(server) expect(server.row()).toMatchObject({ state: 'working', providerSession: {} }) - await server.checkAgentPresenceSince(PANE, 0) + await server.checkAgentPresenceSince(PANE, 0, { sleepCapture: true }) // A fresh hook can land between capture's presence check and the PTY's physical stop. await turn(server) server.setTerminalPaneLifecycle({ @@ -85,7 +85,8 @@ it.each([ launchByPtyId: new Map(), readRowsForPane: (key) => server.getStatusSnapshotForPane(key), readIdentity: (key, saved) => server.paneAgentIdentity(key, saved), - checkAgentPresence: (key, since) => server.checkAgentPresenceSince(key, since ?? 0), + checkAgentPresence: (key, since) => + server.checkAgentPresenceSince(key, since ?? 0, { sleepCapture: true }), capturedAt: NOW }) expect(capture.get('pty')).toEqual({ records: [], retiredPaneKeys: [PANE] }) @@ -160,7 +161,8 @@ it('does not recapture a detached tmux writer from its remaining live checkpoint readRowsForPane: (key) => server.getStatusSnapshotForPane(key), readSavedRecord: async () => saved, readIdentity: (key, record) => server.paneAgentIdentity(key, record), - checkAgentPresence: (key, since) => server.checkAgentPresenceSince(key, since ?? 0), + checkAgentPresence: (key, since) => + server.checkAgentPresenceSince(key, since ?? 0, { sleepCapture: true }), capturedAt: NOW + 1_000 }) expect(capture.get('pty')?.records).toEqual([]) diff --git a/src/main/runtime/construction/runtime-store-contract.ts b/src/main/runtime/construction/runtime-store-contract.ts index 62120c867c8e..1dedfaccbb7b 100644 --- a/src/main/runtime/construction/runtime-store-contract.ts +++ b/src/main/runtime/construction/runtime-store-contract.ts @@ -61,6 +61,7 @@ export type RuntimeStore = { onWorkspaceSessionOperationEnded?: Store['onWorkspaceSessionOperationEnded'] onStateWritten?: Store['onStateWritten'] setWorkspaceSession?: Store['setWorkspaceSession'] + patchWorkspaceSession?: Store['patchWorkspaceSession'] getRemoteLayoutSnapshots?: Store['getRemoteLayoutSnapshots'] readTerminalScrollbackSnapshotAsync?: Store['readTerminalScrollbackSnapshotAsync'] statTerminalScrollbackSnapshotSize?: Store['statTerminalScrollbackSnapshotSize'] diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts index 5cd57c64ab68..189f0b9d433e 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts @@ -520,6 +520,9 @@ function makeRuntimeStoreWithWorkspaceSession( getWorkspaceSession: (hostId?: string) => hostId === undefined || hostId === ownerHostId ? session : getDefaultWorkspaceSession(), setWorkspaceSession: vi.fn(setSession), + patchWorkspaceSession: (patch: Partial) => { + session = { ...session, ...patch } + }, getWorkspaceSessionHostIds: () => [ownerHostId], applyLayoutCommand: vi.fn( async ( diff --git a/src/main/runtime/terminal/stop/sleeping-record-removal.ts b/src/main/runtime/terminal/stop/sleeping-record-removal.ts new file mode 100644 index 000000000000..87fb2eae98db --- /dev/null +++ b/src/main/runtime/terminal/stop/sleeping-record-removal.ts @@ -0,0 +1,44 @@ +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { ExecutionHostId } from '../../../../shared/execution-host/execution-host' +import type { RuntimeStore } from '../../construction/runtime-store-contract' + +type SleepingRecordStore = Pick< + RuntimeStore, + 'getWorkspaceSession' | 'patchWorkspaceSession' | 'runDurableMutation' +> + +/** Durably removes one pane's saved resume when `retire` accepts it; a failed write restores only that record. */ +export async function removeSleepingRecordDurably( + store: SleepingRecordStore | null | undefined, + hostId: ExecutionHostId, + paneKey: string, + retire: (saved: SleepingAgentSessionRecord) => boolean +): Promise { + const getSession = store?.getWorkspaceSession?.bind(store) + const patchSession = store?.patchWorkspaceSession?.bind(store) + if (!getSession || !patchSession || !store?.runDurableMutation) { + throw new Error('workspace_session_unavailable') + } + const read = (): Record | undefined => + getSession(hostId)?.sleepingAgentSessionsByPaneKey + const patch = (records: Record): void => + patchSession({ sleepingAgentSessionsByPaneKey: records }, hostId) + await store.runDurableMutation(() => { + const records = read() + const removed = records?.[paneKey] + if (!records || !removed || !retire(removed)) { + return { value: undefined, persist: false } + } + const { [paneKey]: _removed, ...kept } = records + patch(kept) + return { + value: undefined, + rollback: () => { + const current = read() ?? {} + if (!Object.hasOwn(current, paneKey)) { + patch({ ...current, [paneKey]: removed }) + } + } + } + }) +} diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index e7e0bc26cb5c..87ab9738b04a 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -224,6 +224,31 @@ it.each([100, 1000])( } ) +it('retires one exited record without copying the rest of the session', async () => { + const others = Object.fromEntries( + Array.from({ length: 750 }, (_, i) => [ + `other-${i}`, + { ...OLDER_CHECKPOINT, paneKey: `other-${i}` } + ]) + ) + const fixture = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + sleepingAgentSessionsByPaneKey: { ...others, [PANE_KEY]: OLDER_CHECKPOINT } + }) + ) + const before = fixture.getSession() + const runtime = new OrcaRuntimeService(fixture.runtimeStore) + vi.spyOn(runtime, 'getTerminalWorktreeIdForPaneKey').mockReturnValue(TEST_WORKTREE_ID) + + runtime.retireExitedPaneResume(PANE_KEY, 200) + await runtime.readSavedResumeSource(TEST_WORKTREE_ID, PANE_KEY) + + const after = fixture.getSession() + expect(after.sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toBeUndefined() + expect(after.tabsByWorktree).toBe(before.tabsByWorktree) + expect(after.sleepingAgentSessionsByPaneKey?.['other-749']).toBe(others['other-749']) +}) + describe('a hookless resumed Codex across wakes and shell-confirmed command finishes', () => { const SESSION = { key: 'session_id' as const, id: 'woken-codex' } const SLEPT: SleepingAgentSessionRecord = { diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 79e8596e61a4..2dfc91160b5b 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -15,6 +15,7 @@ import { } from './hook-status-resume-records' import type { ResumeRecordStatus } from '../../../../shared/agent-session/lifecycle/resume/agent-resume-record-from-status' import { applyWindowLayoutCommand } from '../layout/runtime-layout-apply' +import { removeSleepingRecordDurably } from './sleeping-record-removal' import type { AgentStatusClearIpcPayload, AgentStatusIpcPayload, @@ -57,16 +58,11 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu if (!existing || existing.updatedAt > exitedAt) { return Promise.resolve() } - return this.commitWorkspaceSessionEdit( - this.getWorkspaceSessionHostIdForWorktree(worktreeId), - (session) => { - const saved = session.sleepingAgentSessionsByPaneKey?.[paneKey] - if (!saved || saved.updatedAt > exitedAt) { - return null - } - const { [paneKey]: _exited, ...kept } = session.sleepingAgentSessionsByPaneKey ?? {} - return { ...session, sleepingAgentSessionsByPaneKey: kept } - } + return removeSleepingRecordDurably( + this.store, + hostId, + paneKey, + (saved) => saved.updatedAt <= exitedAt ) }).catch((error) => console.warn('[runtime] could not retire an exited agent resume record', error) From 36898d204ba402650bfd71d7eb1acd3bb87b5d2e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:54:13 -0800 Subject: [PATCH 044/125] Keep the legacy tmux sleep test's harness beside it after main removed the hook-root suites --- .../server-tmux-hook-root.test-fixtures.ts | 170 ++++++++++++++++++ .../tmux/server-tmux-legacy-sleep.test.ts | 2 +- 2 files changed, 171 insertions(+), 1 deletion(-) create mode 100644 src/main/agent-hooks/server/testing/tmux/server-tmux-hook-root.test-fixtures.ts diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-hook-root.test-fixtures.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-hook-root.test-fixtures.ts new file mode 100644 index 000000000000..5b9315b16bbb --- /dev/null +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-hook-root.test-fixtures.ts @@ -0,0 +1,170 @@ +import { rmSync } from 'node:fs' +import { afterEach, beforeEach, expect, vi } from 'vitest' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import type { AgentProcessIdentity } from '../../../../../shared/agent-status/process/agent-process-presence' +import { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' +import { + readHookRootEvidence, + type HookPaneProcessIo +} from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { ProcessTableRow } from '../../../../../shared/process-observation/tables/process-table-snapshot' + +// Harness for legacy tmux hook tests; the test file mocks telemetry and the process probe module. +const live = new Set() +// Each test file mocks the probe module (vi.mock is per file); this is that mock. +const probe = vi.mocked(probeAgentProcessPresence) + +export const NOW = Date.UTC(2026, 10, 1, 12) +const TTY = 'ttys004' +export type Proc = [ + pid: number, + ppid: number, + pgid: number, + command: string, + stat?: string, + tty?: string +] +// Recorded macOS shape: the pane root is login(1). +const ROOT: Proc = [100, 90, 100, '/usr/bin/login -flpq u /bin/zsh -l', 'Ss'] +const SHELL: Proc = [101, 100, 101, '-zsh', 'S'] + +let rows: ProcessTableRow[] = [] +export const io = { + resolveRoot: vi.fn(async () => ({ + pid: 100, + incarnation: 'inc-1' + })), + probe: (identity: AgentProcessIdentity) => probe(identity), + readProcesses: vi.fn(async (pids: readonly number[]) => + rows.filter((row) => pids.includes(row.pid)) + ), + readTerminal: vi.fn(async (tty: string) => rows.filter((row) => row.tty === tty)) +} + +const servers: AgentHookServer[] = [] +const paths: string[] = [] + +/** Registers the fixed clock and per-test cleanup in the calling test file. */ +export function registerRootTestHarness(): void { + beforeEach(() => { + // Only the clock is fixed; the hook server's sockets keep real timers. + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(NOW) + }) + afterEach(() => { + for (const server of servers.splice(0)) { + server.stop() + } + for (const path of paths.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } + live.clear() + rows = [] + vi.clearAllMocks() + probe.mockReset() + vi.useRealTimers() + }) +} + +export class RootTestServer extends AgentHookServer { + row(paneKey = PANE) { + return this.getStatusSnapshot().find( + (entry) => entry.paneKey === paneKey && !entry.providerSessionOnly + ) + } +} + +function startOf(pid: number): string { + return `Sun Nov 1 00:${String(pid % 60).padStart(2, '0')}:23 2026` +} + +// Shaped like the Claude hook's X-Orca-Agent-Process capture. +function capture(pid: number): AgentProcessIdentity { + return { pid, platform: 'darwin', startTime: startOf(pid) } +} + +/** A server whose startup (spool replay included) the caller drives; `reader: false` installs none. */ +function launchServer( + userDataPath?: string, + options: { reader?: boolean; start?: (server: RootTestServer) => Promise } = {} +): { server: RootTestServer; started: Promise } { + probe.mockImplementation(async (identity) => + identity && live.has(identity.pid) ? 'live' : 'unverifiable' + ) + const server = new RootTestServer() + servers.push(server) + if (options.reader !== false) { + server.setHookRootEvidenceReader((request) => readHookRootEvidence(request, io)) + } + const start = + options.start ?? + ((target) => target.start({ env: 'production', ...(userDataPath ? { userDataPath } : {}) })) + return { server, started: start(server) } +} + +export async function createServer(userDataPath?: string): Promise { + const { server, started } = launchServer(userDataPath) + await started + return server +} + +/** The pane's processes; `foreground` holds the pane terminal's foreground group. */ +export function runningPane(foreground: number, ...procs: Proc[]): void { + rows = [ROOT, SHELL, ...procs].map(([pid, ppid, pgid, command, stat = 'S', tty = TTY]) => ({ + pid, + ppid, + pgid, + tpgid: tty === TTY ? foreground : 0, + stat, + tty, + command + })) + for (const [pid] of procs) { + live.add(pid) + } +} + +export async function hook( + server: AgentHookServer, + event: string, + options: { + session?: string + pid?: number | null + prompt?: string + reason?: string + source?: string + tmuxPane?: string + } = {} +): Promise { + const pid = options.pid === undefined ? 49969 : options.pid + const response = await postHookEvent( + server, + buildBody( + { + hook_event_name: event, + ...(event === 'SessionStart' ? { source: 'startup' } : {}), + ...(options.session !== undefined ? { session_id: options.session } : {}), + ...(options.reason ? { reason: options.reason } : {}), + ...(options.prompt ? { prompt: options.prompt } : {}) + }, + { + ...(pid === null ? {} : { agentProcess: JSON.stringify(capture(pid)) }), + ...(options.tmuxPane ? { tmuxPane: options.tmuxPane } : {}) + } + ), + `/hook/${options.source ?? 'claude'}` + ) + expect(response.status).toBe(204) +} + +export const codexTurn = (server: AgentHookServer, prompt = 'task') => + hook(server, 'UserPromptSubmit', { session: 'cx', pid: null, prompt, source: 'codex' }) + +// A tmux server started from the pane and its inner pane, on its own terminal. +export const TMUX: Proc[] = [ + [4041, 1, 4041, 'tmux', 'Ss', '??'], + [4042, 4041, 4042, '-zsh', 'Ss', 'ttys011'], + [4043, 4042, 4043, 'claude', 'S+', 'ttys011'] +] +export const TMUX_HINT = '%1 /private/tmp/tmux-501/default' diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 47626442573e..5bd2a395379e 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -12,7 +12,7 @@ import { runningPane, type Proc, type RootTestServer -} from '../presence/server-hook-root.test-fixtures' +} from './server-tmux-hook-root.test-fixtures' import { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture From 0d80c2b6e4f53ef8624b413a3c0da0bcf781fadf Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:18:39 -0800 Subject: [PATCH 045/125] Retire an exited record through the store's single-record retirement and the coalesced save The keyed patch still reordered every workspace's rows and forced an immediate whole-domain durable write per exit. The store now drops just that record without topology work, and the ordinary debounced save persists it, so a burst of exits shares one save, as the window's own record clearing did. --- .../session-snapshot-operations.ts | 35 ++++++++++++- ...sistence-host-partitioned-sessions.test.ts | 52 +++++++++++++++++++ .../construction/runtime-store-contract.ts | 2 +- .../orca-runtime-test-fixtures.spec.ts | 15 +++++- .../terminal/stop/sleeping-record-removal.ts | 44 ---------------- .../worktree-sleep-resume-recording.test.ts | 40 -------------- .../stop/worktree-sleep-resume-recording.ts | 18 ++----- 7 files changed, 104 insertions(+), 102 deletions(-) delete mode 100644 src/main/runtime/terminal/stop/sleeping-record-removal.ts diff --git a/src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts b/src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts index dce0dbef4a8a..187305190ded 100644 --- a/src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts +++ b/src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts @@ -7,6 +7,7 @@ import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host/execution-host' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import { pruneWorkspaceSessionBrowserHistory } from '../../../../shared/workspace-session/workspace-session-browser-history' import { workspaceSessionPatchNeedsFullNormalization } from './terminal-session-cleanup' @@ -102,8 +103,38 @@ export class SessionSnapshotOperations { this.publishSession(next, resolved) } - private publishSession(session: WorkspaceSessionState, hostId: ExecutionHostId): void { - session = orderTerminalRowsByTabGroups(session) + /** Drops one pane's saved resume when `retire` accepts it. Topology is untouched, so rows keep + * their order and the next coalesced save persists it. */ + retireSleepingAgentSession( + paneKey: string, + retire: (saved: SleepingAgentSessionRecord) => boolean, + hostId?: string | null + ): boolean { + const resolved = resolveHostId(hostId) + const session = this[sessionSnapshotOperationsContext].sessions.getWorkspaceSession(resolved) + const records = session.sleepingAgentSessionsByPaneKey + const saved = records?.[paneKey] + if (!records || !saved || !retire(saved)) { + return false + } + this.assertSnapshotAdmission() + const { [paneKey]: _retired, ...kept } = records + let next: WorkspaceSessionState = { ...session, sleepingAgentSessionsByPaneKey: kept } + if (resolved === LOCAL_EXECUTION_HOST_ID) { + next = keepWslMoveFrozenSessionsForStore(next, session) + } + this.publishSession(next, resolved, false) + return true + } + + private publishSession( + session: WorkspaceSessionState, + hostId: ExecutionHostId, + topologyChanged = true + ): void { + if (topologyChanged) { + session = orderTerminalRowsByTabGroups(session) + } const { runtime, scheduling } = this[sessionSnapshotOperationsContext] if (hostId === LOCAL_EXECUTION_HOST_ID) { runtime.state.workspaceSession = session diff --git a/src/main/persistence/persistence-host-partitioned-sessions.test.ts b/src/main/persistence/persistence-host-partitioned-sessions.test.ts index 6064f5ce86a9..e6e47cbfd623 100644 --- a/src/main/persistence/persistence-host-partitioned-sessions.test.ts +++ b/src/main/persistence/persistence-host-partitioned-sessions.test.ts @@ -14,6 +14,7 @@ import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' +import type { SleepingAgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-resume' import { getDefaultWorkspaceSession } from '../../shared/orca-profiles/constants' import { worktreeWorkspaceKey } from '../../shared/workspace/identity/workspace-scope' @@ -207,6 +208,57 @@ describe('Store host-partitioned workspace sessions', () => { }) // Fencing an unwritten host partition would rebase sibling worktrees onto empty state. + it.each(['local', 'runtime:env-a'])( + 'retires one saved resume in the %s partition and keeps it retired after reload', + async (hostId) => { + const record = (paneKey: string, updatedAt: number): SleepingAgentSessionRecord => ({ + paneKey, + tabId: 'tab-1', + worktreeId: 'repo-1::/workspace/repo-1', + agent: 'claude', + providerSession: { key: 'session_id', id: `${paneKey}-session` }, + prompt: '', + state: 'done', + capturedAt: 1, + updatedAt, + origin: 'worktree-sleep', + connectionId: null + }) + const store = createStore() + store.addRepo(makeRepo({ id: 'repo-1', path: '/workspace/repo-1' })) + store.setWorkspaceSession( + { + ...makeHostSession('repo-1'), + sleepingAgentSessionsByPaneKey: { + quit: record('quit', 100), + newer: record('newer', 300), + other: record('other', 100) + } + }, + hostId + ) + const before = store.getWorkspaceSession(hostId) + + expect( + store.retireSleepingAgentSession('quit', (saved) => saved.updatedAt <= 200, hostId) + ).toBe(true) + expect( + store.retireSleepingAgentSession('newer', (saved) => saved.updatedAt <= 200, hostId) + ).toBe(false) + expect(store.getWorkspaceSession(hostId).sleepingAgentSessionsByPaneKey?.other).toBe( + before.sleepingAgentSessionsByPaneKey?.other + ) + store.flush() + store.freezeWrites() + await store.waitForPendingWrite() + const reloaded = createStore().getWorkspaceSession(hostId) + expect(Object.keys(reloaded.sleepingAgentSessionsByPaneKey ?? {}).sort()).toEqual([ + 'newer', + 'other' + ]) + } + ) + it('does not fence a delayed session write when its host partition was never persisted', async () => { const store = await createStore() const worktreeId = 'repo-gone::/workspace/stale' diff --git a/src/main/runtime/construction/runtime-store-contract.ts b/src/main/runtime/construction/runtime-store-contract.ts index 884a4b83481f..4df75fcb2094 100644 --- a/src/main/runtime/construction/runtime-store-contract.ts +++ b/src/main/runtime/construction/runtime-store-contract.ts @@ -62,7 +62,7 @@ export type RuntimeStore = { onWorkspaceSessionOperationEnded?: Store['onWorkspaceSessionOperationEnded'] onStateWritten?: Store['onStateWritten'] setWorkspaceSession?: Store['setWorkspaceSession'] - patchWorkspaceSession?: Store['patchWorkspaceSession'] + retireSleepingAgentSession?: Store['retireSleepingAgentSession'] getRemoteLayoutSnapshots?: Store['getRemoteLayoutSnapshots'] readTerminalScrollbackSnapshotAsync?: Store['readTerminalScrollbackSnapshotAsync'] statTerminalScrollbackSnapshotSize?: Store['statTerminalScrollbackSnapshotSize'] diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts index 189f0b9d433e..41a97182ae7a 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts @@ -30,6 +30,7 @@ import type { RpcRequest } from '../rpc/core' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' @@ -520,8 +521,18 @@ function makeRuntimeStoreWithWorkspaceSession( getWorkspaceSession: (hostId?: string) => hostId === undefined || hostId === ownerHostId ? session : getDefaultWorkspaceSession(), setWorkspaceSession: vi.fn(setSession), - patchWorkspaceSession: (patch: Partial) => { - session = { ...session, ...patch } + retireSleepingAgentSession: ( + paneKey: string, + retire: (saved: SleepingAgentSessionRecord) => boolean, + hostId?: string | null + ) => { + const saved = session.sleepingAgentSessionsByPaneKey?.[paneKey] + if ((hostId ?? ownerHostId) !== ownerHostId || !saved || !retire(saved)) { + return false + } + const { [paneKey]: _retired, ...kept } = session.sleepingAgentSessionsByPaneKey ?? {} + session = { ...session, sleepingAgentSessionsByPaneKey: kept } + return true }, getWorkspaceSessionHostIds: () => [ownerHostId], applyLayoutCommand: vi.fn( diff --git a/src/main/runtime/terminal/stop/sleeping-record-removal.ts b/src/main/runtime/terminal/stop/sleeping-record-removal.ts deleted file mode 100644 index 87fb2eae98db..000000000000 --- a/src/main/runtime/terminal/stop/sleeping-record-removal.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' -import type { ExecutionHostId } from '../../../../shared/execution-host/execution-host' -import type { RuntimeStore } from '../../construction/runtime-store-contract' - -type SleepingRecordStore = Pick< - RuntimeStore, - 'getWorkspaceSession' | 'patchWorkspaceSession' | 'runDurableMutation' -> - -/** Durably removes one pane's saved resume when `retire` accepts it; a failed write restores only that record. */ -export async function removeSleepingRecordDurably( - store: SleepingRecordStore | null | undefined, - hostId: ExecutionHostId, - paneKey: string, - retire: (saved: SleepingAgentSessionRecord) => boolean -): Promise { - const getSession = store?.getWorkspaceSession?.bind(store) - const patchSession = store?.patchWorkspaceSession?.bind(store) - if (!getSession || !patchSession || !store?.runDurableMutation) { - throw new Error('workspace_session_unavailable') - } - const read = (): Record | undefined => - getSession(hostId)?.sleepingAgentSessionsByPaneKey - const patch = (records: Record): void => - patchSession({ sleepingAgentSessionsByPaneKey: records }, hostId) - await store.runDurableMutation(() => { - const records = read() - const removed = records?.[paneKey] - if (!records || !removed || !retire(removed)) { - return { value: undefined, persist: false } - } - const { [paneKey]: _removed, ...kept } = records - patch(kept) - return { - value: undefined, - rollback: () => { - const current = read() ?? {} - if (!Object.hasOwn(current, paneKey)) { - patch({ ...current, [paneKey]: removed }) - } - } - } - }) -} diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 87ab9738b04a..f99a250c31c2 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -209,46 +209,6 @@ describe('main-run sleep of a pane whose hook row is gone', () => { }) }) -it.each([100, 1000])( - 'skips durable session transactions for %s exits without recovery records', - async (count) => { - const fixture = makeRuntimeStoreWithWorkspaceSession(makeWorkspaceSessionWithHeadlessTerminal()) - const runtime = new OrcaRuntimeService(fixture.runtimeStore) - vi.spyOn(runtime, 'getTerminalWorktreeIdForPaneKey').mockReturnValue(TEST_WORKTREE_ID) - const durableMutation = vi.spyOn(fixture.runtimeStore, 'runDurableMutation') - for (let i = 0; i < count; i++) { - runtime.retireExitedPaneResume(`absent-tab-${i}:11111111-1111-4111-8111-111111111111`, 200) - } - await runtime.readSavedResumeSource(TEST_WORKTREE_ID, PANE_KEY) - expect(durableMutation).not.toHaveBeenCalled() - } -) - -it('retires one exited record without copying the rest of the session', async () => { - const others = Object.fromEntries( - Array.from({ length: 750 }, (_, i) => [ - `other-${i}`, - { ...OLDER_CHECKPOINT, paneKey: `other-${i}` } - ]) - ) - const fixture = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - sleepingAgentSessionsByPaneKey: { ...others, [PANE_KEY]: OLDER_CHECKPOINT } - }) - ) - const before = fixture.getSession() - const runtime = new OrcaRuntimeService(fixture.runtimeStore) - vi.spyOn(runtime, 'getTerminalWorktreeIdForPaneKey').mockReturnValue(TEST_WORKTREE_ID) - - runtime.retireExitedPaneResume(PANE_KEY, 200) - await runtime.readSavedResumeSource(TEST_WORKTREE_ID, PANE_KEY) - - const after = fixture.getSession() - expect(after.sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toBeUndefined() - expect(after.tabsByWorktree).toBe(before.tabsByWorktree) - expect(after.sleepingAgentSessionsByPaneKey?.['other-749']).toBe(others['other-749']) -}) - describe('a hookless resumed Codex across wakes and shell-confirmed command finishes', () => { const SESSION = { key: 'session_id' as const, id: 'woken-codex' } const SLEPT: SleepingAgentSessionRecord = { diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 2dfc91160b5b..69109050c3d2 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -15,7 +15,6 @@ import { } from './hook-status-resume-records' import type { ResumeRecordStatus } from '../../../../shared/agent-session/lifecycle/resume/agent-resume-record-from-status' import { applyWindowLayoutCommand } from '../layout/runtime-layout-apply' -import { removeSleepingRecordDurably } from './sleeping-record-removal' import type { AgentStatusClearIpcPayload, AgentStatusIpcPayload, @@ -45,24 +44,17 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu ) } - /** A confirmed quit retires recovery durably before its exit evidence can expire. */ + /** A confirmed quit retires its saved recovery, which the next coalesced save persists. */ retireExitedPaneResume(paneKey: string, exitedAt: number): void { const worktreeId = this.getTerminalWorktreeIdForPaneKey(paneKey) if (!worktreeId) { return } - this.inResumeRecordOrder(() => { - const hostId = this.getWorkspaceSessionHostIdForWorktree(worktreeId) - const existing = - this.store?.getWorkspaceSession?.(hostId)?.sleepingAgentSessionsByPaneKey?.[paneKey] - if (!existing || existing.updatedAt > exitedAt) { - return Promise.resolve() - } - return removeSleepingRecordDurably( - this.store, - hostId, + this.inResumeRecordOrder(async () => { + this.store?.retireSleepingAgentSession?.( paneKey, - (saved) => saved.updatedAt <= exitedAt + (saved) => saved.updatedAt <= exitedAt, + this.getWorkspaceSessionHostIdForWorktree(worktreeId) ) }).catch((error) => console.warn('[runtime] could not retire an exited agent resume record', error) From 7e38fe53ad91f1c6eabc3f82289280167ab178f7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:25:34 -0800 Subject: [PATCH 046/125] Place the saved-resume retirement store test above the comment it displaced --- .../persistence-host-partitioned-sessions.test.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/persistence/persistence-host-partitioned-sessions.test.ts b/src/main/persistence/persistence-host-partitioned-sessions.test.ts index e6e47cbfd623..7f093bcbb17f 100644 --- a/src/main/persistence/persistence-host-partitioned-sessions.test.ts +++ b/src/main/persistence/persistence-host-partitioned-sessions.test.ts @@ -207,7 +207,6 @@ describe('Store host-partitioned workspace sessions', () => { expect(tabsOn(toSshExecutionHostId('ssh-b'))?.[0]?.id).toBe('twin-tab') }) - // Fencing an unwritten host partition would rebase sibling worktrees onto empty state. it.each(['local', 'runtime:env-a'])( 'retires one saved resume in the %s partition and keeps it retired after reload', async (hostId) => { @@ -237,7 +236,6 @@ describe('Store host-partitioned workspace sessions', () => { }, hostId ) - const before = store.getWorkspaceSession(hostId) expect( store.retireSleepingAgentSession('quit', (saved) => saved.updatedAt <= 200, hostId) @@ -245,9 +243,6 @@ describe('Store host-partitioned workspace sessions', () => { expect( store.retireSleepingAgentSession('newer', (saved) => saved.updatedAt <= 200, hostId) ).toBe(false) - expect(store.getWorkspaceSession(hostId).sleepingAgentSessionsByPaneKey?.other).toBe( - before.sleepingAgentSessionsByPaneKey?.other - ) store.flush() store.freezeWrites() await store.waitForPendingWrite() @@ -259,6 +254,7 @@ describe('Store host-partitioned workspace sessions', () => { } ) + // Fencing an unwritten host partition would rebase sibling worktrees onto empty state. it('does not fence a delayed session write when its host partition was never persisted', async () => { const store = await createStore() const worktreeId = 'repo-gone::/workspace/stale' From f62e0d41b17a696c0625a0641700c0cf415fa6e4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:40:56 -0800 Subject: [PATCH 047/125] Format the sleep handoff tests after main's directory move --- .../agent-status/agent-status-sleep-handoff.test.ts | 11 +++++++---- .../agent-status-sleep-wake-completion.test.ts | 11 +++++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-sleep-handoff.test.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-sleep-handoff.test.ts index 2a6cdcac9b29..b0453596e9be 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-sleep-handoff.test.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-sleep-handoff.test.ts @@ -10,10 +10,13 @@ vi.mock('../../../store', async () => { const { createTestStore } = await import('../../../store/testing/app-store-test-fixture') return { useAppStore: createTestStore() } }) -vi.mock('../../../components/terminal-pane/agent-completion/hook-lane/agent-hook-completion-notifications', () => ({ - observeAgentHookCompletionForNotification: vi.fn(), - syncAgentHookCompletionNotificationsForStoreUpdate: () => {} -})) +vi.mock( + '../../../components/terminal-pane/agent-completion/hook-lane/agent-hook-completion-notifications', + () => ({ + observeAgentHookCompletionForNotification: vi.fn(), + syncAgentHookCompletionNotificationsForStoreUpdate: () => {} + }) +) const NOW = 1_800_000_000_000 const LEAF = '11111111-1111-4111-8111-111111111111' const PANE = `tab-1:${LEAF}` diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-sleep-wake-completion.test.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-sleep-wake-completion.test.ts index 63315b852c16..d3a6988ef86b 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-sleep-wake-completion.test.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-sleep-wake-completion.test.ts @@ -17,10 +17,13 @@ vi.mock('../../../store', async () => { return { useAppStore: createTestStore() } }) // The lanes are replaced by direct restatements below; only admission is under test. -vi.mock('../../../components/terminal-pane/agent-completion/hook-lane/agent-hook-completion-notifications', () => ({ - observeAgentHookCompletionForNotification: vi.fn(), - syncAgentHookCompletionNotificationsForStoreUpdate: () => {} -})) +vi.mock( + '../../../components/terminal-pane/agent-completion/hook-lane/agent-hook-completion-notifications', + () => ({ + observeAgentHookCompletionForNotification: vi.fn(), + syncAgentHookCompletionNotificationsForStoreUpdate: () => {} + }) +) vi.mock('../../../store/github/refresh/stale-worktree-refresh-actions', () => ({ createStaleWorktreeRefreshActions: () => ({ refreshGitHubForWorktreeIfStale: vi.fn() }) })) From 15c6ec5edda4c17754afb01d32bf7ed0245cb01b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:33:23 -0800 Subject: [PATCH 048/125] Close new-vs-main gaps: tmux proofs, shared read budget, sleep verdicts, resume-only status, release cutoff, quit capture, notification and replay guards --- .../observations/local-hook-root-evidence.ts | 31 +++++---- .../runtime/agent-hook-runtime-deps.test.ts | 42 ++++++++++++ .../runtime/agent-hook-runtime-deps.ts | 4 ++ .../server/pane-agent-identity.test.ts | 24 +++++++ .../agent-hooks/server/pane-agent-identity.ts | 3 +- .../server/server-ingest-normalization.ts | 9 ++- src/main/agent-hooks/server/server-state.ts | 8 ++- .../tmux/server-tmux-legacy-sleep.test.ts | 60 +++++++++++++++-- .../runtime-agent-status-sources.ts | 4 ++ .../worktree-sleep-resume-recording.test.ts | 2 + .../stop/worktree-sleep-resume-recording.ts | 5 +- .../runtime-hook-agent-row-selection.ts | 7 +- ...ispatch-terminal-notification.mute.test.ts | 27 +++++++- .../dispatch-terminal-notification.ts | 1 + .../agent-status/agent-status-routing.test.ts | 9 +++ .../agent-status/agent-status-routing.ts | 5 +- .../hook-process-root-evidence-reader.ts | 31 +++++---- .../presence/hook-process-root-evidence.ts | 43 +----------- .../presence/pane-tmux-host-proof.ts | 65 +++++++++++++++++++ .../lifecycle/agent-pane-sleep-status.test.ts | 21 ++++++ .../lifecycle/agent-pane-sleep-status.ts | 2 +- 21 files changed, 321 insertions(+), 82 deletions(-) create mode 100644 src/main/agent-hooks/runtime/agent-hook-runtime-deps.test.ts create mode 100644 src/main/agent-hooks/server/pane-agent-identity.test.ts create mode 100644 src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts create mode 100644 src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts create mode 100644 src/shared/agent-status/lifecycle/agent-pane-sleep-status.test.ts diff --git a/src/main/agent-hooks/observations/local-hook-root-evidence.ts b/src/main/agent-hooks/observations/local-hook-root-evidence.ts index ee083998a798..9f6996093fc5 100644 --- a/src/main/agent-hooks/observations/local-hook-root-evidence.ts +++ b/src/main/agent-hooks/observations/local-hook-root-evidence.ts @@ -4,8 +4,12 @@ import { createLocalPtyInventoryReader, type LocalPtyInventoryReader } from './local-tmux-managed-pty' -import { createLocalHookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' -import { readPaneTmuxHost } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import { + createHookProcessReadSlots, + createLocalHookRootEvidenceReader, + hookProcessReadGate +} from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' +import { readPaneTmuxHost } from '../../../shared/agent-hook-listener/presence/pane-tmux-host-proof' import { readSelectedRows, readTerminalRows @@ -22,15 +26,20 @@ export function installLocalHookRootEvidence(server: AgentHookServer): LocalPtyI }) if (process.platform !== 'win32') { const resolveRoot = createLocalHookPaneRootResolver(readInventory) - server.setHookRootEvidenceReader(createLocalHookRootEvidenceReader(resolveRoot), (request) => - readPaneTmuxHost( - { - resolveRoot, - readProcesses: (pids) => readSelectedRows(pids).catch(() => []), - readTerminal: (tty) => readTerminalRows(tty).catch(() => []) - }, - request - ) + // Root evidence and tmux host probes share one process-read budget. + const slots = createHookProcessReadSlots() + const gate = hookProcessReadGate(slots) + server.setHookRootEvidenceReader( + createLocalHookRootEvidenceReader(resolveRoot, slots), + (request) => + readPaneTmuxHost( + { + resolveRoot, + readProcesses: (pids) => readSelectedRows(pids, gate).catch(() => []), + readTerminal: (tty) => readTerminalRows(tty, gate).catch(() => []) + }, + request + ) ) } return readInventory diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.test.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.test.ts new file mode 100644 index 000000000000..92e20d4e5087 --- /dev/null +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.test.ts @@ -0,0 +1,42 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../server/agent-hook-server' +import { selectFreshExplicitAgentStatusRow } from '../../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' +import { agentHookRuntimeDeps } from './agent-hook-runtime-deps' + +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) + +const PANE = makePaneKey('tab-dismissed', '11111111-1111-4111-8111-111111111111') +const servers: AgentHookServer[] = [] +afterEach(() => { + for (const server of servers.splice(0)) { + server.stop() + } +}) + +it('keeps a dismissed running agent out of status readers', () => { + const server = new AgentHookServer() + servers.push(server) + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-dismissed', + worktreeId: 'wt-dismissed', + source: 'claude', + hookEventName: 'UserPromptSubmit', + hasExplicitPrompt: true, + providerSession: { key: 'session_id', id: 'claude-conversation' }, + payload: { agentType: 'claude', state: 'working', prompt: 'Keep going' } + }, + null + ) + server.dropStatusEntry(PANE) + const rows = server.getStatusSnapshot() + expect(rows).toMatchObject([{ paneKey: PANE, providerSessionOnly: true }]) + const deps = agentHookRuntimeDeps(server, { read: () => undefined }, () => ({})) + expect(deps.getAgentStatusSnapshot()).toEqual([]) + expect( + selectFreshExplicitAgentStatusRow({ handles: [], paneKeys: [PANE], hookRows: rows }) + ).toBeNull() +}) diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index 075e5167f275..6b01868ce1a4 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -22,6 +22,10 @@ export function agentHookRuntimeDeps( if (row.structuredHost) { return [row] } + // Resume-only rows carry identity for recovery, never status. + if (row.providerSessionOnly) { + return [] + } const identity = server.paneAgentIdentity(row.paneKey) return identity && !identity.ended ? [identity.status] : [] }), diff --git a/src/main/agent-hooks/server/pane-agent-identity.test.ts b/src/main/agent-hooks/server/pane-agent-identity.test.ts new file mode 100644 index 000000000000..60103e6a87ea --- /dev/null +++ b/src/main/agent-hooks/server/pane-agent-identity.test.ts @@ -0,0 +1,24 @@ +import { expect, it } from 'vitest' +import { paneAgentIdentity } from './pane-agent-identity' + +it('ends a pane whose only report since the exit is a replay of older evidence', () => { + const row = { + paneKey: 'tab:1', + worktreeId: 'wt', + connectionId: null, + receivedAt: 2_000, + evidenceObservedAt: 1_000, + stateStartedAt: 1_000, + state: 'done', + agentType: 'claude', + prompt: '' + } as const + expect(paneAgentIdentity({ paneKey: 'tab:1', row, exitedAt: 1_500 })?.ended).toBe(true) + expect( + paneAgentIdentity({ + paneKey: 'tab:1', + row: { ...row, evidenceObservedAt: 1_800 }, + exitedAt: 1_500 + })?.ended + ).toBe(false) +}) diff --git a/src/main/agent-hooks/server/pane-agent-identity.ts b/src/main/agent-hooks/server/pane-agent-identity.ts index 76bbb2444ecb..09a0dd85efdb 100644 --- a/src/main/agent-hooks/server/pane-agent-identity.ts +++ b/src/main/agent-hooks/server/pane-agent-identity.ts @@ -47,7 +47,8 @@ export function paneAgentIdentity(args: { if (row.paneSleep) { return { status, ended: false } } - return { status, ended: endedSince(args, row.receivedAt) } + // A replayed report restamps receipt but not evidence; only newer evidence outlives an exit. + return { status, ended: endedSince(args, row.evidenceObservedAt ?? row.receivedAt) } } const saved = args.savedRecord if (!saved || !args.worktreeId || saved.paneKey !== args.paneKey) { diff --git a/src/main/agent-hooks/server/server-ingest-normalization.ts b/src/main/agent-hooks/server/server-ingest-normalization.ts index 4786e821dd41..8de6acb00eaa 100644 --- a/src/main/agent-hooks/server/server-ingest-normalization.ts +++ b/src/main/agent-hooks/server/server-ingest-normalization.ts @@ -11,10 +11,8 @@ import { checkHookOwnerPresence, restateHookRoot } from '../../../shared/agent-hook-listener/presence/agent-hook-owner-presence' -import type { - HookRootEvidenceReader, - PaneTmuxHostReader -} from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { HookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { PaneTmuxHostReader } from '../../../shared/agent-hook-listener/presence/pane-tmux-host-proof' import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normalization/normalize-hook-payload' import { isAgentHookSource, @@ -56,7 +54,8 @@ export abstract class AgentHookServerIngestNormalization extends AgentHookServer ) { return } - this.releaseSharedPaneConversation(paneKey, identity.status) + // The identity is the saved record as probed; a record saved during the probe stays. + this.releaseSharedPaneConversation(paneKey, identity.status, identity.status.receivedAt) } /** Panes whose owner an undecided hook challenged: until that hook is admitted or refused, the diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 1f66e89b9b8b..1b9794f79bc7 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -114,12 +114,14 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract this.retirePaneResume(paneKeys, status, exitedAt) } - /** A shared server's client left the pane; its conversation lives on there, never resumed here. */ + /** A shared server's client left the pane; its conversation lives on there, never resumed here. + * `releasedAt` bounds which saved record retires; one saved later is a newer conversation. */ protected releaseSharedPaneConversation( paneKey: string, - status: PaneAgentIdentity['status'] + status: PaneAgentIdentity['status'], + releasedAt = Date.now() ): void { - this.retirePaneResume(this.paneKeysWithAliases(paneKey), status, Date.now()) + this.retirePaneResume(this.paneKeysWithAliases(paneKey), status, releasedAt) } private paneKeysWithAliases(paneKey: string): Set { diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 5bd2a395379e..6f60a3762ee9 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -17,10 +17,8 @@ import { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture } from '../../../../runtime/terminal/identity/agent-status-observed-pane-identity' -import { - readHookRootEvidence, - readPaneTmuxHost -} from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import { readHookRootEvidence } from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import { readPaneTmuxHost } from '../../../../../shared/agent-hook-listener/presence/pane-tmux-host-proof' import { captureWorktreeSleepResumeRecords } from '../../../../runtime/terminal/stop/worktree-sleep-resume-records' import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' @@ -214,3 +212,57 @@ it('does not resume a checkpoint the pane reaches through its tmux client after expect(saved).toBeUndefined() expect(capture.get('pty')?.records).toEqual([]) }) + +it('proves a tmux-hosted pane only from a complete process picture', async () => { + const pane = { paneKey: PANE, worktreeId: 'wt-1' } + const agent = { ...pane, process: { pid: 4043, platform: 'darwin', startTime: 'start' } as const } + runningPane(4050, CLIENT, ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) + await expect(readPaneTmuxHost(io, agent)).resolves.toBe(true) + // The pane's own suspended agent stays behind an unrelated tmux client. + runningPane(4050, CLIENT, [4060, 101, 4060, 'claude', 'T'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + // An agent whose ancestry cannot be read is not proven to live outside the pane. + runningPane(4050, CLIENT, [4043, 4042, 4043, 'claude', 'S+', 'ttys011']) + await expect(readPaneTmuxHost(io, agent)).resolves.toBe(false) +}) + +it('keeps a checkpoint saved while its tmux release was probing', async () => { + const server = await createServer() + const record = (id: string, updatedAt: number): SleepingAgentSessionRecord => ({ + paneKey: PANE, + worktreeId: 'wt-1', + agent: 'claude', + providerSession: { key: 'session_id', id }, + prompt: 'In tmux', + state: 'done', + capturedAt: updatedAt, + updatedAt, + origin: 'live' + }) + const replacement = record('replacement', NOW + 500) + let saved: SleepingAgentSessionRecord | undefined = record('released', NOW) + server.setHookRootEvidenceReader( + (request) => readHookRootEvidence(request, io), + (request) => { + saved = replacement + return readPaneTmuxHost(io, request) + } + ) + runningPane(4050, CLIENT, ...TMUX) + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => true, + isPlaced: () => true, + readSavedRecord: () => saved, + retireSavedRecord: (_paneKey, before) => { + if (saved && saved.updatedAt <= before) { + saved = undefined + } + } + }) + vi.setSystemTime(NOW + 1_000) + await server.checkAgentPresenceSince(PANE, 0, { sleepCapture: true }) + expect(saved).toBe(replacement) +}) diff --git a/src/main/runtime/construction/runtime-agent-status-sources.ts b/src/main/runtime/construction/runtime-agent-status-sources.ts index dcceb9d4735d..232bf86133ac 100644 --- a/src/main/runtime/construction/runtime-agent-status-sources.ts +++ b/src/main/runtime/construction/runtime-agent-status-sources.ts @@ -43,6 +43,10 @@ export abstract class RuntimeAgentStatusSources extends OrcaRuntimeWithTerminalD if (row.structuredHost) { return [row] } + // A live pane's resume-only row (a dismissed agent) carries identity, never status. + if (row.providerSessionOnly) { + return [] + } const identity = this.readPaneAgentIdentity(row.paneKey, undefined, row) return identity && !identity.ended ? [identity.status] : [] }) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 98a724f7f701..a91bf1743b5a 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -140,6 +140,8 @@ describe('main-run sleep of a pane whose hook row is gone', () => { if (scenario === 'working' || scenario === 'interrupted') { expect(record?.interrupted).toBe(true) } + // Quitting while asleep keeps the sleep record rather than rewriting it as a quit. + expect(runtime.quitResumeRecordsFor(fixture.getSession())).toEqual([]) } } finally { server.stop() diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 69109050c3d2..7bdcfdbdb579 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -238,9 +238,12 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu /** A layout-owner build's quit capture of the agents of the panes one partition holds. */ quitResumeRecordsFor(session: WorkspaceSessionState): SleepingAgentSessionRecord[] { + // A saved-only pane quits only while its terminal runs; an asleep pane keeps its sleep record. const paneKeys = new Set([ ...(this.getAgentProviderSessionSnapshotFn?.() ?? []).map((row) => row.paneKey), - ...Object.keys(session.sleepingAgentSessionsByPaneKey ?? {}) + ...Object.keys(session.sleepingAgentSessionsByPaneKey ?? {}).filter((paneKey) => + this.hasLiveTerminalForPaneKey(paneKey) + ) ]) const statuses = [...paneKeys].flatMap((paneKey) => { const identity = this.readPaneAgentIdentity( diff --git a/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts b/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts index 7dda716dd7f9..060b15415e5d 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts @@ -36,8 +36,12 @@ function isLiveObservation(row: AgentStatusIpcPayload): boolean { if (row.structuredHost) { return row.restoredUnconfirmed !== true } + // Restored rows cannot prove current liveness; resume-identity rows carry no status. + if (row.restoredUnconfirmed === true || row.providerSessionOnly === true) { + return false + } const identity = paneAgentIdentity({ paneKey: row.paneKey, row }) - return row.restoredUnconfirmed !== true && identity !== null && !identity.ended + return identity !== null && !identity.ended } type HookRowJoin = { @@ -56,6 +60,7 @@ function isPermissionState(state: AgentStatusEntry['state']): boolean { function isHeldRestoredPermission(row: AgentStatusIpcPayload, join: HookRowJoin): boolean { return ( row.restoredUnconfirmed === true && + row.providerSessionOnly !== true && isPermissionState(row.state) && join.screenMayHoldDialog?.() === true ) diff --git a/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.mute.test.ts b/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.mute.test.ts index e06bef44b705..9e7f78b096ff 100644 --- a/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.mute.test.ts +++ b/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.mute.test.ts @@ -28,7 +28,7 @@ const NOW = 1_700_000_000_000 const dispatched: NotificationDispatchRequest[] = [] -function seed(muted: Record): void { +function seed(muted: Record, launchRestored = false): void { store.setState({ repos: [TEST_REPO], worktreesByRepo: { @@ -69,7 +69,18 @@ function seed(muted: Record): void { paneKey: PANE_KEY, terminalTitle: 'codex', stateHistory: [], - lastAssistantMessage: 'Done.' + lastAssistantMessage: 'Done.', + ...(launchRestored + ? { + observation: { + origin: 'launch' as const, + authorityId: 'main', + incarnation: 1, + revision: 1, + observedAt: NOW + } + } + : {}) } ] ]), @@ -114,4 +125,16 @@ describe('dispatchTerminalNotification per-worktree mute', () => { expect(dispatched).toEqual([]) expect(store.getState().worktreesByRepo.repo1?.[0]?.isUnread).toBe(true) }) + + it("does not take another agent's restored turn for this completion's restatement", () => { + seed({}, true) + + dispatchTerminalNotification(WORKSPACE, { + source: 'agent-task-complete', + terminalTitle: 'claude', + paneKey: PANE_KEY + }) + + expect(store.getState().worktreesByRepo.repo1?.[0]?.isUnread).toBe(true) + }) }) diff --git a/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.ts b/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.ts index 642afb1b01ba..9eecf5420971 100644 --- a/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.ts +++ b/src/renderer/src/components/terminal-pane/notifications/dispatch-terminal-notification.ts @@ -114,6 +114,7 @@ export function dispatchTerminalNotification( event.source === 'agent-task-complete' && storedAgentStatus?.state === 'done' && storedAgentStatus.observation?.origin === 'launch' && + agentSnapshotMatchesExplicitTitle(storedAgentStatus, explicitTitleAgentType) && (!eventAgentStatusSnapshot || eventAgentStatusSnapshot.stateStartedAt === storedAgentStatus.stateStartedAt) ) { diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts new file mode 100644 index 000000000000..99cb13fc2445 --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts @@ -0,0 +1,9 @@ +import { expect, it } from 'vitest' +import { isSeenHostReplay } from './agent-status-routing' + +it('lets a sleep replay carry an unseen clean completion but not its own interruption', () => { + const working = { state: 'working', stateStartedAt: 1_000 } + const slept = { isReplay: true, paneSleep: { ptyId: 'pty-1' }, stateStartedAt: 2_000 } as const + expect(isSeenHostReplay(slept, 'done', working)).toBe(false) + expect(isSeenHostReplay({ ...slept, interrupted: true }, 'done', working)).toBe(true) +}) diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.ts index bf7f50c1ba3f..156da3fd2fd4 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.ts @@ -36,7 +36,7 @@ export function isAgentStatusForRecentlyClosedTab( export function isSeenHostReplay( data: Pick< AgentStatusIpcPayload, - 'isReplay' | 'paneSleep' | 'stateStartedAt' | 'turnCompletedAt' | 'turnEndedAt' + 'isReplay' | 'paneSleep' | 'interrupted' | 'stateStartedAt' | 'turnCompletedAt' | 'turnEndedAt' >, state: string, existing: @@ -49,7 +49,8 @@ export function isSeenHostReplay( if (data.isReplay !== true) { return false } - if (data.paneSleep) { + // Sleep's own interruption is no new turn end; a clean completion it carries still counts. + if (data.paneSleep && data.interrupted === true) { return true } // Why: with no row there is no proof the turn was unseen, so keep seeding (no reload re-fires). diff --git a/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts b/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts index 3aff68652062..d60557386a51 100644 --- a/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts +++ b/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts @@ -17,23 +17,32 @@ import { // Every pane's acquisition shares this executor's process table: a burst of first hooks queues // behind four subprocess or proc reads instead of spawning one ps per pane at once. -const MAX_ACTIVE_HOOK_ROOT_READS = 4 +export function createHookProcessReadSlots(): PrioritySemaphore { + return new PrioritySemaphore(4) +} + +/** Each leaf read holds a slot only while it runs; an expired attempt's queued reads give up. */ +export function hookProcessReadGate( + slots: PrioritySemaphore, + signal?: AbortSignal +): ProcessReadGate { + return async (read) => { + const release = await slots.acquire(0, signal) + try { + return await read() + } finally { + release() + } + } +} /** Root evidence from this host's own processes, for panes whose PTY root `resolveRoot` names. */ export function createLocalHookRootEvidenceReader( resolveRoot: HookPaneProcessIo['resolveRoot'], - slots = new PrioritySemaphore(MAX_ACTIVE_HOOK_ROOT_READS) + slots = createHookProcessReadSlots() ): HookRootEvidenceReader { return (request) => { - // Each leaf read holds a slot only while it runs; an expired attempt's queued reads give up. - const gate: ProcessReadGate = async (read) => { - const release = await slots.acquire(0, request.signal) - try { - return await read() - } finally { - release() - } - } + const gate = hookProcessReadGate(slots, request.signal) const io: HookPaneProcessIo = { resolveRoot, probe: (process) => diff --git a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts index f6cd4e326254..b133a40149aa 100644 --- a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts +++ b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts @@ -78,7 +78,7 @@ export type HookPaneProcessIo = { } // Matches the bounded ancestry walk of the common pattern; a pane's agent sits a few levels below its root. -const MAX_ANCESTRY_DEPTH = 32 +export const MAX_ANCESTRY_DEPTH = 32 const MAX_TERMINAL_ROWS = 256 type Role = 'agent' | 'launcher' | 'other' | 'unknown' @@ -133,7 +133,7 @@ type Walk = 'reached' | 'outside' | 'nested' | 'unknown' * when the sender runs under a tmux server and the pane does not show an agent. */ type OtherTerminal = 'foreign' | 'bridged' | 'tmux' -function isTmuxServer(row: ProcessTableRow): boolean { +export function isTmuxServer(row: ProcessTableRow): boolean { const token = firstToken(row.command) return /^tmux:?$/.test(token.slice(token.lastIndexOf('/') + 1)) } @@ -231,7 +231,7 @@ export function classifyPaneHookProcess(input: { return role === 'shell' ? 'foreign' : 'bridged' } -async function collectRows( +export async function collectRows( io: Pick, rootPid: number, senderPid: number @@ -295,43 +295,6 @@ export async function readHookRootEvidence( return verdict === 'root' && root ? { verdict, binding: root.incarnation } : { verdict } } -/** Whether a tmux server, not the pane, keeps the pane's agent alive: a tmux client holds the - * pane's foreground and the agent's known process runs outside the pane. */ -export type PaneTmuxHostReader = (request: { - paneKey: string - worktreeId: string | undefined - process?: AgentProcessIdentity -}) => Promise - -export async function readPaneTmuxHost( - io: Pick, - request: Parameters[0] -): Promise { - const root = await io.resolveRoot(request.paneKey, request.worktreeId) - if (!root || root === 'legacy') { - return false - } - const rows = await collectRows(io, root.pid, request.process?.pid ?? root.pid) - if (!rows) { - return false - } - const rootRow = rows.find((row) => row.pid === root.pid) - if (!rootRow?.tpgid || rootRow.tpgid <= 0) { - return false - } - const shown = rows.some( - (row) => row.tty === rootRow.tty && row.pgid === rootRow.tpgid && isTmuxServer(row) - ) - let agent = request.process ? rows.find((row) => row.pid === request.process?.pid) : undefined - for (let depth = 0; shown && agent && depth < MAX_ANCESTRY_DEPTH; depth++) { - if (agent.pid === root.pid) { - return false - } - agent = agent.ppid > 1 ? rows.find((row) => row.pid === agent?.ppid) : undefined - } - return shown -} - async function readAgainstRoot( request: HookRootEvidenceRequest, io: HookPaneProcessIo, diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts new file mode 100644 index 000000000000..52147f8c1463 --- /dev/null +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -0,0 +1,65 @@ +import type { AgentProcessIdentity } from '../../agent-status/process/agent-process-presence' +import type { ProcessTableRow } from '../../process-observation/tables/process-table-snapshot' +import { + MAX_ANCESTRY_DEPTH, + collectRows, + isTmuxServer, + type HookPaneProcessIo +} from './hook-process-root-evidence' + +/** Whether a tmux server, not the pane, keeps the pane's agent alive: a tmux client holds the + * pane's foreground and the agent's known process runs outside the pane. */ +export type PaneTmuxHostReader = (request: { + paneKey: string + worktreeId: string | undefined + process?: AgentProcessIdentity +}) => Promise + +export async function readPaneTmuxHost( + io: Pick, + request: Parameters[0] +): Promise { + const root = await io.resolveRoot(request.paneKey, request.worktreeId) + if (!root || root === 'legacy') { + return false + } + const rows = await collectRows(io, root.pid, request.process?.pid ?? root.pid) + if (!rows) { + return false + } + const rootRow = rows.find((row) => row.pid === root.pid) + if (!rootRow?.tpgid || rootRow.tpgid <= 0) { + return false + } + const client = rows.find( + (row) => row.tty === rootRow.tty && row.pgid === rootRow.tpgid && isTmuxServer(row) + ) + if (!client) { + return false + } + // Without a process, only a pane holding nothing but the client and its shells proves it. + if (!request.process) { + const clientChain = new Set() + for (let row: ProcessTableRow | undefined = client; row && !clientChain.has(row.pid);) { + clientChain.add(row.pid) + const parent: number = row.ppid + row = rows.find((candidate) => candidate.pid === parent) + } + return rows.every( + (row) => row.tty !== rootRow.tty || clientChain.has(row.pid) || row.pgid === rootRow.tpgid + ) + } + // Only a complete ancestry outside the pane proves it; a missing row proves nothing. + let agent = rows.find((row) => row.pid === request.process?.pid) + for (let depth = 0; agent && depth < MAX_ANCESTRY_DEPTH; depth++) { + if (agent.pid === root.pid) { + return false + } + if (agent.ppid <= 1) { + return true + } + const parent = agent.ppid + agent = rows.find((row) => row.pid === parent) + } + return false +} diff --git a/src/shared/agent-status/lifecycle/agent-pane-sleep-status.test.ts b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.test.ts new file mode 100644 index 000000000000..48ab224ce8d8 --- /dev/null +++ b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.test.ts @@ -0,0 +1,21 @@ +import { expect, it } from 'vitest' +import { agentPaneSleepStatus } from './agent-pane-sleep-status' + +it('keeps a finished main agent verdict when sleep interrupts its children', () => { + const finished = { state: 'done', outcome: 'success', stateStartedAt: 10 } as const + expect(agentPaneSleepStatus({ state: 'working', mainAgent: finished }, 50)).toEqual({ + state: 'done', + interrupted: true, + mainAgent: finished + }) + expect( + agentPaneSleepStatus( + { state: 'working', mainAgent: { state: 'working', stateStartedAt: 10 } }, + 50 + ) + ).toEqual({ + state: 'done', + interrupted: true, + mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: 50 } + }) +}) diff --git a/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts index d963b75ed6c4..d81a1df119fa 100644 --- a/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts +++ b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts @@ -11,7 +11,7 @@ export function agentPaneSleepStatus< ...status, state: 'done', interrupted: true, - ...(status.mainAgent + ...(status.mainAgent && status.mainAgent.state !== 'done' ? { mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: at } } : {}) } From 147aef2aeca9b820d13edde9247e07f822f8998c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:50:08 -0800 Subject: [PATCH 049/125] Fix new-test types; forward the shell-alone proof option through the degraded daemon provider --- .../agent-hooks/runtime/agent-hook-runtime-deps.test.ts | 3 ++- .../providers/routing/degraded-daemon-pty-provider.ts | 7 +++++-- .../ipc-events/agent-status/agent-status-routing.test.ts | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.test.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.test.ts index 92e20d4e5087..989d73033e9c 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.test.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.test.ts @@ -3,6 +3,7 @@ import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { AgentHookServer } from '../server/agent-hook-server' import { selectFreshExplicitAgentStatusRow } from '../../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' import { agentHookRuntimeDeps } from './agent-hook-runtime-deps' +import { AgentStatusObservedPaneIdentities } from '../../runtime/terminal/identity/agent-status-observed-pane-identity' vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) @@ -34,7 +35,7 @@ it('keeps a dismissed running agent out of status readers', () => { server.dropStatusEntry(PANE) const rows = server.getStatusSnapshot() expect(rows).toMatchObject([{ paneKey: PANE, providerSessionOnly: true }]) - const deps = agentHookRuntimeDeps(server, { read: () => undefined }, () => ({})) + const deps = agentHookRuntimeDeps(server, new AgentStatusObservedPaneIdentities(), () => ({})) expect(deps.getAgentStatusSnapshot()).toEqual([]) expect( selectFreshExplicitAgentStatusRow({ handles: [], paneKeys: [PANE], hookRows: rows }) diff --git a/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts b/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts index b17d15d49033..a04de42254fc 100644 --- a/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts +++ b/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts @@ -207,8 +207,11 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { async confirmForegroundProcess(id: string): Promise { return this.providerFor(id).confirmForegroundProcess?.(id) ?? null } - async confirmShellForeground(id: string): Promise { - return (await this.providerFor(id).confirmShellForeground?.(id)) ?? false + async confirmShellForeground( + id: string, + options?: { noLiveDescendants?: boolean } + ): Promise { + return (await this.providerFor(id).confirmShellForeground?.(id, options)) ?? false } async serialize(ids: string[]): Promise { diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts index 99cb13fc2445..9f485fd3f229 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts @@ -2,7 +2,7 @@ import { expect, it } from 'vitest' import { isSeenHostReplay } from './agent-status-routing' it('lets a sleep replay carry an unseen clean completion but not its own interruption', () => { - const working = { state: 'working', stateStartedAt: 1_000 } + const working = { state: 'working', stateStartedAt: 1_000 } as const const slept = { isReplay: true, paneSleep: { ptyId: 'pty-1' }, stateStartedAt: 2_000 } as const expect(isSeenHostReplay(slept, 'done', working)).toBe(false) expect(isSeenHostReplay({ ...slept, interrupted: true }, 'done', working)).toBe(true) From a8e5278076ff036fbd9ccb51335b2831b06a7ce3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:54:49 -0800 Subject: [PATCH 050/125] End a resumed Claude's startup window at its SessionStart; swallow only Claude's startup OSC work --- .../server/pane-agent-turn-continuity.ts | 5 ++++- .../server/server-status-row-mutation.ts | 11 +++++++++-- .../persistence/server-pane-sleep.test.ts | 19 +++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index 94ad5946d951..336015bb3cb1 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -15,7 +15,10 @@ export function resumedAcceptedTurn( (incoming.payload.sessionBoundary === true || (origin === 'osc' && previous.observation?.origin === 'launch')) && (incoming.payload.state === 'done' || - (origin === 'osc' && incoming.payload.state === 'working')) && + // Only Claude restates startup work over OSC before its SessionStart. + (origin === 'osc' && + incoming.payload.state === 'working' && + incoming.payload.agentType === 'claude')) && incoming.toolAgentId === undefined && previous.payload.state === 'done' && previous.payload.sessionBoundary !== true && diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index 2c35e0acbb81..bc2f95819657 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -16,10 +16,17 @@ export abstract class AgentHookServerStatusRowMutation extends AgentHookServerSt before: EnrichedAgentHookEventPayload | undefined, origin: AgentStatusObservationOrigin ): EnrichedAgentHookEventPayload | null | undefined { - const resumed = previous && resumedAcceptedTurn(previous, incoming, origin) - if (!resumed) { + const accepted = previous && resumedAcceptedTurn(previous, incoming, origin) + if (!accepted) { return null } + // The CLI's own session start ends its startup; later terminal reports are new work. + const resumed = + origin === 'hook' && + incoming.payload.sessionBoundary === true && + accepted.observation?.origin === 'launch' + ? { ...accepted, observation: this.stampObservation(accepted, 'hook', Date.now()) } + : accepted if (!this.writeLegacyStatusRow(resumed)) { return undefined } diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 0c60973bba3c..3f3d79609a78 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -253,6 +253,25 @@ it.each(['retained', 'evicted'] as const)( } ) +it('shows hookless Claude work once its resumed session has started', async () => { + const working = `\x1b]7501;app=claude-code:state=working\x1b\\` + server.setHookRootEvidenceReader(async () => ({ verdict: 'root' })) + await agentHook('claude', 'UserPromptSubmit', 4001) + await agentHook('claude', 'Stop', 4001) + await sleepPane('claude', 'pty-1', 4001) + server.retireSleepingPaneOnSpawn(PANE, { + agentType: 'claude', + providerSession: { key: 'session_id', id: 'claude-session' } + }) + // Startup restates work before SessionStart; that is not a new turn. + ingestProgramStatusOsc(server, working) + expect(read()).toMatchObject({ state: 'done' }) + await agentHook('claude', 'SessionStart', 4002, 'resume') + // A hookless command such as /compact after startup is real work. + ingestProgramStatusOsc(server, working) + expect(read()).toMatchObject({ state: 'working' }) +}) + it.each(['claude', 'codex'] as const)( 'keeps a %s that never had a turn through sleep', async (agent) => { From da01c2a81e122c3e782138019d14da6f52cd862f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:08:14 -0800 Subject: [PATCH 051/125] Revert "End a resumed Claude's startup window at its SessionStart; swallow only Claude's startup OSC work" This reverts commit a8e5278076ff036fbd9ccb51335b2831b06a7ce3. --- .../server/pane-agent-turn-continuity.ts | 5 +---- .../server/server-status-row-mutation.ts | 11 ++--------- .../persistence/server-pane-sleep.test.ts | 19 ------------------- 3 files changed, 3 insertions(+), 32 deletions(-) diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index 336015bb3cb1..94ad5946d951 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -15,10 +15,7 @@ export function resumedAcceptedTurn( (incoming.payload.sessionBoundary === true || (origin === 'osc' && previous.observation?.origin === 'launch')) && (incoming.payload.state === 'done' || - // Only Claude restates startup work over OSC before its SessionStart. - (origin === 'osc' && - incoming.payload.state === 'working' && - incoming.payload.agentType === 'claude')) && + (origin === 'osc' && incoming.payload.state === 'working')) && incoming.toolAgentId === undefined && previous.payload.state === 'done' && previous.payload.sessionBoundary !== true && diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index bc2f95819657..2c35e0acbb81 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -16,17 +16,10 @@ export abstract class AgentHookServerStatusRowMutation extends AgentHookServerSt before: EnrichedAgentHookEventPayload | undefined, origin: AgentStatusObservationOrigin ): EnrichedAgentHookEventPayload | null | undefined { - const accepted = previous && resumedAcceptedTurn(previous, incoming, origin) - if (!accepted) { + const resumed = previous && resumedAcceptedTurn(previous, incoming, origin) + if (!resumed) { return null } - // The CLI's own session start ends its startup; later terminal reports are new work. - const resumed = - origin === 'hook' && - incoming.payload.sessionBoundary === true && - accepted.observation?.origin === 'launch' - ? { ...accepted, observation: this.stampObservation(accepted, 'hook', Date.now()) } - : accepted if (!this.writeLegacyStatusRow(resumed)) { return undefined } diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 3f3d79609a78..0c60973bba3c 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -253,25 +253,6 @@ it.each(['retained', 'evicted'] as const)( } ) -it('shows hookless Claude work once its resumed session has started', async () => { - const working = `\x1b]7501;app=claude-code:state=working\x1b\\` - server.setHookRootEvidenceReader(async () => ({ verdict: 'root' })) - await agentHook('claude', 'UserPromptSubmit', 4001) - await agentHook('claude', 'Stop', 4001) - await sleepPane('claude', 'pty-1', 4001) - server.retireSleepingPaneOnSpawn(PANE, { - agentType: 'claude', - providerSession: { key: 'session_id', id: 'claude-session' } - }) - // Startup restates work before SessionStart; that is not a new turn. - ingestProgramStatusOsc(server, working) - expect(read()).toMatchObject({ state: 'done' }) - await agentHook('claude', 'SessionStart', 4002, 'resume') - // A hookless command such as /compact after startup is real work. - ingestProgramStatusOsc(server, working) - expect(read()).toMatchObject({ state: 'working' }) -}) - it.each(['claude', 'codex'] as const)( 'keeps a %s that never had a turn through sleep', async (agent) => { From 3e42b2a57e25b7078f30e744cb63e42d9d4d4c7a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:22:18 -0800 Subject: [PATCH 052/125] End a resumed agent's startup window at the user's first submission; narrow the no-process tmux proof to agents; queue tmux reads behind hook admission --- .../observations/local-hook-root-evidence.ts | 4 ++-- .../server/pane-agent-turn-continuity.ts | 6 ++++-- .../server/server-status-inference.ts | 3 +++ .../server/server-status-row-mutation.ts | 8 +++++++- .../persistence/server-pane-sleep.test.ts | 20 +++++++++++++++++++ .../tmux/server-tmux-legacy-sleep.test.ts | 4 +++- .../hook-process-root-evidence-reader.ts | 5 +++-- .../presence/hook-process-root-evidence.ts | 2 +- .../presence/pane-tmux-host-proof.ts | 9 +++++++-- 9 files changed, 50 insertions(+), 11 deletions(-) diff --git a/src/main/agent-hooks/observations/local-hook-root-evidence.ts b/src/main/agent-hooks/observations/local-hook-root-evidence.ts index 9f6996093fc5..84d962a0858c 100644 --- a/src/main/agent-hooks/observations/local-hook-root-evidence.ts +++ b/src/main/agent-hooks/observations/local-hook-root-evidence.ts @@ -26,9 +26,9 @@ export function installLocalHookRootEvidence(server: AgentHookServer): LocalPtyI }) if (process.platform !== 'win32') { const resolveRoot = createLocalHookPaneRootResolver(readInventory) - // Root evidence and tmux host probes share one process-read budget. + // Root evidence and tmux host probes share one process-read budget; hook admission goes first. const slots = createHookProcessReadSlots() - const gate = hookProcessReadGate(slots) + const gate = hookProcessReadGate(slots, undefined, 1) server.setHookRootEvidenceReader( createLocalHookRootEvidenceReader(resolveRoot, slots), (request) => diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index 94ad5946d951..aaab076b4fa8 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -8,14 +8,16 @@ import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/ident export function resumedAcceptedTurn( previous: EnrichedAgentHookEventPayload, incoming: AgentHookEventPayload, - origin: AgentStatusObservationOrigin + origin: AgentStatusObservationOrigin, + /** No user submission since the launch: terminal work is still the CLI's own startup. */ + startupOpen = true ): EnrichedAgentHookEventPayload | null { const continuesTurn = (incoming.payload.agentType === 'claude' || previous.observation?.origin === 'launch') && (incoming.payload.sessionBoundary === true || (origin === 'osc' && previous.observation?.origin === 'launch')) && (incoming.payload.state === 'done' || - (origin === 'osc' && incoming.payload.state === 'working')) && + (origin === 'osc' && incoming.payload.state === 'working' && startupOpen)) && incoming.toolAgentId === undefined && previous.payload.state === 'done' && previous.payload.sessionBoundary !== true && diff --git a/src/main/agent-hooks/server/server-status-inference.ts b/src/main/agent-hooks/server/server-status-inference.ts index 29f0b9ba1e6e..92b072326e7f 100644 --- a/src/main/agent-hooks/server/server-status-inference.ts +++ b/src/main/agent-hooks/server/server-status-inference.ts @@ -62,6 +62,9 @@ export abstract class AgentHookServerStatusInference extends AgentHookServerQues observeClaudeTerminalEvidence(paneKey: string, evidence: ClaudeTerminalEvidence): void { if (evidence.kind === 'input') { this.programStatusFacets.noteInput(paneKey) + if (/[\r\n]/.test(evidence.data)) { + this.lastSubmittedAtByPaneKey.set(paneKey, Date.now()) + } } this.claudeTerminalInterrupts.observe(paneKey, evidence) } diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index 2c35e0acbb81..9b9185ff82ad 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -10,13 +10,19 @@ import { ClaudeOwedNotificationExpiryTimers } from '../../../shared/agent-hook-l import { AgentHookServerStatusApplication } from './server-status-application' export abstract class AgentHookServerStatusRowMutation extends AgentHookServerStatusApplication { + /** When the user last submitted a line in each pane; a resumed CLI's startup ends there. */ + protected readonly lastSubmittedAtByPaneKey = new Map() + protected preserveAcceptedTurn( previous: EnrichedAgentHookEventPayload | undefined, incoming: AgentHookEventPayload, before: EnrichedAgentHookEventPayload | undefined, origin: AgentStatusObservationOrigin ): EnrichedAgentHookEventPayload | null | undefined { - const resumed = previous && resumedAcceptedTurn(previous, incoming, origin) + const submittedAt = previous && this.lastSubmittedAtByPaneKey.get(previous.paneKey) + const startupOpen = + submittedAt === undefined || submittedAt < (previous?.observation?.observedAt ?? 0) + const resumed = previous && resumedAcceptedTurn(previous, incoming, origin, startupOpen) if (!resumed) { return null } diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 0c60973bba3c..171a6943b396 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -253,6 +253,26 @@ it.each(['retained', 'evicted'] as const)( } ) +it('shows hookless work the user submits after a resumed agent starts', async () => { + const working = `\x1b]7501;app=claude-code:state=working\x1b\\` + server.setHookRootEvidenceReader(async () => ({ verdict: 'root' })) + await agentHook('claude', 'UserPromptSubmit', 4001) + await agentHook('claude', 'Stop', 4001) + await sleepPane('claude', 'pty-1', 4001) + server.retireSleepingPaneOnSpawn(PANE, { + agentType: 'claude', + providerSession: { key: 'session_id', id: 'claude-session' } + }) + // The resumed CLI's own startup work is not a new turn. + ingestProgramStatusOsc(server, working) + expect(read()).toMatchObject({ state: 'done' }) + vi.setSystemTime(Date.now() + 1_000) + // A hookless command such as /compact is. + server.observeClaudeTerminalEvidence(PANE, { kind: 'input', data: '/compact\r' }) + ingestProgramStatusOsc(server, working) + expect(read()).toMatchObject({ state: 'working' }) +}) + it.each(['claude', 'codex'] as const)( 'keeps a %s that never had a turn through sleep', async (agent) => { diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 6f60a3762ee9..c8aab36d150c 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -219,9 +219,11 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => runningPane(4050, CLIENT, ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) await expect(readPaneTmuxHost(io, agent)).resolves.toBe(true) - // The pane's own suspended agent stays behind an unrelated tmux client. + // The pane's own suspended agent stays behind an unrelated tmux client; other jobs don't matter. runningPane(4050, CLIENT, [4060, 101, 4060, 'claude', 'T'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + runningPane(4050, CLIENT, [4070, 101, 4070, 'sleep 9999'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) // An agent whose ancestry cannot be read is not proven to live outside the pane. runningPane(4050, CLIENT, [4043, 4042, 4043, 'claude', 'S+', 'ttys011']) await expect(readPaneTmuxHost(io, agent)).resolves.toBe(false) diff --git a/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts b/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts index d60557386a51..c7844b3bec00 100644 --- a/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts +++ b/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts @@ -24,10 +24,11 @@ export function createHookProcessReadSlots(): PrioritySemaphore { /** Each leaf read holds a slot only while it runs; an expired attempt's queued reads give up. */ export function hookProcessReadGate( slots: PrioritySemaphore, - signal?: AbortSignal + signal?: AbortSignal, + priority = 0 ): ProcessReadGate { return async (read) => { - const release = await slots.acquire(0, signal) + const release = await slots.acquire(priority, signal) try { return await read() } finally { diff --git a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts index b133a40149aa..ead34fd15ed4 100644 --- a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts +++ b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts @@ -83,7 +83,7 @@ const MAX_TERMINAL_ROWS = 256 type Role = 'agent' | 'launcher' | 'other' | 'unknown' -function agentOf(command: string): string | undefined { +export function agentOf(command: string): string | undefined { const recognized = recognizeAgentProcessFromCommandLine(command, { includeHeadlessOneShot: true }) if (recognized) { return recognized.agent diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index 52147f8c1463..6bbe7a219b9c 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -2,6 +2,7 @@ import type { AgentProcessIdentity } from '../../agent-status/process/agent-proc import type { ProcessTableRow } from '../../process-observation/tables/process-table-snapshot' import { MAX_ANCESTRY_DEPTH, + agentOf, collectRows, isTmuxServer, type HookPaneProcessIo @@ -37,7 +38,7 @@ export async function readPaneTmuxHost( if (!client) { return false } - // Without a process, only a pane holding nothing but the client and its shells proves it. + // Without a process, a pane whose own agent sits beside the client (a stopped job) proves nothing. if (!request.process) { const clientChain = new Set() for (let row: ProcessTableRow | undefined = client; row && !clientChain.has(row.pid);) { @@ -46,7 +47,11 @@ export async function readPaneTmuxHost( row = rows.find((candidate) => candidate.pid === parent) } return rows.every( - (row) => row.tty !== rootRow.tty || clientChain.has(row.pid) || row.pgid === rootRow.tpgid + (row) => + row.tty !== rootRow.tty || + clientChain.has(row.pid) || + row.pgid === rootRow.tpgid || + agentOf(row.command) === undefined ) } // Only a complete ancestry outside the pane proves it; a missing row proves nothing. From 59b0ab419eac79b9b7d6cab1f8e03402cfff319c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:23:33 -0800 Subject: [PATCH 053/125] Let a sleep replay carry a finished main agent's completion --- .../agent-status/agent-status-routing.test.ts | 5 +++++ .../agent-status/agent-status-routing.ts | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts index 9f485fd3f229..587efb904735 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.test.ts @@ -6,4 +6,9 @@ it('lets a sleep replay carry an unseen clean completion but not its own interru const slept = { isReplay: true, paneSleep: { ptyId: 'pty-1' }, stateStartedAt: 2_000 } as const expect(isSeenHostReplay(slept, 'done', working)).toBe(false) expect(isSeenHostReplay({ ...slept, interrupted: true }, 'done', working)).toBe(true) + // Sleep cut only children short: the main agent's own completion is still unseen. + const finished = { state: 'done', outcome: 'success', stateStartedAt: 1_500 } as const + expect( + isSeenHostReplay({ ...slept, interrupted: true, mainAgent: finished }, 'done', working) + ).toBe(false) }) diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.ts index 156da3fd2fd4..6e2b5a9f4bd6 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-routing.ts @@ -36,7 +36,13 @@ export function isAgentStatusForRecentlyClosedTab( export function isSeenHostReplay( data: Pick< AgentStatusIpcPayload, - 'isReplay' | 'paneSleep' | 'interrupted' | 'stateStartedAt' | 'turnCompletedAt' | 'turnEndedAt' + | 'isReplay' + | 'paneSleep' + | 'interrupted' + | 'mainAgent' + | 'stateStartedAt' + | 'turnCompletedAt' + | 'turnEndedAt' >, state: string, existing: @@ -49,8 +55,12 @@ export function isSeenHostReplay( if (data.isReplay !== true) { return false } - // Sleep's own interruption is no new turn end; a clean completion it carries still counts. - if (data.paneSleep && data.interrupted === true) { + // Sleep's own interruption is no new turn end; a completion it carries still counts. + if ( + data.paneSleep && + data.interrupted === true && + (data.mainAgent === undefined || data.mainAgent.outcome === 'cancellation') + ) { return true } // Why: with no row there is no proof the turn was unseen, so keep seeding (no reload re-fires). From 1051d3947069fe82cd0dc9bffc5d02bba2a3d15b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:33:10 -0800 Subject: [PATCH 054/125] Record a submitted line for every pane so remote panes end a resumed agent's startup too --- .../agent-hooks/runtime/agent-hook-runtime-deps.ts | 1 + src/main/agent-hooks/server/server-status-inference.ts | 3 --- .../agent-hooks/server/server-status-row-mutation.ts | 4 ++++ .../testing/persistence/server-pane-sleep.test.ts | 2 +- src/main/ipc/pty/ipc/write-input.ts | 3 +++ src/main/ipc/pty/runtime/operations.ts | 3 +++ .../construction/runtime-construction-dependencies.ts | 2 ++ src/main/runtime/construction/runtime-construction.ts | 1 + src/main/runtime/construction/runtime-host-services.ts | 2 ++ .../terminal/output/terminal-title-observation.ts | 10 ++++++++++ 10 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index 6b01868ce1a4..cfa6e28ac038 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -16,6 +16,7 @@ export function agentHookRuntimeDeps( onTerminalProgramStatusFacet: (event) => server.ingestProgramStatusFacet(event), onClaudeTerminalEvidence: (paneKey, evidence) => server.observeClaudeTerminalEvidence(paneKey, evidence), + onPaneInputSubmitted: (paneKey) => server.notePaneInputSubmitted(paneKey), getPaneAgentIdentity: (paneKey, savedRecord) => server.paneAgentIdentity(paneKey, savedRecord), getAgentStatusSnapshot: () => server.getStatusSnapshot().flatMap((row) => { diff --git a/src/main/agent-hooks/server/server-status-inference.ts b/src/main/agent-hooks/server/server-status-inference.ts index 92b072326e7f..29f0b9ba1e6e 100644 --- a/src/main/agent-hooks/server/server-status-inference.ts +++ b/src/main/agent-hooks/server/server-status-inference.ts @@ -62,9 +62,6 @@ export abstract class AgentHookServerStatusInference extends AgentHookServerQues observeClaudeTerminalEvidence(paneKey: string, evidence: ClaudeTerminalEvidence): void { if (evidence.kind === 'input') { this.programStatusFacets.noteInput(paneKey) - if (/[\r\n]/.test(evidence.data)) { - this.lastSubmittedAtByPaneKey.set(paneKey, Date.now()) - } } this.claudeTerminalInterrupts.observe(paneKey, evidence) } diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index 9b9185ff82ad..43e13b99bfe6 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -13,6 +13,10 @@ export abstract class AgentHookServerStatusRowMutation extends AgentHookServerSt /** When the user last submitted a line in each pane; a resumed CLI's startup ends there. */ protected readonly lastSubmittedAtByPaneKey = new Map() + notePaneInputSubmitted(paneKey: string): void { + this.lastSubmittedAtByPaneKey.set(this.resolvePaneKeyAlias(paneKey), Date.now()) + } + protected preserveAcceptedTurn( previous: EnrichedAgentHookEventPayload | undefined, incoming: AgentHookEventPayload, diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index 171a6943b396..e2e04d753f2a 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -268,7 +268,7 @@ it('shows hookless work the user submits after a resumed agent starts', async () expect(read()).toMatchObject({ state: 'done' }) vi.setSystemTime(Date.now() + 1_000) // A hookless command such as /compact is. - server.observeClaudeTerminalEvidence(PANE, { kind: 'input', data: '/compact\r' }) + server.notePaneInputSubmitted(PANE) ingestProgramStatusOsc(server, working) expect(read()).toMatchObject({ state: 'working' }) }) diff --git a/src/main/ipc/pty/ipc/write-input.ts b/src/main/ipc/pty/ipc/write-input.ts index 1e803f7ef110..85c29b38975c 100644 --- a/src/main/ipc/pty/ipc/write-input.ts +++ b/src/main/ipc/pty/ipc/write-input.ts @@ -241,6 +241,9 @@ export function createPtyWriteInput(deps: { ) { runtime?.observeClaudeTerminalEvidence?.(args.id, { kind: 'input', data: args.data }) } + if (accepted && args.inputKind === 'driving') { + runtime?.notePtyInputSubmitted?.(args.id, args.data) + } return accepted } const result = writePtyProviderInput(provider, args, verify) diff --git a/src/main/ipc/pty/runtime/operations.ts b/src/main/ipc/pty/runtime/operations.ts index 5bb75bbac0f8..d90425bcde69 100644 --- a/src/main/ipc/pty/runtime/operations.ts +++ b/src/main/ipc/pty/runtime/operations.ts @@ -48,6 +48,9 @@ export function writePtyFromRuntimeController( if (isDrivingInputKind(inputKind) && ptyOwnership.get(ptyId) === LOCAL_EXECUTION_HOST_ID) { deps.runtime?.observeClaudeTerminalEvidence?.(ptyId, { kind: 'input', data }) } + if (isDrivingInputKind(inputKind)) { + deps.runtime?.notePtyInputSubmitted?.(ptyId, data) + } } let provider: IPtyProvider try { diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index ba5b4025bd52..5898ed182131 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -38,6 +38,8 @@ export type RuntimeConstructionDependencies = { onTerminalProgramStatusFacet?: (event: RuntimeTerminalProgramStatusFacetEvent) => void onTerminalSideEffects?: (batch: TerminalSideEffectBatch) => void onClaudeTerminalEvidence?: (paneKey: string, evidence: ClaudeTerminalEvidence) => void + /** A line the user submitted in a pane, on any host. */ + onPaneInputSubmitted?: (paneKey: string) => void getPaneAgentIdentity?: ( paneKey: string, savedRecord?: SleepingAgentSessionRecord diff --git a/src/main/runtime/construction/runtime-construction.ts b/src/main/runtime/construction/runtime-construction.ts index 9328155418bd..37929e44ebf7 100644 --- a/src/main/runtime/construction/runtime-construction.ts +++ b/src/main/runtime/construction/runtime-construction.ts @@ -292,6 +292,7 @@ export abstract class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCo this.onTerminalAgentStatus = deps?.onTerminalAgentStatus ?? null this.onTerminalProgramStatusFacet = deps?.onTerminalProgramStatusFacet ?? null this.onClaudeTerminalEvidence = deps?.onClaudeTerminalEvidence ?? null + this.onPaneInputSubmitted = deps?.onPaneInputSubmitted ?? null this.buildAgentHookPtyEnv = deps?.buildAgentHookPtyEnv ?? null this.getDesktopWindowStatusFn = deps?.getDesktopWindowStatus ?? (() => 'openable') this.headlessTerminalScrollbackRows = diff --git a/src/main/runtime/construction/runtime-host-services.ts b/src/main/runtime/construction/runtime-host-services.ts index f993253e0b24..3b246ed554d4 100644 --- a/src/main/runtime/construction/runtime-host-services.ts +++ b/src/main/runtime/construction/runtime-host-services.ts @@ -104,6 +104,8 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends RuntimeAgent protected readonly onClaudeTerminalEvidence!: HostBindings['onClaudeTerminalEvidence'] | null + protected onPaneInputSubmitted: HostBindings['onPaneInputSubmitted'] | null = null + protected terminalSideEffectLocalConsumerAvailable = false protected terminalSideEffectConsumerAvailable = false diff --git a/src/main/runtime/terminal/output/terminal-title-observation.ts b/src/main/runtime/terminal/output/terminal-title-observation.ts index ecf30e4b2173..c18dace48f2e 100644 --- a/src/main/runtime/terminal/output/terminal-title-observation.ts +++ b/src/main/runtime/terminal/output/terminal-title-observation.ts @@ -45,6 +45,16 @@ export abstract class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWit /** A title moved a terminal agent to another status; worktree.ps rows show it without a hook row. */ protected abstract onTitleAgentStatusChanged(): void + /** A submitted line ends a resumed agent's startup on every host, remote panes included. */ + notePtyInputSubmitted(ptyId: string, data: string): void { + if (!this.onPaneInputSubmitted || !/[\r\n]/.test(data)) { + return + } + for (const paneKey of this.collectPaneKeysForPty(ptyId)) { + this.onPaneInputSubmitted(paneKey) + } + } + observeClaudeTerminalEvidence(ptyId: string, evidence: ClaudeTerminalEvidence): void { if (!this.onClaudeTerminalEvidence || this.ptysById.get(ptyId)?.connectionId) { return From 3aa32e5fe6357c9dcf0bc25c9588eb1910b742df Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:37:00 -0800 Subject: [PATCH 055/125] Count only Enter as a submission, prune it with the pane, and refuse unreadable jobs as tmux proof --- .../agent-hooks/server/server-status-row-mutation.ts | 10 +++++++++- src/main/agent-hooks/server/server-tab-cleanup.ts | 1 + .../testing/tmux/server-tmux-legacy-sleep.test.ts | 3 +++ .../terminal/output/terminal-input-submission.test.ts | 10 ++++++++++ .../terminal/output/terminal-input-submission.ts | 9 +++++++++ .../terminal/output/terminal-title-observation.ts | 3 ++- .../presence/pane-tmux-host-proof.ts | 7 +++++-- 7 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 src/main/runtime/terminal/output/terminal-input-submission.test.ts create mode 100644 src/main/runtime/terminal/output/terminal-input-submission.ts diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index 43e13b99bfe6..b75eca2790bd 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -13,8 +13,16 @@ export abstract class AgentHookServerStatusRowMutation extends AgentHookServerSt /** When the user last submitted a line in each pane; a resumed CLI's startup ends there. */ protected readonly lastSubmittedAtByPaneKey = new Map() + /** Kept only while a resumed row's startup window is open; pane teardown forgets it. */ notePaneInputSubmitted(paneKey: string): void { - this.lastSubmittedAtByPaneKey.set(this.resolvePaneKeyAlias(paneKey), Date.now()) + const resolved = this.resolvePaneKeyAlias(paneKey) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. + const row = this.state.lastStatusByPaneKey.get(resolved) as + | EnrichedAgentHookEventPayload + | undefined + if (row?.observation?.origin === 'launch') { + this.lastSubmittedAtByPaneKey.set(resolved, Date.now()) + } } protected preserveAcceptedTurn( diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index d865ded30279..1f61d8f5466d 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -246,6 +246,7 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } ): void { const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey) + this.lastSubmittedAtByPaneKey.delete(resolvedPaneKey) if (options?.forgetAgentExit) { this.forgetAgentExit(paneKey) } diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index c8aab36d150c..2a8f4f670749 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -224,6 +224,9 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane(4050, CLIENT, [4070, 101, 4070, 'sleep 9999'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) + // An unreadable job might be the pane's own agent. + runningPane(4050, CLIENT, [4080, 101, 4080, '(claude)', 'T'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) // An agent whose ancestry cannot be read is not proven to live outside the pane. runningPane(4050, CLIENT, [4043, 4042, 4043, 'claude', 'S+', 'ttys011']) await expect(readPaneTmuxHost(io, agent)).resolves.toBe(false) diff --git a/src/main/runtime/terminal/output/terminal-input-submission.test.ts b/src/main/runtime/terminal/output/terminal-input-submission.test.ts new file mode 100644 index 000000000000..13efe9063d84 --- /dev/null +++ b/src/main/runtime/terminal/output/terminal-input-submission.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from 'vitest' +import { isSubmittedTerminalInput } from './terminal-input-submission' + +it('counts Enter as a submission but not pasted or modified newlines', () => { + expect(isSubmittedTerminalInput('/compact\r')).toBe(true) + expect(isSubmittedTerminalInput('\r')).toBe(true) + expect(isSubmittedTerminalInput('\x1b[200~draft\ncontinued\r\x1b[201~')).toBe(false) + expect(isSubmittedTerminalInput('\x1b\r')).toBe(false) + expect(isSubmittedTerminalInput('draft\n')).toBe(false) +}) diff --git a/src/main/runtime/terminal/output/terminal-input-submission.ts b/src/main/runtime/terminal/output/terminal-input-submission.ts new file mode 100644 index 000000000000..500d9485ca3a --- /dev/null +++ b/src/main/runtime/terminal/output/terminal-input-submission.ts @@ -0,0 +1,9 @@ +// oxlint-disable-next-line no-control-regex -- SAFETY: bracketed-paste framing is ESC-based. +const PASTED_TEXT = /\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)/g +// oxlint-disable-next-line no-control-regex -- SAFETY: Alt/Shift+Enter arrive as ESC CR. +const PLAIN_ENTER = /(?:^|[^\x1b])\r/ + +/** Enter submits a line; pasted text and Alt/Shift+Enter (ESC CR) only edit the draft. */ +export function isSubmittedTerminalInput(data: string): boolean { + return PLAIN_ENTER.test(data.replace(PASTED_TEXT, '')) +} diff --git a/src/main/runtime/terminal/output/terminal-title-observation.ts b/src/main/runtime/terminal/output/terminal-title-observation.ts index c18dace48f2e..a8807c5c2e49 100644 --- a/src/main/runtime/terminal/output/terminal-title-observation.ts +++ b/src/main/runtime/terminal/output/terminal-title-observation.ts @@ -1,3 +1,4 @@ +import { isSubmittedTerminalInput } from './terminal-input-submission' import type { AgentStatus } from '../../../../shared/agent-status/title/agent-title-core' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' import { OrcaRuntimeWithGetUnpersistedTrackedTitleForPty } from './terminal-title-tracker' @@ -47,7 +48,7 @@ export abstract class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWit /** A submitted line ends a resumed agent's startup on every host, remote panes included. */ notePtyInputSubmitted(ptyId: string, data: string): void { - if (!this.onPaneInputSubmitted || !/[\r\n]/.test(data)) { + if (!this.onPaneInputSubmitted || !isSubmittedTerminalInput(data)) { return } for (const paneKey of this.collectPaneKeysForPty(ptyId)) { diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index 6bbe7a219b9c..367d78350a81 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -1,5 +1,8 @@ import type { AgentProcessIdentity } from '../../agent-status/process/agent-process-presence' -import type { ProcessTableRow } from '../../process-observation/tables/process-table-snapshot' +import { + unreadableArgvName, + type ProcessTableRow +} from '../../process-observation/tables/process-table-snapshot' import { MAX_ANCESTRY_DEPTH, agentOf, @@ -51,7 +54,7 @@ export async function readPaneTmuxHost( row.tty !== rootRow.tty || clientChain.has(row.pid) || row.pgid === rootRow.tpgid || - agentOf(row.command) === undefined + (unreadableArgvName(row.command) === null && agentOf(row.command) === undefined) ) } // Only a complete ancestry outside the pane proves it; a missing row proves nothing. From d115983402ca75e0ecd90bec3afc206ca8b7345a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:54:09 -0800 Subject: [PATCH 056/125] Keep paste framing across writes and drop submission marks of closed panes --- .../server/server-status-row-mutation.ts | 11 ++++- .../output/terminal-input-submission.test.ts | 22 +++++++--- .../output/terminal-input-submission.ts | 40 +++++++++++++++---- .../output/terminal-title-observation.ts | 7 +++- 4 files changed, 63 insertions(+), 17 deletions(-) diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index b75eca2790bd..cc1f1ed4f989 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -20,9 +20,16 @@ export abstract class AgentHookServerStatusRowMutation extends AgentHookServerSt const row = this.state.lastStatusByPaneKey.get(resolved) as | EnrichedAgentHookEventPayload | undefined - if (row?.observation?.origin === 'launch') { - this.lastSubmittedAtByPaneKey.set(resolved, Date.now()) + if (row?.observation?.origin !== 'launch') { + return } + // Panes whose rows are gone (closed tabs) leave with the next submission. + for (const key of this.lastSubmittedAtByPaneKey.keys()) { + if (!this.state.lastStatusByPaneKey.has(key)) { + this.lastSubmittedAtByPaneKey.delete(key) + } + } + this.lastSubmittedAtByPaneKey.set(resolved, Date.now()) } protected preserveAcceptedTurn( diff --git a/src/main/runtime/terminal/output/terminal-input-submission.test.ts b/src/main/runtime/terminal/output/terminal-input-submission.test.ts index 13efe9063d84..43aeacdffcda 100644 --- a/src/main/runtime/terminal/output/terminal-input-submission.test.ts +++ b/src/main/runtime/terminal/output/terminal-input-submission.test.ts @@ -1,10 +1,20 @@ import { expect, it } from 'vitest' -import { isSubmittedTerminalInput } from './terminal-input-submission' +import { scanTerminalInputSubmission } from './terminal-input-submission' it('counts Enter as a submission but not pasted or modified newlines', () => { - expect(isSubmittedTerminalInput('/compact\r')).toBe(true) - expect(isSubmittedTerminalInput('\r')).toBe(true) - expect(isSubmittedTerminalInput('\x1b[200~draft\ncontinued\r\x1b[201~')).toBe(false) - expect(isSubmittedTerminalInput('\x1b\r')).toBe(false) - expect(isSubmittedTerminalInput('draft\n')).toBe(false) + expect(scanTerminalInputSubmission('/compact\r', false)).toEqual({ + submitted: true, + pasteOpen: false + }) + expect(scanTerminalInputSubmission('\x1b\r', false).submitted).toBe(false) + expect(scanTerminalInputSubmission('draft\n', false).submitted).toBe(false) + // A chunked paste keeps its framing across writes. + const opened = scanTerminalInputSubmission('\x1b[200~', false) + expect(opened).toEqual({ submitted: false, pasteOpen: true }) + const body = scanTerminalInputSubmission('draft\rcontinued', opened.pasteOpen) + expect(body).toEqual({ submitted: false, pasteOpen: true }) + expect(scanTerminalInputSubmission('\x1b[201~', body.pasteOpen)).toEqual({ + submitted: false, + pasteOpen: false + }) }) diff --git a/src/main/runtime/terminal/output/terminal-input-submission.ts b/src/main/runtime/terminal/output/terminal-input-submission.ts index 500d9485ca3a..528783bfea2e 100644 --- a/src/main/runtime/terminal/output/terminal-input-submission.ts +++ b/src/main/runtime/terminal/output/terminal-input-submission.ts @@ -1,9 +1,35 @@ -// oxlint-disable-next-line no-control-regex -- SAFETY: bracketed-paste framing is ESC-based. -const PASTED_TEXT = /\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)/g -// oxlint-disable-next-line no-control-regex -- SAFETY: Alt/Shift+Enter arrive as ESC CR. -const PLAIN_ENTER = /(?:^|[^\x1b])\r/ +const PASTE_START = '\x1b[200~' +const PASTE_END = '\x1b[201~' -/** Enter submits a line; pasted text and Alt/Shift+Enter (ESC CR) only edit the draft. */ -export function isSubmittedTerminalInput(data: string): boolean { - return PLAIN_ENTER.test(data.replace(PASTED_TEXT, '')) +/** Enter submits a line; pasted text (its framing can span writes) and Alt/Shift+Enter (ESC CR) + * only edit the draft. */ +export function scanTerminalInputSubmission( + data: string, + pasteOpen: boolean +): { submitted: boolean; pasteOpen: boolean } { + let open = pasteOpen + let submitted = false + for (let i = 0; i < data.length; i++) { + if (data.startsWith(PASTE_START, i)) { + open = true + i += PASTE_START.length - 1 + } else if (data.startsWith(PASTE_END, i)) { + open = false + i += PASTE_END.length - 1 + } else if (!open && data[i] === '\r' && data[i - 1] !== '\x1b') { + submitted = true + } + } + return { submitted, pasteOpen: open } +} + +/** Bracketed-paste framing per live PTY record; it can span accepted writes. */ +export class TerminalInputSubmissions { + private readonly pasteOpenByPty = new WeakMap() + + submitted(pty: object, data: string): boolean { + const scan = scanTerminalInputSubmission(data, this.pasteOpenByPty.get(pty) === true) + this.pasteOpenByPty.set(pty, scan.pasteOpen) + return scan.submitted + } } diff --git a/src/main/runtime/terminal/output/terminal-title-observation.ts b/src/main/runtime/terminal/output/terminal-title-observation.ts index a8807c5c2e49..0de6d9ddbc00 100644 --- a/src/main/runtime/terminal/output/terminal-title-observation.ts +++ b/src/main/runtime/terminal/output/terminal-title-observation.ts @@ -1,4 +1,4 @@ -import { isSubmittedTerminalInput } from './terminal-input-submission' +import { TerminalInputSubmissions } from './terminal-input-submission' import type { AgentStatus } from '../../../../shared/agent-status/title/agent-title-core' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' import { OrcaRuntimeWithGetUnpersistedTrackedTitleForPty } from './terminal-title-tracker' @@ -46,9 +46,12 @@ export abstract class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWit /** A title moved a terminal agent to another status; worktree.ps rows show it without a hook row. */ protected abstract onTitleAgentStatusChanged(): void + private readonly inputSubmissions = new TerminalInputSubmissions() + /** A submitted line ends a resumed agent's startup on every host, remote panes included. */ notePtyInputSubmitted(ptyId: string, data: string): void { - if (!this.onPaneInputSubmitted || !isSubmittedTerminalInput(data)) { + const pty = this.ptysById.get(ptyId) + if (!this.onPaneInputSubmitted || !pty || !this.inputSubmissions.submitted(pty, data)) { return } for (const paneKey of this.collectPaneKeysForPty(ptyId)) { From 6064a056c84ff368425588063a132898ebba1bfb Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:56:42 -0800 Subject: [PATCH 057/125] Forget a closed tab's submission marks with its other pane caches --- src/main/agent-hooks/server/server-tab-cleanup.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 1f61d8f5466d..8fc04b23f785 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -207,6 +207,7 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { this.restartedStatusLaunchTokenHashByPaneKey.delete(paneKey) this.evidenceObservedAtByPaneKey.delete(paneKey) this.programStatusFacets.delete(paneKey) + this.lastSubmittedAtByPaneKey.delete(paneKey) this.hookSilenceRechecks.cancel(paneKey) this.programStatusFacetRepublishes.cancel(paneKey) } From 82d4299a57aec726096af534696b48678b2f3ed3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:05:55 -0800 Subject: [PATCH 058/125] Judge a submission from the write alone and bound remembered submissions --- .../server/server-status-row-mutation.ts | 14 ++++--- .../output/terminal-input-submission.test.ts | 26 +++++-------- .../output/terminal-input-submission.ts | 39 +++---------------- .../output/terminal-title-observation.ts | 7 +--- 4 files changed, 27 insertions(+), 59 deletions(-) diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index cc1f1ed4f989..c13f7c74e7d4 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -9,6 +9,8 @@ import { ClaudeOwedNotificationExpiryTimers } from '../../../shared/agent-hook-l import { AgentHookServerStatusApplication } from './server-status-application' +const MAX_REMEMBERED_SUBMISSIONS = 1_000 + export abstract class AgentHookServerStatusRowMutation extends AgentHookServerStatusApplication { /** When the user last submitted a line in each pane; a resumed CLI's startup ends there. */ protected readonly lastSubmittedAtByPaneKey = new Map() @@ -23,13 +25,15 @@ export abstract class AgentHookServerStatusRowMutation extends AgentHookServerSt if (row?.observation?.origin !== 'launch') { return } - // Panes whose rows are gone (closed tabs) leave with the next submission. - for (const key of this.lastSubmittedAtByPaneKey.keys()) { - if (!this.state.lastStatusByPaneKey.has(key)) { - this.lastSubmittedAtByPaneKey.delete(key) + // Pane teardown forgets marks; the oldest go first if panes outrun that. + this.lastSubmittedAtByPaneKey.delete(resolved) + this.lastSubmittedAtByPaneKey.set(resolved, Date.now()) + if (this.lastSubmittedAtByPaneKey.size > MAX_REMEMBERED_SUBMISSIONS) { + const oldest = this.lastSubmittedAtByPaneKey.keys().next().value + if (oldest !== undefined) { + this.lastSubmittedAtByPaneKey.delete(oldest) } } - this.lastSubmittedAtByPaneKey.set(resolved, Date.now()) } protected preserveAcceptedTurn( diff --git a/src/main/runtime/terminal/output/terminal-input-submission.test.ts b/src/main/runtime/terminal/output/terminal-input-submission.test.ts index 43aeacdffcda..bec818ab16d3 100644 --- a/src/main/runtime/terminal/output/terminal-input-submission.test.ts +++ b/src/main/runtime/terminal/output/terminal-input-submission.test.ts @@ -1,20 +1,14 @@ import { expect, it } from 'vitest' -import { scanTerminalInputSubmission } from './terminal-input-submission' +import { isSubmittedTerminalInput } from './terminal-input-submission' it('counts Enter as a submission but not pasted or modified newlines', () => { - expect(scanTerminalInputSubmission('/compact\r', false)).toEqual({ - submitted: true, - pasteOpen: false - }) - expect(scanTerminalInputSubmission('\x1b\r', false).submitted).toBe(false) - expect(scanTerminalInputSubmission('draft\n', false).submitted).toBe(false) - // A chunked paste keeps its framing across writes. - const opened = scanTerminalInputSubmission('\x1b[200~', false) - expect(opened).toEqual({ submitted: false, pasteOpen: true }) - const body = scanTerminalInputSubmission('draft\rcontinued', opened.pasteOpen) - expect(body).toEqual({ submitted: false, pasteOpen: true }) - expect(scanTerminalInputSubmission('\x1b[201~', body.pasteOpen)).toEqual({ - submitted: false, - pasteOpen: false - }) + expect(isSubmittedTerminalInput('\r')).toBe(true) + expect(isSubmittedTerminalInput('/compact\r')).toBe(true) + expect(isSubmittedTerminalInput('\x1b\r')).toBe(false) + expect(isSubmittedTerminalInput('draft\n')).toBe(false) + // Each chunk of a large paste: its opening frame, a body ending in CR, a split closing frame. + expect(isSubmittedTerminalInput('\x1b[200~')).toBe(false) + expect(isSubmittedTerminalInput(`${'x'.repeat(16_383)}\r`)).toBe(false) + expect(isSubmittedTerminalInput('\x1b[')).toBe(false) + expect(isSubmittedTerminalInput('201~')).toBe(false) }) diff --git a/src/main/runtime/terminal/output/terminal-input-submission.ts b/src/main/runtime/terminal/output/terminal-input-submission.ts index 528783bfea2e..26fcea46155f 100644 --- a/src/main/runtime/terminal/output/terminal-input-submission.ts +++ b/src/main/runtime/terminal/output/terminal-input-submission.ts @@ -1,35 +1,8 @@ -const PASTE_START = '\x1b[200~' -const PASTE_END = '\x1b[201~' +// Typed lines are short; a paste arrives in large or escape-framed chunks. +const MAX_SUBMITTED_LINE_LENGTH = 1_024 -/** Enter submits a line; pasted text (its framing can span writes) and Alt/Shift+Enter (ESC CR) - * only edit the draft. */ -export function scanTerminalInputSubmission( - data: string, - pasteOpen: boolean -): { submitted: boolean; pasteOpen: boolean } { - let open = pasteOpen - let submitted = false - for (let i = 0; i < data.length; i++) { - if (data.startsWith(PASTE_START, i)) { - open = true - i += PASTE_START.length - 1 - } else if (data.startsWith(PASTE_END, i)) { - open = false - i += PASTE_END.length - 1 - } else if (!open && data[i] === '\r' && data[i - 1] !== '\x1b') { - submitted = true - } - } - return { submitted, pasteOpen: open } -} - -/** Bracketed-paste framing per live PTY record; it can span accepted writes. */ -export class TerminalInputSubmissions { - private readonly pasteOpenByPty = new WeakMap() - - submitted(pty: object, data: string): boolean { - const scan = scanTerminalInputSubmission(data, this.pasteOpenByPty.get(pty) === true) - this.pasteOpenByPty.set(pty, scan.pasteOpen) - return scan.submitted - } +/** A short write ending in Enter submits a line. Pastes (escape-framed or chunked large) and + * Alt/Shift+Enter (ESC CR) only edit the draft. */ +export function isSubmittedTerminalInput(data: string): boolean { + return data.length <= MAX_SUBMITTED_LINE_LENGTH && data.endsWith('\r') && !data.includes('\x1b') } diff --git a/src/main/runtime/terminal/output/terminal-title-observation.ts b/src/main/runtime/terminal/output/terminal-title-observation.ts index 0de6d9ddbc00..a8807c5c2e49 100644 --- a/src/main/runtime/terminal/output/terminal-title-observation.ts +++ b/src/main/runtime/terminal/output/terminal-title-observation.ts @@ -1,4 +1,4 @@ -import { TerminalInputSubmissions } from './terminal-input-submission' +import { isSubmittedTerminalInput } from './terminal-input-submission' import type { AgentStatus } from '../../../../shared/agent-status/title/agent-title-core' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' import { OrcaRuntimeWithGetUnpersistedTrackedTitleForPty } from './terminal-title-tracker' @@ -46,12 +46,9 @@ export abstract class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWit /** A title moved a terminal agent to another status; worktree.ps rows show it without a hook row. */ protected abstract onTitleAgentStatusChanged(): void - private readonly inputSubmissions = new TerminalInputSubmissions() - /** A submitted line ends a resumed agent's startup on every host, remote panes included. */ notePtyInputSubmitted(ptyId: string, data: string): void { - const pty = this.ptysById.get(ptyId) - if (!this.onPaneInputSubmitted || !pty || !this.inputSubmissions.submitted(pty, data)) { + if (!this.onPaneInputSubmitted || !isSubmittedTerminalInput(data)) { return } for (const paneKey of this.collectPaneKeysForPty(ptyId)) { From e66184101861f9d84d72d6c96ddb0d4f18a75c50 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:17:23 -0800 Subject: [PATCH 059/125] Count an Enter in merged keystroke writes --- .../output/terminal-input-submission.test.ts | 5 ++++ .../output/terminal-input-submission.ts | 23 +++++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/main/runtime/terminal/output/terminal-input-submission.test.ts b/src/main/runtime/terminal/output/terminal-input-submission.test.ts index bec818ab16d3..5ecd59ec5c91 100644 --- a/src/main/runtime/terminal/output/terminal-input-submission.test.ts +++ b/src/main/runtime/terminal/output/terminal-input-submission.test.ts @@ -6,9 +6,14 @@ it('counts Enter as a submission but not pasted or modified newlines', () => { expect(isSubmittedTerminalInput('/compact\r')).toBe(true) expect(isSubmittedTerminalInput('\x1b\r')).toBe(false) expect(isSubmittedTerminalInput('draft\n')).toBe(false) + // Keystrokes merged while a write is in flight still carry their Enter. + expect(isSubmittedTerminalInput('\x1b[A\r')).toBe(true) + expect(isSubmittedTerminalInput('/compact\x1b[116;1:3u\r')).toBe(true) + expect(isSubmittedTerminalInput('/compact\rnext')).toBe(true) // Each chunk of a large paste: its opening frame, a body ending in CR, a split closing frame. expect(isSubmittedTerminalInput('\x1b[200~')).toBe(false) expect(isSubmittedTerminalInput(`${'x'.repeat(16_383)}\r`)).toBe(false) + expect(isSubmittedTerminalInput('\x1b[200~line\r\x1b[201~')).toBe(false) expect(isSubmittedTerminalInput('\x1b[')).toBe(false) expect(isSubmittedTerminalInput('201~')).toBe(false) }) diff --git a/src/main/runtime/terminal/output/terminal-input-submission.ts b/src/main/runtime/terminal/output/terminal-input-submission.ts index 26fcea46155f..a91f9be5ae0c 100644 --- a/src/main/runtime/terminal/output/terminal-input-submission.ts +++ b/src/main/runtime/terminal/output/terminal-input-submission.ts @@ -1,8 +1,21 @@ -// Typed lines are short; a paste arrives in large or escape-framed chunks. -const MAX_SUBMITTED_LINE_LENGTH = 1_024 +// Typed input, even merged while a write is in flight, stays short; pastes arrive in larger or +// escape-framed chunks. +const MAX_SUBMITTED_WRITE_LENGTH = 4_096 +const PASTE_FRAME = '\x1b[20' +// oxlint-disable-next-line no-control-regex -- SAFETY: key reports (arrows, kitty) are ESC-led CSI. +const KEY_REPORT = /\x1b\[[0-9;:?]*[A-Za-z~]/g -/** A short write ending in Enter submits a line. Pastes (escape-framed or chunked large) and - * Alt/Shift+Enter (ESC CR) only edit the draft. */ +/** A short write holding a plain Enter submits a line. Pastes and Alt/Shift+Enter (ESC CR) only + * edit the draft. */ export function isSubmittedTerminalInput(data: string): boolean { - return data.length <= MAX_SUBMITTED_LINE_LENGTH && data.endsWith('\r') && !data.includes('\x1b') + if (data.length > MAX_SUBMITTED_WRITE_LENGTH || data.includes(PASTE_FRAME)) { + return false + } + const keys = data.replace(KEY_REPORT, '') + for (let i = keys.indexOf('\r'); i !== -1; i = keys.indexOf('\r', i + 1)) { + if (keys[i - 1] !== '\x1b') { + return true + } + } + return false } From 0525f63af01a5dc4e645aec215686b4b4bbf3b3a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:25:10 -0800 Subject: [PATCH 060/125] Show terminal work after a wake as main does: drop the startup swallow and its submission tracking, and skip the cancel latch on a resumed row --- .../runtime/agent-hook-runtime-deps.ts | 1 - .../server/pane-agent-turn-continuity.ts | 8 ++--- .../server/server-status-row-mutation.ts | 31 +----------------- .../agent-hooks/server/server-tab-cleanup.ts | 2 -- .../persistence/server-pane-sleep.test.ts | 32 +++++++------------ src/main/ipc/pty/ipc/write-input.ts | 3 -- src/main/ipc/pty/runtime/operations.ts | 3 -- .../runtime-construction-dependencies.ts | 2 -- .../construction/runtime-construction.ts | 1 - .../construction/runtime-host-services.ts | 2 -- .../output/terminal-input-submission.test.ts | 19 ----------- .../output/terminal-input-submission.ts | 21 ------------ .../output/terminal-title-observation.ts | 11 ------- .../state/agent-hook-cancel-verdict-latch.ts | 5 ++- 14 files changed, 20 insertions(+), 121 deletions(-) delete mode 100644 src/main/runtime/terminal/output/terminal-input-submission.test.ts delete mode 100644 src/main/runtime/terminal/output/terminal-input-submission.ts diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index cfa6e28ac038..6b01868ce1a4 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -16,7 +16,6 @@ export function agentHookRuntimeDeps( onTerminalProgramStatusFacet: (event) => server.ingestProgramStatusFacet(event), onClaudeTerminalEvidence: (paneKey, evidence) => server.observeClaudeTerminalEvidence(paneKey, evidence), - onPaneInputSubmitted: (paneKey) => server.notePaneInputSubmitted(paneKey), getPaneAgentIdentity: (paneKey, savedRecord) => server.paneAgentIdentity(paneKey, savedRecord), getAgentStatusSnapshot: () => server.getStatusSnapshot().flatMap((row) => { diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index aaab076b4fa8..85fbe094d741 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -8,16 +8,14 @@ import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/ident export function resumedAcceptedTurn( previous: EnrichedAgentHookEventPayload, incoming: AgentHookEventPayload, - origin: AgentStatusObservationOrigin, - /** No user submission since the launch: terminal work is still the CLI's own startup. */ - startupOpen = true + origin: AgentStatusObservationOrigin ): EnrichedAgentHookEventPayload | null { const continuesTurn = (incoming.payload.agentType === 'claude' || previous.observation?.origin === 'launch') && (incoming.payload.sessionBoundary === true || (origin === 'osc' && previous.observation?.origin === 'launch')) && - (incoming.payload.state === 'done' || - (origin === 'osc' && incoming.payload.state === 'working' && startupOpen)) && + // Terminal work after a resume is shown as it is on main; only restated verdicts continue. + incoming.payload.state === 'done' && incoming.toolAgentId === undefined && previous.payload.state === 'done' && previous.payload.sessionBoundary !== true && diff --git a/src/main/agent-hooks/server/server-status-row-mutation.ts b/src/main/agent-hooks/server/server-status-row-mutation.ts index c13f7c74e7d4..2c35e0acbb81 100644 --- a/src/main/agent-hooks/server/server-status-row-mutation.ts +++ b/src/main/agent-hooks/server/server-status-row-mutation.ts @@ -9,43 +9,14 @@ import { ClaudeOwedNotificationExpiryTimers } from '../../../shared/agent-hook-l import { AgentHookServerStatusApplication } from './server-status-application' -const MAX_REMEMBERED_SUBMISSIONS = 1_000 - export abstract class AgentHookServerStatusRowMutation extends AgentHookServerStatusApplication { - /** When the user last submitted a line in each pane; a resumed CLI's startup ends there. */ - protected readonly lastSubmittedAtByPaneKey = new Map() - - /** Kept only while a resumed row's startup window is open; pane teardown forgets it. */ - notePaneInputSubmitted(paneKey: string): void { - const resolved = this.resolvePaneKeyAlias(paneKey) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. - const row = this.state.lastStatusByPaneKey.get(resolved) as - | EnrichedAgentHookEventPayload - | undefined - if (row?.observation?.origin !== 'launch') { - return - } - // Pane teardown forgets marks; the oldest go first if panes outrun that. - this.lastSubmittedAtByPaneKey.delete(resolved) - this.lastSubmittedAtByPaneKey.set(resolved, Date.now()) - if (this.lastSubmittedAtByPaneKey.size > MAX_REMEMBERED_SUBMISSIONS) { - const oldest = this.lastSubmittedAtByPaneKey.keys().next().value - if (oldest !== undefined) { - this.lastSubmittedAtByPaneKey.delete(oldest) - } - } - } - protected preserveAcceptedTurn( previous: EnrichedAgentHookEventPayload | undefined, incoming: AgentHookEventPayload, before: EnrichedAgentHookEventPayload | undefined, origin: AgentStatusObservationOrigin ): EnrichedAgentHookEventPayload | null | undefined { - const submittedAt = previous && this.lastSubmittedAtByPaneKey.get(previous.paneKey) - const startupOpen = - submittedAt === undefined || submittedAt < (previous?.observation?.observedAt ?? 0) - const resumed = previous && resumedAcceptedTurn(previous, incoming, origin, startupOpen) + const resumed = previous && resumedAcceptedTurn(previous, incoming, origin) if (!resumed) { return null } diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 8fc04b23f785..d865ded30279 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -207,7 +207,6 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { this.restartedStatusLaunchTokenHashByPaneKey.delete(paneKey) this.evidenceObservedAtByPaneKey.delete(paneKey) this.programStatusFacets.delete(paneKey) - this.lastSubmittedAtByPaneKey.delete(paneKey) this.hookSilenceRechecks.cancel(paneKey) this.programStatusFacetRepublishes.cancel(paneKey) } @@ -247,7 +246,6 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } ): void { const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey) - this.lastSubmittedAtByPaneKey.delete(resolvedPaneKey) if (options?.forgetAgentExit) { this.forgetAgentExit(paneKey) } diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index e2e04d753f2a..aa6962070ac7 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -207,16 +207,14 @@ it.each(['retained', 'evicted'] as const)( providerSession: { key: 'session_id', id: 'claude-session' }, launchedAt: Date.now() }) - // Startup work precedes SessionStart; neither report opens a user turn. - for (const state of ['working', 'idle']) { - ingestProgramStatusOsc(server, `\x1b]7501;app=claude-code:state=${state}\x1b\\`) - expect(read()).toMatchObject({ - state: 'done', - interrupted: true, - prompt: 'Finished work', - mainAgent: { state: 'done', outcome: 'cancellation' } - }) - } + // A resumed CLI's idle restatement before SessionStart opens no user turn. + ingestProgramStatusOsc(server, `\x1b]7501;app=claude-code:state=idle\x1b\\`) + expect(read()).toMatchObject({ + state: 'done', + interrupted: true, + prompt: 'Finished work', + mainAgent: { state: 'done', outcome: 'cancellation' } + }) const response = await postHookEvent( server, buildBody( @@ -253,23 +251,17 @@ it.each(['retained', 'evicted'] as const)( } ) -it('shows hookless work the user submits after a resumed agent starts', async () => { - const working = `\x1b]7501;app=claude-code:state=working\x1b\\` +it('shows terminal work right after a wake, as for any pane', async () => { server.setHookRootEvidenceReader(async () => ({ verdict: 'root' })) await agentHook('claude', 'UserPromptSubmit', 4001) - await agentHook('claude', 'Stop', 4001) await sleepPane('claude', 'pty-1', 4001) server.retireSleepingPaneOnSpawn(PANE, { agentType: 'claude', providerSession: { key: 'session_id', id: 'claude-session' } }) - // The resumed CLI's own startup work is not a new turn. - ingestProgramStatusOsc(server, working) - expect(read()).toMatchObject({ state: 'done' }) - vi.setSystemTime(Date.now() + 1_000) - // A hookless command such as /compact is. - server.notePaneInputSubmitted(PANE) - ingestProgramStatusOsc(server, working) + expect(read()).toMatchObject({ state: 'done', interrupted: true }) + // A hookless command such as /compact reports its work only over the terminal. + ingestProgramStatusOsc(server, `\x1b]7501;app=claude-code:state=working\x1b\\`) expect(read()).toMatchObject({ state: 'working' }) }) diff --git a/src/main/ipc/pty/ipc/write-input.ts b/src/main/ipc/pty/ipc/write-input.ts index 85c29b38975c..1e803f7ef110 100644 --- a/src/main/ipc/pty/ipc/write-input.ts +++ b/src/main/ipc/pty/ipc/write-input.ts @@ -241,9 +241,6 @@ export function createPtyWriteInput(deps: { ) { runtime?.observeClaudeTerminalEvidence?.(args.id, { kind: 'input', data: args.data }) } - if (accepted && args.inputKind === 'driving') { - runtime?.notePtyInputSubmitted?.(args.id, args.data) - } return accepted } const result = writePtyProviderInput(provider, args, verify) diff --git a/src/main/ipc/pty/runtime/operations.ts b/src/main/ipc/pty/runtime/operations.ts index d90425bcde69..5bb75bbac0f8 100644 --- a/src/main/ipc/pty/runtime/operations.ts +++ b/src/main/ipc/pty/runtime/operations.ts @@ -48,9 +48,6 @@ export function writePtyFromRuntimeController( if (isDrivingInputKind(inputKind) && ptyOwnership.get(ptyId) === LOCAL_EXECUTION_HOST_ID) { deps.runtime?.observeClaudeTerminalEvidence?.(ptyId, { kind: 'input', data }) } - if (isDrivingInputKind(inputKind)) { - deps.runtime?.notePtyInputSubmitted?.(ptyId, data) - } } let provider: IPtyProvider try { diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 5898ed182131..ba5b4025bd52 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -38,8 +38,6 @@ export type RuntimeConstructionDependencies = { onTerminalProgramStatusFacet?: (event: RuntimeTerminalProgramStatusFacetEvent) => void onTerminalSideEffects?: (batch: TerminalSideEffectBatch) => void onClaudeTerminalEvidence?: (paneKey: string, evidence: ClaudeTerminalEvidence) => void - /** A line the user submitted in a pane, on any host. */ - onPaneInputSubmitted?: (paneKey: string) => void getPaneAgentIdentity?: ( paneKey: string, savedRecord?: SleepingAgentSessionRecord diff --git a/src/main/runtime/construction/runtime-construction.ts b/src/main/runtime/construction/runtime-construction.ts index 37929e44ebf7..9328155418bd 100644 --- a/src/main/runtime/construction/runtime-construction.ts +++ b/src/main/runtime/construction/runtime-construction.ts @@ -292,7 +292,6 @@ export abstract class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCo this.onTerminalAgentStatus = deps?.onTerminalAgentStatus ?? null this.onTerminalProgramStatusFacet = deps?.onTerminalProgramStatusFacet ?? null this.onClaudeTerminalEvidence = deps?.onClaudeTerminalEvidence ?? null - this.onPaneInputSubmitted = deps?.onPaneInputSubmitted ?? null this.buildAgentHookPtyEnv = deps?.buildAgentHookPtyEnv ?? null this.getDesktopWindowStatusFn = deps?.getDesktopWindowStatus ?? (() => 'openable') this.headlessTerminalScrollbackRows = diff --git a/src/main/runtime/construction/runtime-host-services.ts b/src/main/runtime/construction/runtime-host-services.ts index 3b246ed554d4..f993253e0b24 100644 --- a/src/main/runtime/construction/runtime-host-services.ts +++ b/src/main/runtime/construction/runtime-host-services.ts @@ -104,8 +104,6 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends RuntimeAgent protected readonly onClaudeTerminalEvidence!: HostBindings['onClaudeTerminalEvidence'] | null - protected onPaneInputSubmitted: HostBindings['onPaneInputSubmitted'] | null = null - protected terminalSideEffectLocalConsumerAvailable = false protected terminalSideEffectConsumerAvailable = false diff --git a/src/main/runtime/terminal/output/terminal-input-submission.test.ts b/src/main/runtime/terminal/output/terminal-input-submission.test.ts deleted file mode 100644 index 5ecd59ec5c91..000000000000 --- a/src/main/runtime/terminal/output/terminal-input-submission.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { expect, it } from 'vitest' -import { isSubmittedTerminalInput } from './terminal-input-submission' - -it('counts Enter as a submission but not pasted or modified newlines', () => { - expect(isSubmittedTerminalInput('\r')).toBe(true) - expect(isSubmittedTerminalInput('/compact\r')).toBe(true) - expect(isSubmittedTerminalInput('\x1b\r')).toBe(false) - expect(isSubmittedTerminalInput('draft\n')).toBe(false) - // Keystrokes merged while a write is in flight still carry their Enter. - expect(isSubmittedTerminalInput('\x1b[A\r')).toBe(true) - expect(isSubmittedTerminalInput('/compact\x1b[116;1:3u\r')).toBe(true) - expect(isSubmittedTerminalInput('/compact\rnext')).toBe(true) - // Each chunk of a large paste: its opening frame, a body ending in CR, a split closing frame. - expect(isSubmittedTerminalInput('\x1b[200~')).toBe(false) - expect(isSubmittedTerminalInput(`${'x'.repeat(16_383)}\r`)).toBe(false) - expect(isSubmittedTerminalInput('\x1b[200~line\r\x1b[201~')).toBe(false) - expect(isSubmittedTerminalInput('\x1b[')).toBe(false) - expect(isSubmittedTerminalInput('201~')).toBe(false) -}) diff --git a/src/main/runtime/terminal/output/terminal-input-submission.ts b/src/main/runtime/terminal/output/terminal-input-submission.ts deleted file mode 100644 index a91f9be5ae0c..000000000000 --- a/src/main/runtime/terminal/output/terminal-input-submission.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Typed input, even merged while a write is in flight, stays short; pastes arrive in larger or -// escape-framed chunks. -const MAX_SUBMITTED_WRITE_LENGTH = 4_096 -const PASTE_FRAME = '\x1b[20' -// oxlint-disable-next-line no-control-regex -- SAFETY: key reports (arrows, kitty) are ESC-led CSI. -const KEY_REPORT = /\x1b\[[0-9;:?]*[A-Za-z~]/g - -/** A short write holding a plain Enter submits a line. Pastes and Alt/Shift+Enter (ESC CR) only - * edit the draft. */ -export function isSubmittedTerminalInput(data: string): boolean { - if (data.length > MAX_SUBMITTED_WRITE_LENGTH || data.includes(PASTE_FRAME)) { - return false - } - const keys = data.replace(KEY_REPORT, '') - for (let i = keys.indexOf('\r'); i !== -1; i = keys.indexOf('\r', i + 1)) { - if (keys[i - 1] !== '\x1b') { - return true - } - } - return false -} diff --git a/src/main/runtime/terminal/output/terminal-title-observation.ts b/src/main/runtime/terminal/output/terminal-title-observation.ts index a8807c5c2e49..ecf30e4b2173 100644 --- a/src/main/runtime/terminal/output/terminal-title-observation.ts +++ b/src/main/runtime/terminal/output/terminal-title-observation.ts @@ -1,4 +1,3 @@ -import { isSubmittedTerminalInput } from './terminal-input-submission' import type { AgentStatus } from '../../../../shared/agent-status/title/agent-title-core' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' import { OrcaRuntimeWithGetUnpersistedTrackedTitleForPty } from './terminal-title-tracker' @@ -46,16 +45,6 @@ export abstract class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWit /** A title moved a terminal agent to another status; worktree.ps rows show it without a hook row. */ protected abstract onTitleAgentStatusChanged(): void - /** A submitted line ends a resumed agent's startup on every host, remote panes included. */ - notePtyInputSubmitted(ptyId: string, data: string): void { - if (!this.onPaneInputSubmitted || !isSubmittedTerminalInput(data)) { - return - } - for (const paneKey of this.collectPaneKeysForPty(ptyId)) { - this.onPaneInputSubmitted(paneKey) - } - } - observeClaudeTerminalEvidence(ptyId: string, evidence: ClaudeTerminalEvidence): void { if (!this.onClaudeTerminalEvidence || this.ptysById.get(ptyId)?.connectionId) { return diff --git a/src/shared/agent-hook-listener/state/agent-hook-cancel-verdict-latch.ts b/src/shared/agent-hook-listener/state/agent-hook-cancel-verdict-latch.ts index 77c3ff26b108..2f7261290c9c 100644 --- a/src/shared/agent-hook-listener/state/agent-hook-cancel-verdict-latch.ts +++ b/src/shared/agent-hook-listener/state/agent-hook-cancel-verdict-latch.ts @@ -1,3 +1,4 @@ +import type { WithAgentStatusObservation } from '../../agent-status/contracts/agent-status-observation' import type { AgentHookEventPayload } from '../listener-event' import type { AgentMainAgentStatus } from '../../agent-status/lifecycle/main-agent-status' import { foldMainAgentWithRowChildWork } from './agent-hook-row-child-work-fold' @@ -21,7 +22,7 @@ export function isToolProgressWorkingAfterInterrupt(next: AgentHookEventPayload) return next.hookEventName !== undefined && TOOL_PROGRESS_HOOK_EVENTS.has(next.hookEventName) } -type CancelledRow = AgentHookEventPayload & { receivedAt: number } +type CancelledRow = AgentHookEventPayload & WithAgentStatusObservation & { receivedAt: number } export type CancelVerdictLatchDecision = | { hold: true } @@ -108,6 +109,8 @@ export function resolveCancelVerdictLatch( if ( !previous || !isCancelVerdictLatched(previous) || + // A resumed row's verdict outlives its process; nothing late can follow it, as on main. + previous.observation?.origin === 'launch' || previous.payload.agentType !== incoming.payload.agentType || restatesAnotherPrompt(previous, incoming) || incoming.payload.mainAgent?.state === 'done' || From d0b4b6d984b3315d6f5a9b826aa9caeb623cd776 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:32:35 -0800 Subject: [PATCH 061/125] fix(sleep): keep main's behavior for six review findings A restated done keeps its turn only when it ends no other turn; a tmux release keeps a checkpoint saved during its probe; quit capture leaves saved live checkpoints as main does; only an attached tmux client hosts a pane; sleep no longer cancels an already finished main agent. --- .../server/pane-agent-turn-continuity.test.ts | 43 +++++++++++++++++++ .../server/pane-agent-turn-continuity.ts | 14 ++++++ .../agent-hooks/server/server-tmux-status.ts | 6 ++- .../tmux/server-tmux-legacy-sleep.test.ts | 6 ++- .../worktree-sleep-resume-recording.test.ts | 4 ++ .../stop/worktree-sleep-resume-recording.ts | 9 ++-- .../presence/pane-tmux-host-proof.ts | 29 ++++++++++++- .../lifecycle/agent-pane-sleep-status.test.ts | 3 +- .../lifecycle/agent-pane-sleep-status.ts | 10 +++-- 9 files changed, 111 insertions(+), 13 deletions(-) create mode 100644 src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts new file mode 100644 index 000000000000..13ebc4874b6c --- /dev/null +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts @@ -0,0 +1,43 @@ +import { expect, it } from 'vitest' +import { wslHookRelayConnectionId } from '../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' +import { resumedAcceptedTurn } from './pane-agent-turn-continuity' +import type { EnrichedAgentHookEventPayload } from './server-types' + +const WORKTREE = 'repo::\\\\wsl.localhost\\Ubuntu\\home\\u\\wt' +const SESSION = { key: 'session_id', id: 'claude-session' } as const + +// A woken row: the resumed conversation's accepted verdict, stamped by its launch. +const resumed: EnrichedAgentHookEventPayload = { + paneKey: 'tab-1:pane', + tabId: 'tab-1', + worktreeId: WORKTREE, + connectionId: wslHookRelayConnectionId('Ubuntu'), + receivedAt: 1_000, + stateStartedAt: 1_000, + turnEndedAt: 1_000, + providerSession: SESSION, + observation: { + origin: 'launch', + authorityId: 'main', + incarnation: 1, + revision: 1, + observedAt: 2_000 + }, + payload: { state: 'done', prompt: 'Finished work', agentType: 'claude' } +} +const restated = { + paneKey: 'tab-1:pane', + tabId: 'tab-1', + worktreeId: WORKTREE, + connectionId: null, + providerSession: SESSION, + payload: { state: 'done', prompt: '', agentType: 'claude' } +} as const + +it('keeps a restated verdict on the reporting terminal, but not a later stamped turn end', () => { + expect(resumedAcceptedTurn(resumed, restated, 'osc')).toMatchObject({ + connectionId: null, + payload: { prompt: 'Finished work' } + }) + expect(resumedAcceptedTurn(resumed, { ...restated, turnEndedAt: 3_000 }, 'osc')).toBeNull() +}) diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index 85fbe094d741..d64cce7af9b4 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -17,6 +17,7 @@ export function resumedAcceptedTurn( // Terminal work after a resume is shown as it is on main; only restated verdicts continue. incoming.payload.state === 'done' && incoming.toolAgentId === undefined && + !endsAnotherTurn(previous, incoming) && previous.payload.state === 'done' && previous.payload.sessionBoundary !== true && previous.providerSessionOnly !== true && @@ -39,12 +40,25 @@ export function resumedAcceptedTurn( } = previous return { ...accepted, + connectionId: incoming.connectionId, ...(incoming.providerSession ? { providerSession: incoming.providerSession } : {}), ...(incoming.agentPresence ? { agentPresence: incoming.agentPresence } : {}), ...(incoming.terminalHandle ? { terminalHandle: incoming.terminalHandle } : {}) } } +/** A completion stamped with its own turn end is a later turn, not a restatement. */ +function endsAnotherTurn( + previous: EnrichedAgentHookEventPayload, + incoming: AgentHookEventPayload +): boolean { + return ( + (incoming.turnEndedAt !== undefined && incoming.turnEndedAt !== previous.turnEndedAt) || + (incoming.payload.turnCompletedAt !== undefined && + incoming.payload.turnCompletedAt !== previous.payload.turnCompletedAt) + ) +} + export function resolvedHookAgentType( row: T, agentType: AgentHookEventPayload['payload']['agentType'] diff --git a/src/main/agent-hooks/server/server-tmux-status.ts b/src/main/agent-hooks/server/server-tmux-status.ts index dd2847c58682..19772b270192 100644 --- a/src/main/agent-hooks/server/server-tmux-status.ts +++ b/src/main/agent-hooks/server/server-tmux-status.ts @@ -21,6 +21,7 @@ export abstract class AgentHookServerTmuxStatus extends AgentHookServerOpenCodeB * never the pane's own process. */ protected async releaseTmuxHostedCheckpoint(paneKey: string): Promise { const read = this.readPaneTmuxHost + const probed = this.terminalPaneLifecycle?.readSavedRecord?.(paneKey) const identity = read && !this.getTmuxSelectedStatus(paneKey) && this.paneAgentIdentity(paneKey) if ( !read || @@ -30,11 +31,12 @@ export abstract class AgentHookServerTmuxStatus extends AgentHookServerOpenCodeB !identity.status.worktreeId || !(await read({ paneKey, worktreeId: identity.status.worktreeId }).catch(() => false)) || this.state.lastStatusByPaneKey.has(paneKey) || - this.getTmuxSelectedStatus(paneKey) + this.getTmuxSelectedStatus(paneKey) || + // A record saved during the probe is a newer conversation; it stays. + this.terminalPaneLifecycle?.readSavedRecord?.(paneKey) !== probed ) { return } - // The identity is the saved record as probed; a record saved during the probe stays. this.releaseSharedPaneConversation(paneKey, identity.status, identity.status.receivedAt) } diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 2a8f4f670749..9b014d955291 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -227,6 +227,9 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => // An unreadable job might be the pane's own agent. runningPane(4050, CLIENT, [4080, 101, 4080, '(claude)', 'T'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + // A foreground tmux command that attaches no session hosts nothing. + runningPane(4050, [4050, 101, 4050, 'tmux wait-for build-ready', 'S+'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) // An agent whose ancestry cannot be read is not proven to live outside the pane. runningPane(4050, CLIENT, [4043, 4042, 4043, 'claude', 'S+', 'ttys011']) await expect(readPaneTmuxHost(io, agent)).resolves.toBe(false) @@ -245,7 +248,8 @@ it('keeps a checkpoint saved while its tmux release was probing', async () => { updatedAt, origin: 'live' }) - const replacement = record('replacement', NOW + 500) + // Saved after the probe began, with the same clock as the record it replaces. + const replacement = record('replacement', NOW) let saved: SleepingAgentSessionRecord | undefined = record('released', NOW) server.setHookRootEvidenceReader( (request) => readHookRootEvidence(request, io), diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index a91bf1743b5a..35116cb6779b 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -126,6 +126,10 @@ describe('main-run sleep of a pane whose hook row is gone', () => { server.forgetAgentExit(PANE_KEY) } } + if (scenario === 'live' || scenario === 'working') { + // A running pane's saved live checkpoint is not proof it still owns that conversation. + expect(runtime.quitResumeRecordsFor(fixture.getSession())).toEqual([]) + } try { await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) const record = fixture.getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY] diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 7bdcfdbdb579..d4839ab2fad8 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -238,12 +238,13 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu /** A layout-owner build's quit capture of the agents of the panes one partition holds. */ quitResumeRecordsFor(session: WorkspaceSessionState): SleepingAgentSessionRecord[] { - // A saved-only pane quits only while its terminal runs; an asleep pane keeps its sleep record. + // A saved-only pane quits only while its terminal runs; an asleep pane keeps its sleep record + // and a live checkpoint stays as saved, as main leaves both. const paneKeys = new Set([ ...(this.getAgentProviderSessionSnapshotFn?.() ?? []).map((row) => row.paneKey), - ...Object.keys(session.sleepingAgentSessionsByPaneKey ?? {}).filter((paneKey) => - this.hasLiveTerminalForPaneKey(paneKey) - ) + ...Object.values(session.sleepingAgentSessionsByPaneKey ?? {}) + .filter((saved) => saved.origin !== 'live' && this.hasLiveTerminalForPaneKey(saved.paneKey)) + .map((saved) => saved.paneKey) ]) const statuses = [...paneKeys].flatMap((paneKey) => { const identity = this.readPaneAgentIdentity( diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index 367d78350a81..747fe9938c8d 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -1,3 +1,4 @@ +import { tokenizeCommandLine } from '../../agent-status/process/agent-command-line-entrypoint' import type { AgentProcessIdentity } from '../../agent-status/process/agent-process-presence' import { unreadableArgvName, @@ -19,6 +20,32 @@ export type PaneTmuxHostReader = (request: { process?: AgentProcessIdentity }) => Promise +const TMUX_OPTIONS_WITH_VALUE = new Set(['-L', '-S', '-f', '-T']) +const TMUX_ATTACHING_COMMANDS = new Set([ + 'attach', + 'attach-session', + 'a', + 'at', + 'new', + 'new-session' +]) + +/** Only a client attached to a session shows that server's panes; `wait-for` or `-c` do not. */ +function isAttachingTmuxClient(row: ProcessTableRow): boolean { + if (!isTmuxServer(row)) { + return false + } + const args = tokenizeCommandLine(row.command).slice(1) + let index = 0 + while (args[index]?.startsWith('-')) { + if (args[index] === '-c') { + return false + } + index += TMUX_OPTIONS_WITH_VALUE.has(args[index]) ? 2 : 1 + } + return args[index] === undefined || TMUX_ATTACHING_COMMANDS.has(args[index]) +} + export async function readPaneTmuxHost( io: Pick, request: Parameters[0] @@ -36,7 +63,7 @@ export async function readPaneTmuxHost( return false } const client = rows.find( - (row) => row.tty === rootRow.tty && row.pgid === rootRow.tpgid && isTmuxServer(row) + (row) => row.tty === rootRow.tty && row.pgid === rootRow.tpgid && isAttachingTmuxClient(row) ) if (!client) { return false diff --git a/src/shared/agent-status/lifecycle/agent-pane-sleep-status.test.ts b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.test.ts index 48ab224ce8d8..c16133ae7182 100644 --- a/src/shared/agent-status/lifecycle/agent-pane-sleep-status.test.ts +++ b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.test.ts @@ -2,10 +2,9 @@ import { expect, it } from 'vitest' import { agentPaneSleepStatus } from './agent-pane-sleep-status' it('keeps a finished main agent verdict when sleep interrupts its children', () => { - const finished = { state: 'done', outcome: 'success', stateStartedAt: 10 } as const + const finished = { state: 'done', stateStartedAt: 10 } as const expect(agentPaneSleepStatus({ state: 'working', mainAgent: finished }, 50)).toEqual({ state: 'done', - interrupted: true, mainAgent: finished }) expect( diff --git a/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts index d81a1df119fa..dce3ab4acc1b 100644 --- a/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts +++ b/src/shared/agent-status/lifecycle/agent-pane-sleep-status.ts @@ -5,13 +5,17 @@ import type { AgentStatusState } from '../contracts/agent-status-types' export function agentPaneSleepStatus< T extends { state: AgentStatusState; interrupted?: boolean; mainAgent?: AgentMainAgentStatus } >(status: T, at: number): T { - return status.state === 'done' - ? status + if (status.state === 'done') { + return status + } + // Only the main agent's own turn can be cancelled; a finished one keeps its verdict. + return status.mainAgent?.state === 'done' + ? { ...status, state: 'done' } : { ...status, state: 'done', interrupted: true, - ...(status.mainAgent && status.mainAgent.state !== 'done' + ...(status.mainAgent ? { mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: at } } : {}) } From ced7e471e8fe5f16fc57616d99ac0875a30e4fe1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:36:51 -0800 Subject: [PATCH 062/125] fix(sleep): count tmux's unambiguous attach prefixes as attaching --- .../tmux/server-tmux-legacy-sleep.test.ts | 3 +++ .../presence/pane-tmux-host-proof.ts | 16 +++++++--------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 9b014d955291..0b3da5db4c97 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -227,6 +227,9 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => // An unreadable job might be the pane's own agent. runningPane(4050, CLIENT, [4080, 101, 4080, '(claude)', 'T'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + // tmux resolves an unambiguous prefix, so `att` attaches. + runningPane(4050, [4050, 101, 4050, 'tmux -L qa att -t cl', 'S+'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) // A foreground tmux command that attaches no session hosts nothing. runningPane(4050, [4050, 101, 4050, 'tmux wait-for build-ready', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index 747fe9938c8d..d3dfe8ab00b6 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -21,14 +21,12 @@ export type PaneTmuxHostReader = (request: { }) => Promise const TMUX_OPTIONS_WITH_VALUE = new Set(['-L', '-S', '-f', '-T']) -const TMUX_ATTACHING_COMMANDS = new Set([ - 'attach', - 'attach-session', - 'a', - 'at', - 'new', - 'new-session' -]) +// tmux aliases, plus the unambiguous prefixes tmux resolves to these commands (`att`, `new-s`). +const TMUX_ATTACHING_ALIASES = new Set(['a', 'at', 'new']) +const isAttachingTmuxCommand = (command: string): boolean => + TMUX_ATTACHING_ALIASES.has(command) || + (command.length >= 3 && 'attach-session'.startsWith(command)) || + (command.length >= 5 && 'new-session'.startsWith(command)) /** Only a client attached to a session shows that server's panes; `wait-for` or `-c` do not. */ function isAttachingTmuxClient(row: ProcessTableRow): boolean { @@ -43,7 +41,7 @@ function isAttachingTmuxClient(row: ProcessTableRow): boolean { } index += TMUX_OPTIONS_WITH_VALUE.has(args[index]) ? 2 : 1 } - return args[index] === undefined || TMUX_ATTACHING_COMMANDS.has(args[index]) + return args[index] === undefined || isAttachingTmuxCommand(args[index]) } export async function readPaneTmuxHost( From 5f70f95ef77d5679b78d2b015dc96879949d63a5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:40:04 -0800 Subject: [PATCH 063/125] fix(sleep): read grouped tmux flags when proving an attached client --- .../server/testing/tmux/server-tmux-legacy-sleep.test.ts | 5 +++++ .../agent-hook-listener/presence/pane-tmux-host-proof.ts | 9 ++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 0b3da5db4c97..64baa169e13f 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -230,6 +230,11 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => // tmux resolves an unambiguous prefix, so `att` attaches. runningPane(4050, [4050, 101, 4050, 'tmux -L qa att -t cl', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) + // Grouped flags: `-vc new` runs a shell command, while `-Lc` names a socket. + runningPane(4050, [4050, 101, 4050, 'tmux -vc new', 'S+'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + runningPane(4050, [4050, 101, 4050, 'tmux -Lc attach', 'S+'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) // A foreground tmux command that attaches no session hosts nothing. runningPane(4050, [4050, 101, 4050, 'tmux wait-for build-ready', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index d3dfe8ab00b6..88d230ca2292 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -20,7 +20,6 @@ export type PaneTmuxHostReader = (request: { process?: AgentProcessIdentity }) => Promise -const TMUX_OPTIONS_WITH_VALUE = new Set(['-L', '-S', '-f', '-T']) // tmux aliases, plus the unambiguous prefixes tmux resolves to these commands (`att`, `new-s`). const TMUX_ATTACHING_ALIASES = new Set(['a', 'at', 'new']) const isAttachingTmuxCommand = (command: string): boolean => @@ -36,10 +35,14 @@ function isAttachingTmuxClient(row: ProcessTableRow): boolean { const args = tokenizeCommandLine(row.command).slice(1) let index = 0 while (args[index]?.startsWith('-')) { - if (args[index] === '-c') { + // Flags may be grouped (`-vc`); the rest of a group after -L/-S/-f/-T is that flag's value. + const flags = args[index].slice(1) + const valueAt = flags.search(/[LSfT]/) + const shellAt = flags.indexOf('c') + if (shellAt !== -1 && (valueAt === -1 || shellAt < valueAt)) { return false } - index += TMUX_OPTIONS_WITH_VALUE.has(args[index]) ? 2 : 1 + index += valueAt !== -1 && valueAt === flags.length - 1 ? 2 : 1 } return args[index] === undefined || isAttachingTmuxCommand(args[index]) } From f557ee1aaa2594ad296902ef0385d7a0731b48df Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:58:29 -0800 Subject: [PATCH 064/125] perf(sleep): index each PTY inventory snapshot once for per-pane lookups --- .../observations/local-tmux-managed-pty.ts | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts index 41c80ad8a31c..0cfb390e4997 100644 --- a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts @@ -13,6 +13,30 @@ export type LocalPtyInventoryReader = ( options?: { bySpawnPaneKey?: boolean } ) => Promise +type InventoryIndex = { + byId: Map + bySpawnPaneKey: Map +} + +function indexInventory(rows: PtyProcessInfo[]): InventoryIndex { + const byId = new Map() + const bySpawnPaneKey = new Map() + for (const row of rows) { + if (!byId.has(row.id)) { + byId.set(row.id, row) + } + if (row.paneKey !== undefined) { + const spawned = bySpawnPaneKey.get(row.paneKey) + if (spawned) { + spawned.push(row) + } else { + bySpawnPaneKey.set(row.paneKey, [row]) + } + } + } + return { byId, bySpawnPaneKey } +} + /** Reuse the daemon's authenticated inventory; never resolve an SSH pane from the client. */ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalPtyInventoryReader { let pending: Promise | undefined @@ -38,10 +62,17 @@ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalP } return pending } + // Sleep capture looks up every pane against one snapshot; index it once per snapshot. + const indexes = new WeakMap() const find = (rows: PtyProcessInfo[], paneKey: string, id: string | undefined | null) => { + let index = indexes.get(rows) + if (!index) { + index = indexInventory(rows) + indexes.set(rows, index) + } // Before a restored pane reattaches, the provider's own spawn record still names its PTY. - const spawned = id ? [] : rows.filter((entry) => entry.paneKey === paneKey) - return (id ? rows.find((entry) => entry.id === id) : spawned.length === 1 && spawned[0]) || null + const spawned = id ? undefined : index.bySpawnPaneKey.get(paneKey) + return (id ? index.byId.get(id) : spawned?.length === 1 && spawned[0]) || null } return async (paneKey, lookup) => { const id = options.getPtyId(paneKey) From 17b4a4bedba48b9efa7ba673fcf911606ea947d2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:25:26 -0800 Subject: [PATCH 065/125] fix(sleep): a foreground tmux server is no attached client; index inventory only for repeated lookups --- .../observations/local-tmux-managed-pty.ts | 14 +++++++++++--- .../testing/tmux/server-tmux-legacy-sleep.test.ts | 2 ++ .../presence/pane-tmux-host-proof.ts | 5 +++-- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts index 0cfb390e4997..bd5eebdde36a 100644 --- a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts @@ -62,15 +62,23 @@ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalP } return pending } - // Sleep capture looks up every pane against one snapshot; index it once per snapshot. - const indexes = new WeakMap() + // A lone lookup scans as before; a second against the same snapshot (sleep capture walks every + // pane) indexes it once. + const indexes = new WeakMap() const find = (rows: PtyProcessInfo[], paneKey: string, id: string | undefined | null) => { let index = indexes.get(rows) if (!index) { + indexes.set(rows, 'scanned') + // Before a restored pane reattaches, the provider's own spawn record still names its PTY. + const spawned = id ? [] : rows.filter((entry) => entry.paneKey === paneKey) + return ( + (id ? rows.find((entry) => entry.id === id) : spawned.length === 1 && spawned[0]) || null + ) + } + if (index === 'scanned') { index = indexInventory(rows) indexes.set(rows, index) } - // Before a restored pane reattaches, the provider's own spawn record still names its PTY. const spawned = id ? undefined : index.bySpawnPaneKey.get(paneKey) return (id ? index.byId.get(id) : spawned?.length === 1 && spawned[0]) || null } diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 64baa169e13f..bfbb2fa91ff9 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -233,6 +233,8 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => // Grouped flags: `-vc new` runs a shell command, while `-Lc` names a socket. runningPane(4050, [4050, 101, 4050, 'tmux -vc new', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + runningPane(4050, [4050, 101, 4050, 'tmux -DL qa', 'S+'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane(4050, [4050, 101, 4050, 'tmux -Lc attach', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) // A foreground tmux command that attaches no session hosts nothing. diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index 88d230ca2292..f61e1e3447b8 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -36,10 +36,11 @@ function isAttachingTmuxClient(row: ProcessTableRow): boolean { let index = 0 while (args[index]?.startsWith('-')) { // Flags may be grouped (`-vc`); the rest of a group after -L/-S/-f/-T is that flag's value. + // -c runs a shell command and -D runs the server itself: neither is an attached client. const flags = args[index].slice(1) const valueAt = flags.search(/[LSfT]/) - const shellAt = flags.indexOf('c') - if (shellAt !== -1 && (valueAt === -1 || shellAt < valueAt)) { + const notClientAt = flags.search(/[cD]/) + if (notClientAt !== -1 && (valueAt === -1 || notClientAt < valueAt)) { return false } index += valueAt !== -1 && valueAt === flags.length - 1 ? 2 : 1 From 55678aedf7eaec1b24413959967e06cccecd8ece Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:30:24 -0800 Subject: [PATCH 066/125] fix(sleep): repeat one pane's inventory lookup from memory; -V/-h are no attached client --- .../observations/local-tmux-managed-pty.ts | 31 +++++++++++-------- .../tmux/server-tmux-legacy-sleep.test.ts | 2 ++ .../presence/pane-tmux-host-proof.ts | 4 +-- 3 files changed, 22 insertions(+), 15 deletions(-) diff --git a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts index bd5eebdde36a..00d30ea5bdd1 100644 --- a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts @@ -62,25 +62,30 @@ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalP } return pending } - // A lone lookup scans as before; a second against the same snapshot (sleep capture walks every - // pane) indexes it once. - const indexes = new WeakMap() + // One pane's lookups scan once per snapshot as before; a second pane against the same snapshot + // (sleep capture walks every pane) indexes it once. + type FirstLookup = { key: string; row: PtyProcessInfo | null } + const lookups = new WeakMap() const find = (rows: PtyProcessInfo[], paneKey: string, id: string | undefined | null) => { - let index = indexes.get(rows) - if (!index) { - indexes.set(rows, 'scanned') + const key = id ? `id:${id}` : `pane:${paneKey}` + let seen = lookups.get(rows) + if (!seen) { // Before a restored pane reattaches, the provider's own spawn record still names its PTY. const spawned = id ? [] : rows.filter((entry) => entry.paneKey === paneKey) - return ( + const row = (id ? rows.find((entry) => entry.id === id) : spawned.length === 1 && spawned[0]) || null - ) + lookups.set(rows, { key, row }) + return row } - if (index === 'scanned') { - index = indexInventory(rows) - indexes.set(rows, index) + if ('key' in seen) { + if (seen.key === key) { + return seen.row + } + seen = indexInventory(rows) + lookups.set(rows, seen) } - const spawned = id ? undefined : index.bySpawnPaneKey.get(paneKey) - return (id ? index.byId.get(id) : spawned?.length === 1 && spawned[0]) || null + const spawned = id ? undefined : seen.bySpawnPaneKey.get(paneKey) + return (id ? seen.byId.get(id) : spawned?.length === 1 && spawned[0]) || null } return async (paneKey, lookup) => { const id = options.getPtyId(paneKey) diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index bfbb2fa91ff9..8858d3f6879b 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -235,6 +235,8 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane(4050, [4050, 101, 4050, 'tmux -DL qa', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + runningPane(4050, [4050, 101, 4050, 'tmux -VL qa', 'S+'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane(4050, [4050, 101, 4050, 'tmux -Lc attach', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) // A foreground tmux command that attaches no session hosts nothing. diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index f61e1e3447b8..9852ed2930ec 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -36,10 +36,10 @@ function isAttachingTmuxClient(row: ProcessTableRow): boolean { let index = 0 while (args[index]?.startsWith('-')) { // Flags may be grouped (`-vc`); the rest of a group after -L/-S/-f/-T is that flag's value. - // -c runs a shell command and -D runs the server itself: neither is an attached client. + // -c runs a shell command, -D runs the server itself and -V/-h print and exit: no attached client. const flags = args[index].slice(1) const valueAt = flags.search(/[LSfT]/) - const notClientAt = flags.search(/[cD]/) + const notClientAt = flags.search(/[cDVh]/) if (notClientAt !== -1 && (valueAt === -1 || notClientAt < valueAt)) { return false } From ec7a1d0c91ffe356c32d85ebdbe167511d80acd3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:35:42 -0800 Subject: [PATCH 067/125] fix(sleep): index the PTY inventory only as far as lookups scan; new-session -d attaches nothing --- .../observations/local-tmux-managed-pty.ts | 56 +++++++++---------- .../tmux/server-tmux-legacy-sleep.test.ts | 6 ++ .../presence/pane-tmux-host-proof.ts | 10 +++- 3 files changed, 42 insertions(+), 30 deletions(-) diff --git a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts index 00d30ea5bdd1..cd0798453afd 100644 --- a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts @@ -13,28 +13,33 @@ export type LocalPtyInventoryReader = ( options?: { bySpawnPaneKey?: boolean } ) => Promise +/** A snapshot indexed as far as lookups have scanned it: no lookup visits more rows than a plain + * search would, and rows already passed are never scanned again. */ type InventoryIndex = { + rows: PtyProcessInfo[] + scanned: number byId: Map bySpawnPaneKey: Map } -function indexInventory(rows: PtyProcessInfo[]): InventoryIndex { - const byId = new Map() - const bySpawnPaneKey = new Map() - for (const row of rows) { - if (!byId.has(row.id)) { - byId.set(row.id, row) +function scanInventory(index: InventoryIndex, foundId?: string): void { + while (index.scanned < index.rows.length) { + const row = index.rows[index.scanned++] + if (!index.byId.has(row.id)) { + index.byId.set(row.id, row) } if (row.paneKey !== undefined) { - const spawned = bySpawnPaneKey.get(row.paneKey) + const spawned = index.bySpawnPaneKey.get(row.paneKey) if (spawned) { spawned.push(row) } else { - bySpawnPaneKey.set(row.paneKey, [row]) + index.bySpawnPaneKey.set(row.paneKey, [row]) } } + if (foundId !== undefined && row.id === foundId) { + return + } } - return { byId, bySpawnPaneKey } } /** Reuse the daemon's authenticated inventory; never resolve an SSH pane from the client. */ @@ -62,30 +67,23 @@ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalP } return pending } - // One pane's lookups scan once per snapshot as before; a second pane against the same snapshot - // (sleep capture walks every pane) indexes it once. - type FirstLookup = { key: string; row: PtyProcessInfo | null } - const lookups = new WeakMap() + const indexes = new WeakMap() const find = (rows: PtyProcessInfo[], paneKey: string, id: string | undefined | null) => { - const key = id ? `id:${id}` : `pane:${paneKey}` - let seen = lookups.get(rows) - if (!seen) { - // Before a restored pane reattaches, the provider's own spawn record still names its PTY. - const spawned = id ? [] : rows.filter((entry) => entry.paneKey === paneKey) - const row = - (id ? rows.find((entry) => entry.id === id) : spawned.length === 1 && spawned[0]) || null - lookups.set(rows, { key, row }) - return row + let index = indexes.get(rows) + if (!index) { + index = { rows, scanned: 0, byId: new Map(), bySpawnPaneKey: new Map() } + indexes.set(rows, index) } - if ('key' in seen) { - if (seen.key === key) { - return seen.row + if (id) { + if (!index.byId.has(id)) { + scanInventory(index, id) } - seen = indexInventory(rows) - lookups.set(rows, seen) + return index.byId.get(id) ?? null } - const spawned = id ? undefined : seen.bySpawnPaneKey.get(paneKey) - return (id ? seen.byId.get(id) : spawned?.length === 1 && spawned[0]) || null + // Before a restored pane reattaches, the provider's own spawn record still names its PTY. + scanInventory(index) + const spawned = index.bySpawnPaneKey.get(paneKey) + return spawned?.length === 1 ? spawned[0] : null } return async (paneKey, lookup) => { const id = options.getPtyId(paneKey) diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 8858d3f6879b..872cea63d8f2 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -237,6 +237,12 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane(4050, [4050, 101, 4050, 'tmux -VL qa', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + runningPane( + 4050, + [4050, 101, 4050, 'tmux -vL qa new-session -d ; wait-for build-ready', 'S+'], + ...TMUX + ) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane(4050, [4050, 101, 4050, 'tmux -Lc attach', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) // A foreground tmux command that attaches no session hosts nothing. diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index 9852ed2930ec..f0011618c72a 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -45,7 +45,15 @@ function isAttachingTmuxClient(row: ProcessTableRow): boolean { } index += valueAt !== -1 && valueAt === flags.length - 1 ? 2 : 1 } - return args[index] === undefined || isAttachingTmuxCommand(args[index]) + const command = args[index] + if (command === undefined) { + return true + } + // `new-session -d` only creates a session; reading any d flag after it as detached errs safe. + return ( + isAttachingTmuxCommand(command) && + !(command.startsWith('n') && args.slice(index + 1).some((arg) => /^-[^-]*d/.test(arg))) + ) } export async function readPaneTmuxHost( From 8d8443ea5103a52800cb9c88321fe7a7ef011b5c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:41:47 -0800 Subject: [PATCH 068/125] fix(sleep): only a tmux client's harmless flags may precede an attaching command --- .../server/testing/tmux/server-tmux-legacy-sleep.test.ts | 2 ++ .../agent-hook-listener/presence/pane-tmux-host-proof.ts | 7 +++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 872cea63d8f2..9db1b9663407 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -235,6 +235,8 @@ it('proves a tmux-hosted pane only from a complete process picture', async () => await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane(4050, [4050, 101, 4050, 'tmux -DL qa', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) + runningPane(4050, [4050, 101, 4050, 'tmux -dL qa', 'S+'], ...TMUX) + await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane(4050, [4050, 101, 4050, 'tmux -VL qa', 'S+'], ...TMUX) await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) runningPane( diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts index f0011618c72a..ed4052aed273 100644 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts @@ -35,12 +35,11 @@ function isAttachingTmuxClient(row: ProcessTableRow): boolean { const args = tokenizeCommandLine(row.command).slice(1) let index = 0 while (args[index]?.startsWith('-')) { - // Flags may be grouped (`-vc`); the rest of a group after -L/-S/-f/-T is that flag's value. - // -c runs a shell command, -D runs the server itself and -V/-h print and exit: no attached client. + // Flags may be grouped (`-vu`); the rest of a group after -L/-S/-f/-T is that flag's value. + // Only a client's harmless flags may precede the command; -c, -D, -V, -h and the rest attach nothing. const flags = args[index].slice(1) const valueAt = flags.search(/[LSfT]/) - const notClientAt = flags.search(/[cDVh]/) - if (notClientAt !== -1 && (valueAt === -1 || notClientAt < valueAt)) { + if (!/^[2ClNquv]*$/.test(valueAt === -1 ? flags : flags.slice(0, valueAt))) { return false } index += valueAt !== -1 && valueAt === flags.length - 1 ? 2 : 1 From 6f3a93fb472986eca007abe0e14abee343875fab Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:45:18 -0800 Subject: [PATCH 069/125] perf(sleep): keep main's inventory lookups; index only for sleep capture's tmux probe --- .../observations/local-hook-root-evidence.ts | 3 +- .../observations/local-tmux-managed-pty.ts | 57 +++++++++---------- 2 files changed, 28 insertions(+), 32 deletions(-) diff --git a/src/main/agent-hooks/observations/local-hook-root-evidence.ts b/src/main/agent-hooks/observations/local-hook-root-evidence.ts index 84d962a0858c..3ee412460225 100644 --- a/src/main/agent-hooks/observations/local-hook-root-evidence.ts +++ b/src/main/agent-hooks/observations/local-hook-root-evidence.ts @@ -26,6 +26,7 @@ export function installLocalHookRootEvidence(server: AgentHookServer): LocalPtyI }) if (process.platform !== 'win32') { const resolveRoot = createLocalHookPaneRootResolver(readInventory) + const tmuxRoot = createLocalHookPaneRootResolver(readInventory, true) // Root evidence and tmux host probes share one process-read budget; hook admission goes first. const slots = createHookProcessReadSlots() const gate = hookProcessReadGate(slots, undefined, 1) @@ -34,7 +35,7 @@ export function installLocalHookRootEvidence(server: AgentHookServer): LocalPtyI (request) => readPaneTmuxHost( { - resolveRoot, + resolveRoot: tmuxRoot, readProcesses: (pids) => readSelectedRows(pids, gate).catch(() => []), readTerminal: (tty) => readTerminalRows(tty, gate).catch(() => []) }, diff --git a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts index cd0798453afd..33b5666ee761 100644 --- a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts @@ -10,36 +10,31 @@ type InventoryOptions = { /** A pane's row in the owning provider's authenticated inventory, re-checked after the read. */ export type LocalPtyInventoryReader = ( paneKey: string, - options?: { bySpawnPaneKey?: boolean } + options?: { bySpawnPaneKey?: boolean; indexed?: boolean } ) => Promise -/** A snapshot indexed as far as lookups have scanned it: no lookup visits more rows than a plain - * search would, and rows already passed are never scanned again. */ type InventoryIndex = { - rows: PtyProcessInfo[] - scanned: number byId: Map bySpawnPaneKey: Map } -function scanInventory(index: InventoryIndex, foundId?: string): void { - while (index.scanned < index.rows.length) { - const row = index.rows[index.scanned++] - if (!index.byId.has(row.id)) { - index.byId.set(row.id, row) +function indexInventory(rows: PtyProcessInfo[]): InventoryIndex { + const byId = new Map() + const bySpawnPaneKey = new Map() + for (const row of rows) { + if (!byId.has(row.id)) { + byId.set(row.id, row) } if (row.paneKey !== undefined) { - const spawned = index.bySpawnPaneKey.get(row.paneKey) + const spawned = bySpawnPaneKey.get(row.paneKey) if (spawned) { spawned.push(row) } else { - index.bySpawnPaneKey.set(row.paneKey, [row]) + bySpawnPaneKey.set(row.paneKey, [row]) } } - if (foundId !== undefined && row.id === foundId) { - return - } } + return { byId, bySpawnPaneKey } } /** Reuse the daemon's authenticated inventory; never resolve an SSH pane from the client. */ @@ -67,31 +62,30 @@ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalP } return pending } - const indexes = new WeakMap() const find = (rows: PtyProcessInfo[], paneKey: string, id: string | undefined | null) => { + // Before a restored pane reattaches, the provider's own spawn record still names its PTY. + const spawned = id ? [] : rows.filter((entry) => entry.paneKey === paneKey) + return (id ? rows.find((entry) => entry.id === id) : spawned.length === 1 && spawned[0]) || null + } + // Sleep capture resolves every pane of a workspace against one snapshot; only it indexes. + const indexes = new WeakMap() + const findIndexed = (rows: PtyProcessInfo[], paneKey: string, id: string | undefined | null) => { let index = indexes.get(rows) if (!index) { - index = { rows, scanned: 0, byId: new Map(), bySpawnPaneKey: new Map() } + index = indexInventory(rows) indexes.set(rows, index) } - if (id) { - if (!index.byId.has(id)) { - scanInventory(index, id) - } - return index.byId.get(id) ?? null - } - // Before a restored pane reattaches, the provider's own spawn record still names its PTY. - scanInventory(index) - const spawned = index.bySpawnPaneKey.get(paneKey) - return spawned?.length === 1 ? spawned[0] : null + const spawned = id ? undefined : index.bySpawnPaneKey.get(paneKey) + return (id ? index.byId.get(id) : spawned?.length === 1 && spawned[0]) || null } return async (paneKey, lookup) => { + const lookUp = lookup?.indexed ? findIndexed : find const id = options.getPtyId(paneKey) if (!id && !lookup?.bySpawnPaneKey) { return null } const cachedAt = capturedAt - let row = find(await read(), paneKey, id) + let row = lookUp(await read(), paneKey, id) // A snapshot taken before this PTY spawned (or reported its guest root) is no answer for it. if ( (!row || (row.wslDistro && !row.wslGuestRoot)) && @@ -100,7 +94,7 @@ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalP cachedAt !== forcedAt ) { capturedAt = -Infinity - row = find(await read(), paneKey, id) + row = lookUp(await read(), paneKey, id) forcedAt = capturedAt } return row && options.getPtyId(paneKey) === id ? row : null @@ -134,10 +128,11 @@ export function createLocalTmuxManagedPtyResolver( /** The root a hook must descend from to own a pane; a provider without root identity (an older * daemon's retained PTY) keeps the legacy path. */ export function createLocalHookPaneRootResolver( - readInventory: LocalPtyInventoryReader + readInventory: LocalPtyInventoryReader, + indexed = false ): HookPaneProcessIo['resolveRoot'] { return async (paneKey, worktreeId) => { - const row = await readInventory(paneKey, { bySpawnPaneKey: true }).catch(() => null) + const row = await readInventory(paneKey, { bySpawnPaneKey: true, indexed }).catch(() => null) if (!row || row.wslDistro || (worktreeId && row.worktreeId && row.worktreeId !== worktreeId)) { return null } From 87dc6ed5769c603ba7ac7cbed7c012c44482efbf Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:39:33 -0800 Subject: [PATCH 070/125] refactor(sleep): record tmux/shared topology when the hook row is written A conversation a tmux or shared server keeps alive now carries sharedHost on its status, and no live checkpoint is written for it, so a restart cannot resume it beside its server. Codex hooks report their tmux pane like Claude's. This replaces the sleep-time tmux process probe and its release paths. --- .../installation/scripts/hook-post-command.ts | 4 +- .../scripts/hook-process-capture.ts | 9 +- .../observations/local-hook-root-evidence.ts | 27 +- .../observations/local-tmux-managed-pty.ts | 47 +-- .../agent-hooks/server/agent-hook-server.ts | 48 +-- .../server/cli-writer-observation.ts | 30 +- .../agent-hooks/server/cli-writer-topology.ts | 24 ++ src/main/agent-hooks/server/server-state.ts | 11 +- .../server/server-status-identity.ts | 2 + .../agent-hooks/server/server-tab-cleanup.ts | 6 - .../agent-hooks/server/server-tmux-status.ts | 33 +-- .../tmux/server-tmux-legacy-sleep.test.ts | 276 ++++-------------- .../hooks/definitions/codex-hook-script.ts | 2 + .../runtime-construction-dependencies.ts | 4 +- .../stop/hook-status-resume-records.ts | 1 + .../stop/worktree-sleep-resume-recording.ts | 3 +- .../normalize-agent-status-event.ts | 4 +- .../contracts/agent-status-contract.ts | 1 + .../agent-status-live-entry-builder.ts | 1 + .../hook-process-root-evidence-reader.ts | 32 +- .../presence/hook-process-root-evidence.ts | 10 +- .../presence/pane-tmux-host-proof.ts | 109 ------- .../resume/agent-resume-record-from-status.ts | 2 + .../contracts/agent-status-ipc-payload.ts | 2 + .../contracts/agent-status-types.ts | 2 + 25 files changed, 145 insertions(+), 545 deletions(-) create mode 100644 src/main/agent-hooks/server/cli-writer-topology.ts delete mode 100644 src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts diff --git a/src/main/agent-hooks/installation/scripts/hook-post-command.ts b/src/main/agent-hooks/installation/scripts/hook-post-command.ts index b0c6ce3e8079..acd8886d257f 100644 --- a/src/main/agent-hooks/installation/scripts/hook-post-command.ts +++ b/src/main/agent-hooks/installation/scripts/hook-post-command.ts @@ -51,8 +51,8 @@ export function buildPosixAgentHookPostCommand( ): string[] { const curlCommand = posixCurlCommand(options.curlCommand ?? 'curl') const indent = options.indent ?? ' ' - // Only Claude's capture sets this; the host checks the attachment itself before trusting it. - const tmux = source === 'claude' + // Only Claude's and Codex's scripts capture this; the host checks the attachment before trusting it. + const tmux = source === 'claude' || source === 'codex' // Names the decision format the script prints; absent, Orca never waits on plugins. const decision = options.decisionHeaderVar ? [` ${indent}-H "X-Orca-Hook-Decision: \${${options.decisionHeaderVar}:-}" \\`] diff --git a/src/main/agent-hooks/installation/scripts/hook-process-capture.ts b/src/main/agent-hooks/installation/scripts/hook-process-capture.ts index f27524538e0f..e49f37b3aca2 100644 --- a/src/main/agent-hooks/installation/scripts/hook-process-capture.ts +++ b/src/main/agent-hooks/installation/scripts/hook-process-capture.ts @@ -44,7 +44,14 @@ export function buildHookProcessCapture(): string[] { ' [ -z "$orca_agent_start" ] || orca_agent_process="{\\"pid\\":$orca_agent_pid,\\"platform\\":\\"darwin\\",\\"startTime\\":\\"$orca_agent_start\\"}"', ' fi ;;', 'esac', - // A tmux pane's own server, socket and pane id; only a lookup hint for the host's attachment check. + ...buildHookTmuxPaneCapture() + ] +} + +/** A tmux pane's own server, socket and pane id: a hook from inside tmux names a conversation its + * server, not the Orca pane, keeps alive; also a lookup hint for the host's attachment check. */ +export function buildHookTmuxPaneCapture(): string[] { + return [ 'orca_tmux_pane=', 'case "${TMUX_PANE:-}" in %[0-9]*) [ -z "${TMUX:-}" ] || orca_tmux_pane="$TMUX_PANE ${TMUX%,*,*}" ;; esac' ] diff --git a/src/main/agent-hooks/observations/local-hook-root-evidence.ts b/src/main/agent-hooks/observations/local-hook-root-evidence.ts index 3ee412460225..413ae59469b6 100644 --- a/src/main/agent-hooks/observations/local-hook-root-evidence.ts +++ b/src/main/agent-hooks/observations/local-hook-root-evidence.ts @@ -4,16 +4,7 @@ import { createLocalPtyInventoryReader, type LocalPtyInventoryReader } from './local-tmux-managed-pty' -import { - createHookProcessReadSlots, - createLocalHookRootEvidenceReader, - hookProcessReadGate -} from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' -import { readPaneTmuxHost } from '../../../shared/agent-hook-listener/presence/pane-tmux-host-proof' -import { - readSelectedRows, - readTerminalRows -} from '../../../shared/agent-hook-listener/presence/tmux-host-attachment-probe' +import { createLocalHookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' import { getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' @@ -25,22 +16,8 @@ export function installLocalHookRootEvidence(server: AgentHookServer): LocalPtyI listProcesses: () => getLocalPtyProvider().listProcesses() }) if (process.platform !== 'win32') { - const resolveRoot = createLocalHookPaneRootResolver(readInventory) - const tmuxRoot = createLocalHookPaneRootResolver(readInventory, true) - // Root evidence and tmux host probes share one process-read budget; hook admission goes first. - const slots = createHookProcessReadSlots() - const gate = hookProcessReadGate(slots, undefined, 1) server.setHookRootEvidenceReader( - createLocalHookRootEvidenceReader(resolveRoot, slots), - (request) => - readPaneTmuxHost( - { - resolveRoot: tmuxRoot, - readProcesses: (pids) => readSelectedRows(pids, gate).catch(() => []), - readTerminal: (tty) => readTerminalRows(tty, gate).catch(() => []) - }, - request - ) + createLocalHookRootEvidenceReader(createLocalHookPaneRootResolver(readInventory)) ) } return readInventory diff --git a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts index 33b5666ee761..41c80ad8a31c 100644 --- a/src/main/agent-hooks/observations/local-tmux-managed-pty.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts @@ -10,33 +10,9 @@ type InventoryOptions = { /** A pane's row in the owning provider's authenticated inventory, re-checked after the read. */ export type LocalPtyInventoryReader = ( paneKey: string, - options?: { bySpawnPaneKey?: boolean; indexed?: boolean } + options?: { bySpawnPaneKey?: boolean } ) => Promise -type InventoryIndex = { - byId: Map - bySpawnPaneKey: Map -} - -function indexInventory(rows: PtyProcessInfo[]): InventoryIndex { - const byId = new Map() - const bySpawnPaneKey = new Map() - for (const row of rows) { - if (!byId.has(row.id)) { - byId.set(row.id, row) - } - if (row.paneKey !== undefined) { - const spawned = bySpawnPaneKey.get(row.paneKey) - if (spawned) { - spawned.push(row) - } else { - bySpawnPaneKey.set(row.paneKey, [row]) - } - } - } - return { byId, bySpawnPaneKey } -} - /** Reuse the daemon's authenticated inventory; never resolve an SSH pane from the client. */ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalPtyInventoryReader { let pending: Promise | undefined @@ -67,25 +43,13 @@ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalP const spawned = id ? [] : rows.filter((entry) => entry.paneKey === paneKey) return (id ? rows.find((entry) => entry.id === id) : spawned.length === 1 && spawned[0]) || null } - // Sleep capture resolves every pane of a workspace against one snapshot; only it indexes. - const indexes = new WeakMap() - const findIndexed = (rows: PtyProcessInfo[], paneKey: string, id: string | undefined | null) => { - let index = indexes.get(rows) - if (!index) { - index = indexInventory(rows) - indexes.set(rows, index) - } - const spawned = id ? undefined : index.bySpawnPaneKey.get(paneKey) - return (id ? index.byId.get(id) : spawned?.length === 1 && spawned[0]) || null - } return async (paneKey, lookup) => { - const lookUp = lookup?.indexed ? findIndexed : find const id = options.getPtyId(paneKey) if (!id && !lookup?.bySpawnPaneKey) { return null } const cachedAt = capturedAt - let row = lookUp(await read(), paneKey, id) + let row = find(await read(), paneKey, id) // A snapshot taken before this PTY spawned (or reported its guest root) is no answer for it. if ( (!row || (row.wslDistro && !row.wslGuestRoot)) && @@ -94,7 +58,7 @@ export function createLocalPtyInventoryReader(options: InventoryOptions): LocalP cachedAt !== forcedAt ) { capturedAt = -Infinity - row = lookUp(await read(), paneKey, id) + row = find(await read(), paneKey, id) forcedAt = capturedAt } return row && options.getPtyId(paneKey) === id ? row : null @@ -128,11 +92,10 @@ export function createLocalTmuxManagedPtyResolver( /** The root a hook must descend from to own a pane; a provider without root identity (an older * daemon's retained PTY) keeps the legacy path. */ export function createLocalHookPaneRootResolver( - readInventory: LocalPtyInventoryReader, - indexed = false + readInventory: LocalPtyInventoryReader ): HookPaneProcessIo['resolveRoot'] { return async (paneKey, worktreeId) => { - const row = await readInventory(paneKey, { bySpawnPaneKey: true, indexed }).catch(() => null) + const row = await readInventory(paneKey, { bySpawnPaneKey: true }).catch(() => null) if (!row || row.wslDistro || (worktreeId && row.worktreeId && row.worktreeId !== worktreeId)) { return null } diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 8318f626abbf..48a44a0e9ebf 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -4,14 +4,9 @@ import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normal import { parseFormEncodedBody } from '../../../shared/agent-hook-listener/request-body' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' -import { - cliWriterTopology, - tmuxCliWriterEvent, - type CliWriterObservation -} from './cli-writer-observation' +import { cliWriterTopology, type CliWriterObservation } from './cli-writer-observation' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' -import type { EnrichedAgentHookEventPayload } from './server-types' import { ClaudeSessionContinuationTracker, resolvePaneClaudeContinuation @@ -110,13 +105,9 @@ export class AgentHookServer extends AgentHookServerLifecycle { /** Include retained exits proven at or after `exitedSince`. */ async checkAgentPresenceSince( paneKey: string, - exitedSince: number, - options?: { sleepCapture?: true } + exitedSince: number ): Promise { - const [verdict] = await Promise.all([ - this.checkAgentPresence(paneKey), - this.observeTmuxHostedWriter(paneKey, options?.sleepCapture === true) - ]) + const verdict = await this.checkAgentPresence(paneKey) // A replaced owner's probe result counts only if its exit was retained. if (verdict !== null && verdict !== 'exited') { return verdict @@ -132,39 +123,6 @@ export class AgentHookServer extends AgentHookServerLifecycle { return exit !== undefined && exit.at >= exitedSince ? 'exited' : null } - /** Legacy hooks cannot say a tmux server hosts them; the pane's foreground client can, before - * a sleep captures the conversation as the pane's own. Other presence reads never probe. */ - private async observeTmuxHostedWriter(paneKey: string, sleepCapture: boolean): Promise { - if (!sleepCapture) { - return - } - const resolved = this.resolvePaneKeyAlias(paneKey) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: main stores enriched accepted rows in the base-typed cache. - const row = this.state.lastStatusByPaneKey.get(resolved) as - | EnrichedAgentHookEventPayload - | undefined - const binding = row?.providerSession - const read = this.readPaneTmuxHost - if (!row) { - return this.releaseTmuxHostedCheckpoint(resolved) - } - if (!read || !binding || row.connectionId !== null || cliWriterTopology(row) !== 'pane-owned') { - return - } - const presence = row.agentPresence - const hosted = await read({ - paneKey: resolved, - worktreeId: row.worktreeId, - ...(presence?.process && !presence.ended ? { process: presence.process } : {}) - }).catch(() => false) - if (hosted && this.state.lastStatusByPaneKey.get(resolved) === row) { - const hostedRow = tmuxCliWriterEvent(row) - if (this.writeLegacyStatusRow(hostedRow)) { - this.commitStatusRowMutation(row, hostedRow) - } - } - } - checkAgentPresence(paneKey: string): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) this.followClaudeSessionContinuation(resolved) diff --git a/src/main/agent-hooks/server/cli-writer-observation.ts b/src/main/agent-hooks/server/cli-writer-observation.ts index ee040f6f7d2c..3efa242a1cb8 100644 --- a/src/main/agent-hooks/server/cli-writer-observation.ts +++ b/src/main/agent-hooks/server/cli-writer-observation.ts @@ -12,18 +12,20 @@ import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/ import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' +import { + cliWriterTopology, + OPEN_CODE_WRITER_TOPOLOGY, + type CliWriterTopology +} from './cli-writer-topology' import { readTmuxHookPane, readTmuxHookPaneHint } from '../../../shared/agent-hook-listener/presence/tmux-client-attachment' -// Execution metadata follows the conversation binding and disappears at serialization. -export const OPEN_CODE_WRITER_TOPOLOGY = Symbol('openCodeWriterTopology') - export type CliWriterObservation = { current: () => boolean presence: () => Promise - topology: 'pane-owned' | 'shared' | 'unverifiable' + topology: CliWriterTopology } export function retainOpenCodeWriterTopology( @@ -50,24 +52,6 @@ export function retainOpenCodeWriterTopology( Object.defineProperty(event.providerSession, OPEN_CODE_WRITER_TOPOLOGY, { value: topology }) } -/** OpenCode-family servers can outlive their pane; only the binding they posted can prove otherwise. */ -export function cliWriterTopology(row: AgentHookEventPayload): CliWriterObservation['topology'] { - const binding = row.providerSession - const topology = - binding && OPEN_CODE_WRITER_TOPOLOGY in binding ? binding[OPEN_CODE_WRITER_TOPOLOGY] : undefined - return topology === 'shared' - ? 'shared' - : row.source !== 'opencode' && - row.source !== 'opencode2' && - row.source !== 'mimo-code' && - row.payload.agentType !== 'opencode' && - row.payload.agentType !== 'opencode2' - ? 'pane-owned' - : topology === 'pane-owned' - ? topology - : 'unverifiable' -} - /** A tmux server outlives the pane it was started from, so nothing it publishes is pane-owned. */ export function tmuxCliWriterEvent(row: T): T { if (!row.providerSession) { @@ -183,3 +167,5 @@ export function deriveCliWriterTopology( } return { ...row, providerSession: { ...binding } } } + +export { cliWriterTopology, OPEN_CODE_WRITER_TOPOLOGY } diff --git a/src/main/agent-hooks/server/cli-writer-topology.ts b/src/main/agent-hooks/server/cli-writer-topology.ts new file mode 100644 index 000000000000..159c61921a6d --- /dev/null +++ b/src/main/agent-hooks/server/cli-writer-topology.ts @@ -0,0 +1,24 @@ +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' + +// Execution metadata follows the conversation binding and disappears at serialization. +export const OPEN_CODE_WRITER_TOPOLOGY = Symbol('openCodeWriterTopology') + +export type CliWriterTopology = 'pane-owned' | 'shared' | 'unverifiable' + +/** OpenCode-family servers can outlive their pane; only the binding they posted can prove otherwise. */ +export function cliWriterTopology(row: AgentHookEventPayload): CliWriterTopology { + const binding = row.providerSession + const topology = + binding && OPEN_CODE_WRITER_TOPOLOGY in binding ? binding[OPEN_CODE_WRITER_TOPOLOGY] : undefined + return topology === 'shared' + ? 'shared' + : row.source !== 'opencode' && + row.source !== 'opencode2' && + row.source !== 'mimo-code' && + row.payload.agentType !== 'opencode' && + row.payload.agentType !== 'opencode2' + ? 'pane-owned' + : topology === 'pane-owned' + ? topology + : 'unverifiable' +} diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 1b9794f79bc7..0e291d21a4f4 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -101,6 +101,7 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract !row.agentPresence.ended ? { suspended: true as const } : {}), + // A shared host's conversation never leaves a saved record (sharedHost), so one is the pane's. processTopology: row ? (legacy ? cliWriterTopology(row) : 'shared') : 'pane-owned' } : null @@ -114,16 +115,6 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract this.retirePaneResume(paneKeys, status, exitedAt) } - /** A shared server's client left the pane; its conversation lives on there, never resumed here. - * `releasedAt` bounds which saved record retires; one saved later is a newer conversation. */ - protected releaseSharedPaneConversation( - paneKey: string, - status: PaneAgentIdentity['status'], - releasedAt = Date.now() - ): void { - this.retirePaneResume(this.paneKeysWithAliases(paneKey), status, releasedAt) - } - private paneKeysWithAliases(paneKey: string): Set { const stable = this.resolvePaneKeyAlias(paneKey) const aliases = [...this.legacyPaneKeyAliases].filter(([, a]) => a.stablePaneKey === stable) diff --git a/src/main/agent-hooks/server/server-status-identity.ts b/src/main/agent-hooks/server/server-status-identity.ts index 7775ff339f7b..1220738d3f87 100644 --- a/src/main/agent-hooks/server/server-status-identity.ts +++ b/src/main/agent-hooks/server/server-status-identity.ts @@ -13,6 +13,7 @@ import { import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { EnrichedAgentHookEventPayload } from './server-types' import { AGENT_PROMPT_SENT_AGENT_KINDS } from './server-constants' +import { cliWriterTopology } from './cli-writer-topology' import { MAX_PANE_KEY_LEN } from '../../../shared/agent-hook-listener/listener-limits' export function agentTypeToPromptSentAgentKind(agentType: AgentType | undefined): AgentKind { @@ -70,6 +71,7 @@ export function toAgentStatusIpcPayload( ...(entry.turnStartedAt !== undefined ? { turnStartedAt: entry.turnStartedAt } : {}), ...pickHostTurnEnd(entry), ...(entry.providerSession ? { providerSession: entry.providerSession } : {}), + ...(cliWriterTopology(entry) === 'shared' ? { sharedHost: true as const } : {}), ...(entry.providerSessionOnly ? { providerSessionOnly: true } : {}), ...(entry.promptInteractionKey ? { promptInteractionKey: entry.promptInteractionKey } : {}), ...(entry.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index d865ded30279..f96532a0a864 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -29,9 +29,6 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { { ...options, preserveResumeIdentity: !options?.confirmedExit && !shared }, (key) => this.clearRevokedPaneState(key) ) - if (shared) { - this.releaseSharedPaneConversation(paneKey, identity.status) - } for (const key of untouched) { this.clearTmuxInnerSubjects(key) this.clearPaneProcessState(key) @@ -73,9 +70,6 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { preserveResumeIdentity: true, confirmedExit: confirmedExit === true }) - if (shared) { - this.releaseSharedPaneConversation(resolved, identity.status) - } } dropPersistedStatusEntry(identity: AgentStatusCacheIdentity): boolean { diff --git a/src/main/agent-hooks/server/server-tmux-status.ts b/src/main/agent-hooks/server/server-tmux-status.ts index e86d93da17e7..5ec7d65a5b73 100644 --- a/src/main/agent-hooks/server/server-tmux-status.ts +++ b/src/main/agent-hooks/server/server-tmux-status.ts @@ -1,5 +1,4 @@ import type { HookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import type { PaneTmuxHostReader } from '../../../shared/agent-hook-listener/presence/pane-tmux-host-proof' import { TmuxAgentHookOwner } from '../../../shared/agent-hook-listener/presence/tmux-agent-hook-owner' import type { TmuxManagedPty } from '../../../shared/agent-hook-listener/presence/tmux-agent-hook-contract' import { commitTmuxSelectedStatus } from '../../../shared/agent-hook-listener/presence/tmux-selected-status' @@ -16,36 +15,11 @@ import { tmuxCliWriterEvent } from './cli-writer-observation' import { agentSightingOf } from '../identity/pane-agent-identities' export abstract class AgentHookServerTmuxStatus extends AgentHookServerOpenCodeBinder { - protected readPaneTmuxHost: PaneTmuxHostReader | undefined /** Unset in tests and embedders without a process table: every acquisition reads as unknown. */ protected readHookRootEvidence: HookRootEvidenceReader | undefined - setHookRootEvidenceReader(reader: HookRootEvidenceReader, tmuxHost?: PaneTmuxHostReader): void { + setHookRootEvidenceReader(reader: HookRootEvidenceReader): void { this.readHookRootEvidence = reader - this.readPaneTmuxHost = tmuxHost - } - - /** A restart forgets the tmux-selected row; a checkpoint shown through the pane's tmux client was - * never the pane's own process. */ - protected async releaseTmuxHostedCheckpoint(paneKey: string): Promise { - const read = this.readPaneTmuxHost - const probed = this.terminalPaneLifecycle?.readSavedRecord?.(paneKey) - const identity = read && !this.getTmuxSelectedStatus(paneKey) && this.paneAgentIdentity(paneKey) - if ( - !read || - !identity || - identity.ended || - identity.status.connectionId !== null || - !identity.status.worktreeId || - !(await read({ paneKey, worktreeId: identity.status.worktreeId }).catch(() => false)) || - this.state.lastStatusByPaneKey.has(paneKey) || - this.getTmuxSelectedStatus(paneKey) || - // A record saved during the probe is a newer conversation; it stays. - this.terminalPaneLifecycle?.readSavedRecord?.(paneKey) !== probed - ) { - return - } - this.releaseSharedPaneConversation(paneKey, identity.status, identity.status.receivedAt) } private tmuxOwner: TmuxAgentHookOwner | undefined @@ -66,8 +40,6 @@ export abstract class AgentHookServerTmuxStatus extends AgentHookServerOpenCodeB if (this.getAgentStatusDisposition(paneKey) === 'suppress') { return } - // Read before the clear below drops the selected row, the only mark that it's shared. - const identity = this.paneAgentIdentity(paneKey) if (subject && !this.canonicalSubjectsByPane.has(paneKey)) { this.canonicalSubjectsByPane.set( paneKey, @@ -77,9 +49,6 @@ export abstract class AgentHookServerTmuxStatus extends AgentHookServerOpenCodeB } this.clearTmuxSelectedStatus(paneKey, true) this.clearPaneState(paneKey, { preserveTmuxInnerSubjects: true, statusUnavailable: true }) - if (identity?.processTopology === 'shared') { - this.releaseSharedPaneConversation(paneKey, identity.status) - } } }) return this.tmuxOwner diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index 9db1b9663407..fd2107e58e3b 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -4,7 +4,6 @@ import { NOW, TMUX, TMUX_HINT, - codexTurn, createServer, hook, io, @@ -18,9 +17,9 @@ import { AgentStatusObservedPaneIdentityCapture } from '../../../../runtime/terminal/identity/agent-status-observed-pane-identity' import { readHookRootEvidence } from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import { readPaneTmuxHost } from '../../../../../shared/agent-hook-listener/presence/pane-tmux-host-proof' import { captureWorktreeSleepResumeRecords } from '../../../../runtime/terminal/stop/worktree-sleep-resume-records' -import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' +import { resumeStatusFromHookRow } from '../../../../runtime/terminal/stop/hook-status-resume-records' +import { liveResumeRecord } from '../../../../../shared/agent-session/lifecycle/resume/agent-resume-record-from-status' vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) @@ -33,6 +32,23 @@ registerRootTestHarness() // The pane shows the tmux session through its foreground client. const CLIENT: Proc = [4050, 101, 4050, 'tmux -L qa attach', 'S+'] +// A pane the runtime places, so the hook's binding keeps the topology it reported. +async function placedServer(): Promise { + const server = await createServer() + server.setHookRootEvidenceReader((request) => readHookRootEvidence(request, io)) + const identities = new AgentStatusObservedPaneIdentities() + const observed = new AgentStatusObservedPaneIdentityCapture(identities) + const runtime = { + getAgentStatusTerminalHandleForPaneKey: () => 'terminal-a', + getTerminalProcessIncarnation: () => 'execution-a', + getAgentStatusOrchestrationContextForPaneKey: () => undefined + } + observed.attach(runtime) + server.subscribeEnrichedStatus((row) => observed.observe(row)) + server.setCliWriterExecutionMatcher(identities, runtime) + return server +} + it.each([ [ 'claude', @@ -44,29 +60,25 @@ it.each([ prompt: 'In tmux' }) ], - ['codex', (server: RootTestServer) => codexTurn(server)] + [ + 'codex', + (server: RootTestServer) => + hook(server, 'UserPromptSubmit', { + session: 'cx', + pid: null, + prompt: 'task', + source: 'codex', + tmuxPane: TMUX_HINT + }) + ] ] as const)( - 'does not capture a legacy %s whose tmux server outlives the sleeping pane', + 'does not capture a %s whose tmux server outlives the sleeping pane', async (_agent, turn) => { - const server = await createServer() - server.setHookRootEvidenceReader( - (request) => readHookRootEvidence(request, io), - (request) => readPaneTmuxHost(io, request) - ) - const identities = new AgentStatusObservedPaneIdentities() - const observed = new AgentStatusObservedPaneIdentityCapture(identities) - const runtime = { - getAgentStatusTerminalHandleForPaneKey: () => 'terminal-a', - getTerminalProcessIncarnation: () => 'execution-a', - getAgentStatusOrchestrationContextForPaneKey: () => undefined - } - observed.attach(runtime) - server.subscribeEnrichedStatus((row) => observed.observe(row)) - server.setCliWriterExecutionMatcher(identities, runtime) + const server = await placedServer() runningPane(4050, CLIENT, ...TMUX) await turn(server) expect(server.row()).toMatchObject({ state: 'working', providerSession: {} }) - await server.checkAgentPresenceSince(PANE, 0, { sleepCapture: true }) + await server.checkAgentPresenceSince(PANE, 0) // A fresh hook can land between capture's presence check and the PTY's physical stop. await turn(server) server.setTerminalPaneLifecycle({ @@ -83,8 +95,7 @@ it.each([ launchByPtyId: new Map(), readRowsForPane: (key) => server.getStatusSnapshotForPane(key), readIdentity: (key, saved) => server.paneAgentIdentity(key, saved), - checkAgentPresence: (key, since) => - server.checkAgentPresenceSince(key, since ?? 0, { sleepCapture: true }), + checkAgentPresence: (key, since) => server.checkAgentPresenceSince(key, since ?? 0), capturedAt: NOW }) expect(capture.get('pty')).toEqual({ records: [], retiredPaneKeys: [PANE] }) @@ -97,201 +108,28 @@ it.each([ } ) -it('does not recapture a detached tmux writer from its remaining live checkpoint', async () => { - const server = await createServer() - server.setHookRootEvidenceReader( - (request) => readHookRootEvidence(request, io), - (request) => readPaneTmuxHost(io, request) - ) - const identities = new AgentStatusObservedPaneIdentities() - const observed = new AgentStatusObservedPaneIdentityCapture(identities) - const runtime = { - getAgentStatusTerminalHandleForPaneKey: () => 'terminal-a', - getTerminalProcessIncarnation: () => 'execution-a', - getAgentStatusOrchestrationContextForPaneKey: () => undefined - } - observed.attach(runtime) - server.subscribeEnrichedStatus((row) => observed.observe(row)) - server.setCliWriterExecutionMatcher(identities, runtime) - runningPane(4050, CLIENT, ...TMUX) - await hook(server, 'UserPromptSubmit', { - session: 'detached-session', - pid: 4043, - tmuxPane: TMUX_HINT, - prompt: 'In tmux' - }) - // Nothing probes the pane while the client is attached; only the hook says it ran in tmux. - let saved: SleepingAgentSessionRecord | undefined = { - paneKey: PANE, - worktreeId: 'wt-1', - agent: 'claude', - providerSession: { key: 'session_id', id: 'detached-session' }, - prompt: 'In tmux', - state: 'done', - capturedAt: NOW, - updatedAt: NOW, - origin: 'live' - } - let stopping = false - server.setTerminalPaneLifecycle({ - ownsProcess: () => true, - isStopping: () => stopping, - isReversibleStop: () => true, - isPlaced: () => true, - readSavedRecord: () => saved, - retireSavedRecord: () => { - saved = undefined - } - }) - // Detach ends the outer command, while the original agent remains under its server. - runningPane(101, ...TMUX) - // The tmux client's command finished after an earlier finish retired the launch: no exit named. - server.retireProcessAuthority(PANE, { confirmedExit: false }) - expect(saved).toBeUndefined() - expect(server.row()).toBeUndefined() - // The sleep's physical stop must not promote a stale checkpoint into a pane-owned agent. - stopping = true - expect(server.settleTerminalPaneSleep(PANE, 'pty')).toBe(false) - const capture = await captureWorktreeSleepResumeRecords({ - worktreeId: 'wt-1', - paneKeysByPtyId: new Map([['pty', [PANE]]]), - launchByPtyId: new Map(), - readRowsForPane: (key) => server.getStatusSnapshotForPane(key), - readSavedRecord: async () => saved, - readIdentity: (key, record) => server.paneAgentIdentity(key, record), - checkAgentPresence: (key, since) => - server.checkAgentPresenceSince(key, since ?? 0, { sleepCapture: true }), - capturedAt: NOW + 1_000 - }) - expect(capture.get('pty')?.records).toEqual([]) -}) - -it('does not resume a checkpoint the pane reaches through its tmux client after a restart', async () => { - // A restart forgot the tmux row; the client still shows the agent before it hooks again. - const server = await createServer() - server.setHookRootEvidenceReader( - (request) => readHookRootEvidence(request, io), - (request) => readPaneTmuxHost(io, request) - ) - runningPane(4050, CLIENT, ...TMUX) - let saved: SleepingAgentSessionRecord | undefined = { - paneKey: PANE, - worktreeId: 'wt-1', - agent: 'claude', - providerSession: { key: 'session_id', id: 'restarted-session' }, - prompt: 'In tmux', - state: 'done', - capturedAt: NOW, - updatedAt: NOW, - origin: 'live' +it('leaves a tmux-hosted conversation no checkpoint, so a restart cannot resume it beside its server', async () => { + const checkpointOf = async (tmuxPane?: string) => { + const server = await placedServer() + await hook(server, 'UserPromptSubmit', { + session: 'detached-session', + pid: 4043, + prompt: 'In tmux', + ...(tmuxPane ? { tmuxPane } : {}) + }) + const row = server.row() + const status = row && resumeStatusFromHookRow(row, undefined) + return status + ? liveResumeRecord({ + entry: status, + retainsResumableIdentity: false, + worktreeIdOf: () => 'wt-1', + tabOf: () => undefined, + capturedAt: NOW + }) + : null } - server.setTerminalPaneLifecycle({ - ownsProcess: () => true, - isStopping: () => false, - isReversibleStop: () => true, - isPlaced: () => true, - readSavedRecord: () => saved, - retireSavedRecord: () => { - saved = undefined - } - }) - // Ordinary presence reads (fleet status) don't pay for the tmux probe. - await server.checkAgentPresenceSince(PANE, 0) - expect(saved).toBeDefined() - const capture = await captureWorktreeSleepResumeRecords({ - worktreeId: 'wt-1', - paneKeysByPtyId: new Map([['pty', [PANE]]]), - launchByPtyId: new Map(), - readRowsForPane: (key) => server.getStatusSnapshotForPane(key), - readSavedRecord: async () => saved, - readIdentity: (key, record) => server.paneAgentIdentity(key, record), - checkAgentPresence: (key, since) => - server.checkAgentPresenceSince(key, since ?? 0, { sleepCapture: true }), - capturedAt: NOW + 1_000 - }) - expect(saved).toBeUndefined() - expect(capture.get('pty')?.records).toEqual([]) -}) - -it('proves a tmux-hosted pane only from a complete process picture', async () => { - const pane = { paneKey: PANE, worktreeId: 'wt-1' } - const agent = { ...pane, process: { pid: 4043, platform: 'darwin', startTime: 'start' } as const } - runningPane(4050, CLIENT, ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) - await expect(readPaneTmuxHost(io, agent)).resolves.toBe(true) - // The pane's own suspended agent stays behind an unrelated tmux client; other jobs don't matter. - runningPane(4050, CLIENT, [4060, 101, 4060, 'claude', 'T'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) - runningPane(4050, CLIENT, [4070, 101, 4070, 'sleep 9999'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) - // An unreadable job might be the pane's own agent. - runningPane(4050, CLIENT, [4080, 101, 4080, '(claude)', 'T'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) - // tmux resolves an unambiguous prefix, so `att` attaches. - runningPane(4050, [4050, 101, 4050, 'tmux -L qa att -t cl', 'S+'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) - // Grouped flags: `-vc new` runs a shell command, while `-Lc` names a socket. - runningPane(4050, [4050, 101, 4050, 'tmux -vc new', 'S+'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) - runningPane(4050, [4050, 101, 4050, 'tmux -DL qa', 'S+'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) - runningPane(4050, [4050, 101, 4050, 'tmux -dL qa', 'S+'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) - runningPane(4050, [4050, 101, 4050, 'tmux -VL qa', 'S+'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) - runningPane( - 4050, - [4050, 101, 4050, 'tmux -vL qa new-session -d ; wait-for build-ready', 'S+'], - ...TMUX - ) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) - runningPane(4050, [4050, 101, 4050, 'tmux -Lc attach', 'S+'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(true) - // A foreground tmux command that attaches no session hosts nothing. - runningPane(4050, [4050, 101, 4050, 'tmux wait-for build-ready', 'S+'], ...TMUX) - await expect(readPaneTmuxHost(io, pane)).resolves.toBe(false) - // An agent whose ancestry cannot be read is not proven to live outside the pane. - runningPane(4050, CLIENT, [4043, 4042, 4043, 'claude', 'S+', 'ttys011']) - await expect(readPaneTmuxHost(io, agent)).resolves.toBe(false) -}) - -it('keeps a checkpoint saved while its tmux release was probing', async () => { - const server = await createServer() - const record = (id: string, updatedAt: number): SleepingAgentSessionRecord => ({ - paneKey: PANE, - worktreeId: 'wt-1', - agent: 'claude', - providerSession: { key: 'session_id', id }, - prompt: 'In tmux', - state: 'done', - capturedAt: updatedAt, - updatedAt, - origin: 'live' - }) - // Saved after the probe began, with the same clock as the record it replaces. - const replacement = record('replacement', NOW) - let saved: SleepingAgentSessionRecord | undefined = record('released', NOW) - server.setHookRootEvidenceReader( - (request) => readHookRootEvidence(request, io), - (request) => { - saved = replacement - return readPaneTmuxHost(io, request) - } - ) - runningPane(4050, CLIENT, ...TMUX) - server.setTerminalPaneLifecycle({ - ownsProcess: () => true, - isStopping: () => false, - isReversibleStop: () => true, - isPlaced: () => true, - readSavedRecord: () => saved, - retireSavedRecord: (_paneKey, before) => { - if (saved && saved.updatedAt <= before) { - saved = undefined - } - } - }) - vi.setSystemTime(NOW + 1_000) - await server.checkAgentPresenceSince(PANE, 0, { sleepCapture: true }) - expect(saved).toBe(replacement) + expect(await checkpointOf()).toMatchObject({ origin: 'live' }) + // Detached or not, the tmux server keeps the agent; the pane must not resume it after a restart. + expect(await checkpointOf(TMUX_HINT)).toBeNull() }) diff --git a/src/main/codex/hooks/definitions/codex-hook-script.ts b/src/main/codex/hooks/definitions/codex-hook-script.ts index 0ef1d101c4bb..0740f4081713 100644 --- a/src/main/codex/hooks/definitions/codex-hook-script.ts +++ b/src/main/codex/hooks/definitions/codex-hook-script.ts @@ -3,6 +3,7 @@ import { buildPosixClaudeBackgroundJobGuardLines } from '../../../agent-hooks/installation/scripts/claude-background-job-guard' import { buildPosixAgentHookPostCommand } from '../../../agent-hooks/installation/scripts/hook-post-command' +import { buildHookTmuxPaneCapture } from '../../../agent-hooks/installation/scripts/hook-process-capture' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, @@ -28,6 +29,7 @@ export function getManagedScript(target: 'local' | 'posix' = 'local'): string { return [ '#!/bin/sh', ...buildPosixHookPayloadCapture(), + ...buildHookTmuxPaneCapture(), ...buildPosixHookSpoolLines('codex'), ...buildPosixClaudeBackgroundJobGuardLines(), // Reload endpoint state so surviving PTYs keep reporting after restart. diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 12d9a5a71b61..d8ec6ddc0672 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -79,9 +79,7 @@ export type RuntimeConstructionDependencies = { /** `exitedSince`: also answer `exited` for an exit the hook store proved at or after it. */ checkHookAgentPresence?: ( paneKey: string, - exitedSince?: number, - /** A sleep capture also releases checkpoints a tmux client shows; other reads skip that probe. */ - options?: { sleepCapture?: true } + exitedSince?: number ) => Promise<'live' | 'unverifiable' | 'exited' | null> reconcileAgentStatusForEndedProcess?: ( paneKeys: Iterable, diff --git a/src/main/runtime/terminal/stop/hook-status-resume-records.ts b/src/main/runtime/terminal/stop/hook-status-resume-records.ts index b001f322e68c..423fcff4cf17 100644 --- a/src/main/runtime/terminal/stop/hook-status-resume-records.ts +++ b/src/main/runtime/terminal/stop/hook-status-resume-records.ts @@ -79,6 +79,7 @@ export function resumeStatusFromHookRow( lastAssistantMessage: row.lastAssistantMessage, interrupted: row.interrupted, ...(row.mainAgent ? { mainAgent: row.mainAgent } : {}), + ...(row.sharedHost ? { sharedHost: true as const } : {}), ...(row.worktreeId ? { worktreeId: row.worktreeId } : {}) } } diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index d4839ab2fad8..7452ec8c5d7e 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -123,8 +123,7 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu readSavedRecord: (paneKey) => this.readSavedResumeSource(worktreeId, paneKey), readIdentity: (paneKey, savedRecord) => this.readPaneAgentIdentity(paneKey, savedRecord), checkAgentPresence: (paneKey, since) => - this.checkHookAgentPresenceFn?.(paneKey, since, { sleepCapture: true }) ?? - Promise.resolve(null), + this.checkHookAgentPresenceFn?.(paneKey, since) ?? Promise.resolve(null), capturedAt: Date.now() }) }, diff --git a/src/renderer/src/hooks/ipc-events/agent-status/normalize-agent-status-event.ts b/src/renderer/src/hooks/ipc-events/agent-status/normalize-agent-status-event.ts index cab58ed5f127..c8345f0b812e 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/normalize-agent-status-event.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/normalize-agent-status-event.ts @@ -37,6 +37,7 @@ export function normalizeAgentStatusMetadata( data.launchConfig === undefined && !authorityRestartId && !data.paneOwner && + !data.sharedHost && data.orcaSessionId === undefined ) { return undefined @@ -47,6 +48,7 @@ export function normalizeAgentStatusMetadata( ...(data.orcaSessionId !== undefined ? { orcaSessionId: data.orcaSessionId } : {}), ...(data.launchToken ? { launchToken: data.launchToken } : {}), ...(data.launchConfig !== undefined ? { launchConfig: data.launchConfig } : {}), - ...(data.paneOwner ? { paneOwner: data.paneOwner } : {}) + ...(data.paneOwner ? { paneOwner: data.paneOwner } : {}), + ...(data.sharedHost ? { sharedHost: true as const } : {}) } } diff --git a/src/renderer/src/store/slices/agent-status/contracts/agent-status-contract.ts b/src/renderer/src/store/slices/agent-status/contracts/agent-status-contract.ts index a13d43fa7b5f..58fbd7379243 100644 --- a/src/renderer/src/store/slices/agent-status/contracts/agent-status-contract.ts +++ b/src/renderer/src/store/slices/agent-status/contracts/agent-status-contract.ts @@ -97,6 +97,7 @@ export type AgentStatusMetadata = { launchConfig?: SleepingAgentLaunchConfig | null launchToken?: string terminalResumeEligible?: false + sharedHost?: true paneOwner?: { agent: AgentType; session: string } } diff --git a/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts b/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts index 2c556c46650e..75f2e1311522 100644 --- a/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts +++ b/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts @@ -222,6 +222,7 @@ export function buildAgentStatusLiveEntry( ...(metadata?.terminalResumeEligible === false ? { terminalResumeEligible: false as const } : {}), + ...(metadata?.sharedHost ? { sharedHost: true as const } : {}), ...(promptInteractionKey ? { promptInteractionKey } : {}), ...(payload.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), ...(payload.paneSleep ? { paneSleep: payload.paneSleep } : {}), diff --git a/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts b/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts index c7844b3bec00..3aff68652062 100644 --- a/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts +++ b/src/shared/agent-hook-listener/presence/hook-process-root-evidence-reader.ts @@ -17,33 +17,23 @@ import { // Every pane's acquisition shares this executor's process table: a burst of first hooks queues // behind four subprocess or proc reads instead of spawning one ps per pane at once. -export function createHookProcessReadSlots(): PrioritySemaphore { - return new PrioritySemaphore(4) -} - -/** Each leaf read holds a slot only while it runs; an expired attempt's queued reads give up. */ -export function hookProcessReadGate( - slots: PrioritySemaphore, - signal?: AbortSignal, - priority = 0 -): ProcessReadGate { - return async (read) => { - const release = await slots.acquire(priority, signal) - try { - return await read() - } finally { - release() - } - } -} +const MAX_ACTIVE_HOOK_ROOT_READS = 4 /** Root evidence from this host's own processes, for panes whose PTY root `resolveRoot` names. */ export function createLocalHookRootEvidenceReader( resolveRoot: HookPaneProcessIo['resolveRoot'], - slots = createHookProcessReadSlots() + slots = new PrioritySemaphore(MAX_ACTIVE_HOOK_ROOT_READS) ): HookRootEvidenceReader { return (request) => { - const gate = hookProcessReadGate(slots, request.signal) + // Each leaf read holds a slot only while it runs; an expired attempt's queued reads give up. + const gate: ProcessReadGate = async (read) => { + const release = await slots.acquire(0, request.signal) + try { + return await read() + } finally { + release() + } + } const io: HookPaneProcessIo = { resolveRoot, probe: (process) => diff --git a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts index b5b712cc99dd..c8b3abcde0cc 100644 --- a/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts +++ b/src/shared/agent-hook-listener/presence/hook-process-root-evidence.ts @@ -78,12 +78,12 @@ export type HookPaneProcessIo = { } // Bounded ancestry walk; a pane's agent sits a few levels below its root. -export const MAX_ANCESTRY_DEPTH = 32 +const MAX_ANCESTRY_DEPTH = 32 const MAX_TERMINAL_ROWS = 256 type Role = 'agent' | 'launcher' | 'other' | 'unknown' -export function agentOf(command: string): string | undefined { +function agentOf(command: string): string | undefined { const recognized = recognizeAgentProcessFromCommandLine(command, { includeHeadlessOneShot: true }) if (recognized) { return recognized.agent @@ -133,7 +133,7 @@ type Walk = 'reached' | 'outside' | 'nested' | 'unknown' * when the sender runs under a tmux server and the pane does not show an agent. */ type OtherTerminal = 'foreign' | 'bridged' | 'tmux' -export function isTmuxServer(row: ProcessTableRow): boolean { +function isTmuxServer(row: ProcessTableRow): boolean { const token = firstToken(row.command) return /^tmux:?$/.test(token.slice(token.lastIndexOf('/') + 1)) } @@ -231,8 +231,8 @@ export function classifyPaneHookProcess(input: { return role === 'shell' ? 'foreign' : 'bridged' } -export async function collectRows( - io: Pick, +async function collectRows( + io: HookPaneProcessIo, rootPid: number, senderPid: number ): Promise { diff --git a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts b/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts deleted file mode 100644 index ed4052aed273..000000000000 --- a/src/shared/agent-hook-listener/presence/pane-tmux-host-proof.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { tokenizeCommandLine } from '../../agent-status/process/agent-command-line-entrypoint' -import type { AgentProcessIdentity } from '../../agent-status/process/agent-process-presence' -import { - unreadableArgvName, - type ProcessTableRow -} from '../../process-observation/tables/process-table-snapshot' -import { - MAX_ANCESTRY_DEPTH, - agentOf, - collectRows, - isTmuxServer, - type HookPaneProcessIo -} from './hook-process-root-evidence' - -/** Whether a tmux server, not the pane, keeps the pane's agent alive: a tmux client holds the - * pane's foreground and the agent's known process runs outside the pane. */ -export type PaneTmuxHostReader = (request: { - paneKey: string - worktreeId: string | undefined - process?: AgentProcessIdentity -}) => Promise - -// tmux aliases, plus the unambiguous prefixes tmux resolves to these commands (`att`, `new-s`). -const TMUX_ATTACHING_ALIASES = new Set(['a', 'at', 'new']) -const isAttachingTmuxCommand = (command: string): boolean => - TMUX_ATTACHING_ALIASES.has(command) || - (command.length >= 3 && 'attach-session'.startsWith(command)) || - (command.length >= 5 && 'new-session'.startsWith(command)) - -/** Only a client attached to a session shows that server's panes; `wait-for` or `-c` do not. */ -function isAttachingTmuxClient(row: ProcessTableRow): boolean { - if (!isTmuxServer(row)) { - return false - } - const args = tokenizeCommandLine(row.command).slice(1) - let index = 0 - while (args[index]?.startsWith('-')) { - // Flags may be grouped (`-vu`); the rest of a group after -L/-S/-f/-T is that flag's value. - // Only a client's harmless flags may precede the command; -c, -D, -V, -h and the rest attach nothing. - const flags = args[index].slice(1) - const valueAt = flags.search(/[LSfT]/) - if (!/^[2ClNquv]*$/.test(valueAt === -1 ? flags : flags.slice(0, valueAt))) { - return false - } - index += valueAt !== -1 && valueAt === flags.length - 1 ? 2 : 1 - } - const command = args[index] - if (command === undefined) { - return true - } - // `new-session -d` only creates a session; reading any d flag after it as detached errs safe. - return ( - isAttachingTmuxCommand(command) && - !(command.startsWith('n') && args.slice(index + 1).some((arg) => /^-[^-]*d/.test(arg))) - ) -} - -export async function readPaneTmuxHost( - io: Pick, - request: Parameters[0] -): Promise { - const root = await io.resolveRoot(request.paneKey, request.worktreeId) - if (!root || root === 'legacy') { - return false - } - const rows = await collectRows(io, root.pid, request.process?.pid ?? root.pid) - if (!rows) { - return false - } - const rootRow = rows.find((row) => row.pid === root.pid) - if (!rootRow?.tpgid || rootRow.tpgid <= 0) { - return false - } - const client = rows.find( - (row) => row.tty === rootRow.tty && row.pgid === rootRow.tpgid && isAttachingTmuxClient(row) - ) - if (!client) { - return false - } - // Without a process, a pane whose own agent sits beside the client (a stopped job) proves nothing. - if (!request.process) { - const clientChain = new Set() - for (let row: ProcessTableRow | undefined = client; row && !clientChain.has(row.pid);) { - clientChain.add(row.pid) - const parent: number = row.ppid - row = rows.find((candidate) => candidate.pid === parent) - } - return rows.every( - (row) => - row.tty !== rootRow.tty || - clientChain.has(row.pid) || - row.pgid === rootRow.tpgid || - (unreadableArgvName(row.command) === null && agentOf(row.command) === undefined) - ) - } - // Only a complete ancestry outside the pane proves it; a missing row proves nothing. - let agent = rows.find((row) => row.pid === request.process?.pid) - for (let depth = 0; agent && depth < MAX_ANCESTRY_DEPTH; depth++) { - if (agent.pid === root.pid) { - return false - } - if (agent.ppid <= 1) { - return true - } - const parent = agent.ppid - agent = rows.find((row) => row.pid === parent) - } - return false -} diff --git a/src/shared/agent-session/lifecycle/resume/agent-resume-record-from-status.ts b/src/shared/agent-session/lifecycle/resume/agent-resume-record-from-status.ts index 2f71b74b1014..c79917991892 100644 --- a/src/shared/agent-session/lifecycle/resume/agent-resume-record-from-status.ts +++ b/src/shared/agent-session/lifecycle/resume/agent-resume-record-from-status.ts @@ -29,6 +29,7 @@ export type ResumeRecordStatus = Pick< | 'terminalTitle' | 'lastAssistantMessage' | 'terminalResumeEligible' + | 'sharedHost' | 'interrupted' | 'mainAgent' | 'worktreeId' @@ -57,6 +58,7 @@ export function resumeRecordFromStatus(args: { const agent = args.entry.agentType if ( args.entry.terminalResumeEligible === false || + args.entry.sharedHost || !isResumableTuiAgent(agent) || !args.entry.providerSession ) { diff --git a/src/shared/agent-status/contracts/agent-status-ipc-payload.ts b/src/shared/agent-status/contracts/agent-status-ipc-payload.ts index 38ff4de41a25..52a64ac631f0 100644 --- a/src/shared/agent-status/contracts/agent-status-ipc-payload.ts +++ b/src/shared/agent-status/contracts/agent-status-ipc-payload.ts @@ -87,6 +87,8 @@ export type AgentStatusIpcPayload = ParsedAgentStatusPayload & { turnEndDisposition?: TurnEndDisposition orchestration?: AgentStatusOrchestrationContext providerSession?: AgentProviderSessionMetadata + /** A tmux or shared server, not this pane, runs this conversation: never the pane's resume. */ + sharedHost?: true /** Resume identity update only; the status-shaped fields are transport placeholders. */ providerSessionOnly?: boolean /** Live-only Command Code turn boundary key; not persisted to last-status.json. */ diff --git a/src/shared/agent-status/contracts/agent-status-types.ts b/src/shared/agent-status/contracts/agent-status-types.ts index 86eb32961ccf..f28e87775ee1 100644 --- a/src/shared/agent-status/contracts/agent-status-types.ts +++ b/src/shared/agent-status/contracts/agent-status-types.ts @@ -133,6 +133,8 @@ export type AgentStatusEntry = { launchAttested?: boolean /** False when the status belongs to a non-terminal owner that restores itself. */ terminalResumeEligible?: false + /** A tmux or shared server, not this pane, runs this conversation: never the pane's resume. */ + sharedHost?: true /** Live-only Command Code turn boundary key; not persisted to last-status.json. */ promptInteractionKey?: string /** Live OSC 7501 facet never decides state; read through resolveProgramStatusPresentation beside the state owner. */ From c1dfd242f6392570e3c9f817b41b1b85729757a3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:45:30 -0800 Subject: [PATCH 071/125] fix(sleep): an SSH pane's returning shell retires its record, as on main Main's shell-alone proof covers local panes only; for a remote pane the window clears the record when its shell comes back, except for the sleep's own kill. --- .../pane-agent-shell-lifecycle.test.ts | 60 +++++++++++++++++++ .../pane-agent-shell-lifecycle.ts | 5 ++ 2 files changed, 65 insertions(+) create mode 100644 src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.test.ts diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.test.ts new file mode 100644 index 000000000000..9330643e5633 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.test.ts @@ -0,0 +1,60 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import type { SleepingAgentSessionRecord } from '../../../../../../shared/agent-session/lifecycle/agent-session-resume' +import { toAppSshPtyId } from '../../../../../../shared/remote-runtime/ssh/ssh-pty-id' +import type { ConnectPanePtySession } from '../connect-pane-pty-session' + +const state = { + suppressedPtyExitIds: {} as Record, + agentStatusByPaneKey: new Map(), + clearAgentLaunchConfig: vi.fn() +} +vi.mock('@/store/index', () => ({ useAppStore: { getState: () => state } })) + +const { settlePaneShellForeground } = await import('./pane-agent-shell-lifecycle') + +const record: SleepingAgentSessionRecord = { + paneKey: 'tab-1:leaf-1', + worktreeId: 'wt-1', + agent: 'codex', + providerSession: { key: 'session_id', id: 'woken-codex' }, + prompt: '', + state: 'done', + capturedAt: 1, + updatedAt: 1, + origin: 'worktree-sleep' +} + +function paneOn(ptyId: string, wake?: { record: SleepingAgentSessionRecord; ptyId: string }) { + return { + transport: { getPtyId: () => ptyId }, + getSleepingRecordForPane: () => ({ paneKey: record.paneKey, record }), + hibernatedWakeTarget: wake, + cacheKey: record.paneKey, + pane: { leafId: 'leaf-1' }, + deps: { onAgentExitedRef: { current: vi.fn() } }, + clearSleepingRecordProviderDuplicates: vi.fn(), + clearStaleAgentTabTitleOnConfirmedShell: vi.fn(), + writeInputModeGround: vi.fn(), + reconcileEndedProcessIfPaneQuiet: vi.fn(), + settleDeferredCommandFinishedStatusDrop: vi.fn() + } +} + +beforeEach(() => { + state.suppressedPtyExitIds = {} +}) + +it('retires a woken SSH agent when its shell comes back, as no host proof reaches main', () => { + const ssh = toAppSshPtyId('conn-1', 'pty-7') + const quit = paneOn(ssh) + settlePaneShellForeground(quit as unknown as ConnectPanePtySession, 'command-finished') + expect(quit.clearSleepingRecordProviderDuplicates).toHaveBeenCalledOnce() + // The sleep's own kill keeps the wake record it is about to resume. + const sleeping = paneOn(ssh, { record, ptyId: ssh }) + settlePaneShellForeground(sleeping as unknown as ConnectPanePtySession, 'command-finished') + expect(sleeping.clearSleepingRecordProviderDuplicates).not.toHaveBeenCalled() + // A local pane waits for main's shell-alone proof instead. + const local = paneOn('pty-local') + settlePaneShellForeground(local as unknown as ConnectPanePtySession, 'command-finished') + expect(local.clearSleepingRecordProviderDuplicates).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts index a1ae2139e21e..f35c41d67edb 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.ts @@ -15,6 +15,11 @@ export function settlePaneShellForeground( const isHibernationWakeRecord = (ptyId && state.suppressedPtyExitIds[ptyId]) || (wake && wake.record === sleepingRecord?.record && (ptyId === null || wake.ptyId === ptyId)) + // Main proves a local agent's exit (shell alone, no stopped job) before retiring its record; a + // remote host has no such proof yet, so its returning shell retires the record as before. + if (sleepingRecord && !isHibernationWakeRecord && ptyId && isRemoteExecutionHostPtyId(ptyId)) { + session.clearSleepingRecordProviderDuplicates(state, sleepingRecord) + } session.clearStaleAgentTabTitleOnConfirmedShell() session.writeInputModeGround(CONFIRMED_SHELL_MODE_RESET) if (!isHibernationWakeRecord) { From 8bba1f8572f3d690b4a7c094db6d6f559955b63d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:49:49 -0800 Subject: [PATCH 072/125] fix(sleep): prove an agent's exit from the PTY's root shell in a fresh process table A daemon answers shell ownership from prompt marks and dropped the no-live-descendants request, so a job left behind the prompt could pass as an exit. POSIX exit proof now reads the root shell's tree directly for local and daemon PTYs alike; the option no longer crosses the provider contract. --- .../routing/degraded-daemon-pty-provider.ts | 11 ++++---- .../terminal-pane-status-lifecycle.test.ts | 28 +++++++++++++------ .../pane/terminal-pane-status-lifecycle.ts | 22 +++++++++------ .../local-pty-foreground-inspection.ts | 7 ++--- .../providers/local-pty/local-pty-provider.ts | 4 +-- src/main/providers/pty/provider-contract.ts | 10 +++---- .../lifecycle/run-terminal-shell-alone.ts | 10 +++++-- 7 files changed, 55 insertions(+), 37 deletions(-) diff --git a/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts b/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts index a04de42254fc..9424929fef6e 100644 --- a/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts +++ b/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts @@ -178,6 +178,10 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { await this.providerFor(id).reportFocusLost?.(id) } + async requestRepaint(id: string): Promise { + await this.providerFor(id).requestRepaint?.(id) + } + async closeStartupQueryAuthority(id: string): Promise { return (await this.providerFor(id).closeStartupQueryAuthority?.(id)) ?? 0 } @@ -207,11 +211,8 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { async confirmForegroundProcess(id: string): Promise { return this.providerFor(id).confirmForegroundProcess?.(id) ?? null } - async confirmShellForeground( - id: string, - options?: { noLiveDescendants?: boolean } - ): Promise { - return (await this.providerFor(id).confirmShellForeground?.(id, options)) ?? false + async confirmShellForeground(id: string): Promise { + return (await this.providerFor(id).confirmShellForeground?.(id)) ?? false } async serialize(ids: string[]): Promise { diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index f018cf4fb905..7d06f5e5f417 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -3,14 +3,18 @@ import type { AgentHookServer } from '../../../agent-hooks/server/agent-hook-ser import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { bindTerminalPaneStatusLifecycle } from './terminal-pane-status-lifecycle' -const { setTerminalPaneLifecycle, getProviderForPty } = vi.hoisted(() => ({ +const { setTerminalPaneLifecycle, getProviderForPty, confirmRootShellAlone } = vi.hoisted(() => ({ setTerminalPaneLifecycle: vi.fn(), - getProviderForPty: vi.fn() + getProviderForPty: vi.fn(), + confirmRootShellAlone: vi.fn() })) vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { setTerminalPaneLifecycle, pruneUnplacedSleepingPanes: () => {} } })) vi.mock('../provider/registry', () => ({ getProviderForPty })) +vi.mock('../../../runtime/terminal/lifecycle/run-terminal-shell-alone', () => ({ + confirmRootShellAloneFromProcessTable: confirmRootShellAlone +})) const platform = process.platform afterEach(() => Object.defineProperty(process, 'platform', { value: platform })) @@ -93,13 +97,21 @@ it.each([ Object.defineProperty(process, 'platform', { value: os }) const launch = { agentArgs: '', agentEnv: {} } let currentLaunch = evidence === 'held' ? launch : evidence === 'gone' ? null : undefined + const proveShellAlone = async () => { + if (replaced) { + currentLaunch = { agentArgs: '--resume next', agentEnv: {} } + } + return shellAlone + } + // POSIX reads the PTY's root shell from the process table, whatever the provider says. + confirmRootShellAlone.mockImplementation(async (rootPid: number, options: unknown) => + rootPid === 4242 && JSON.stringify(options) === '{"noLiveDescendants":true}' + ? proveShellAlone() + : false + ) getProviderForPty.mockReturnValue({ - confirmShellForeground: async () => { - if (replaced) { - currentLaunch = { agentArgs: '--resume next', agentEnv: {} } - } - return shellAlone - }, + listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }], + confirmShellForeground: os === 'win32' ? proveShellAlone : async () => true, // Windows answers from its job census; a foreground name alone is not that census. inspectProcess: async () => ({ foregroundProcess: foreground, diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 454b71d840fd..535373376d9c 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -11,6 +11,7 @@ import { getProviderForPty } from '../provider/registry' import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import { isRemoteExecutionHostPtyId } from '../../../../shared/execution-host/remote-execution-host-pty-id' +import { confirmRootShellAloneFromProcessTable } from '../../../runtime/terminal/lifecycle/run-terminal-shell-alone' export function bindTerminalPaneStatusLifecycle( runtime: OrcaRuntimeService | undefined, @@ -110,17 +111,22 @@ export function bindTerminalPaneStatusLifecycle( agentHookServer.pruneUnplacedSleepingPanes() } -/** The shell alone holds the PTY, with no stopped job behind it. The daemon's proof needs prompt - * marks, which cmd and Git Bash often lack; Windows shells stop no jobs, so the host's job census - * finding no child beside a shell foreground suffices there. Elsewhere only the host's shell-alone - * proof counts; never fall back to a foreground name, which a live unrecognized agent shares. */ +/** The shell alone holds the PTY, with no job behind it, stopped or running. A daemon answers + * shell ownership from prompt marks, so POSIX reads the PTY's root shell from a fresh process + * table instead, local or daemon alike. Windows shells stop no jobs, so the host's job census + * finding no child beside a shell foreground suffices there. Never fall back to a foreground + * name, which a live unrecognized agent shares. */ async function confirmShellAlone(ptyId: string, incarnationId?: string): Promise { const provider = getProviderForPty(ptyId) - if ((await provider.confirmShellForeground?.(ptyId, { noLiveDescendants: true })) === true) { - return true - } if (process.platform !== 'win32') { - return false + const processes = await provider.listProcesses({ ptyIds: [ptyId] }).catch(() => []) + const rootPid = processes.find((entry) => entry.id === ptyId)?.rootProcessId + return rootPid + ? confirmRootShellAloneFromProcessTable(rootPid, { noLiveDescendants: true }) + : false + } + if ((await provider.confirmShellForeground?.(ptyId)) === true) { + return true } const inspection = await inspectPtyProviderProcess(provider, ptyId, { scanChildProcesses: true, diff --git a/src/main/providers/local-pty/local-pty-foreground-inspection.ts b/src/main/providers/local-pty/local-pty-foreground-inspection.ts index 6259ff2ab13d..1a4a7473b0f6 100644 --- a/src/main/providers/local-pty/local-pty-foreground-inspection.ts +++ b/src/main/providers/local-pty/local-pty-foreground-inspection.ts @@ -293,10 +293,7 @@ export async function confirmLocalPtyForegroundProcess( } } -export async function confirmLocalPtyShellForeground( - id: string, - options?: { noLiveDescendants?: boolean } -): Promise { +export async function confirmLocalPtyShellForeground(id: string): Promise { const proc = ptyProcesses.get(id) if (!proc) { return false @@ -306,7 +303,7 @@ export async function confirmLocalPtyShellForeground( ptyShellPath.get(id), process.platform === 'win32' ? { readWindowsPtyJobProcessIds: () => readWindowsPtyJobProcessIds(proc) } - : { noLiveDescendants: options?.noLiveDescendants === true } + : {} ) return ptyProcesses.get(id) === proc && confirmed } diff --git a/src/main/providers/local-pty/local-pty-provider.ts b/src/main/providers/local-pty/local-pty-provider.ts index 66c539e7aafa..2631c5f058a1 100644 --- a/src/main/providers/local-pty/local-pty-provider.ts +++ b/src/main/providers/local-pty/local-pty-provider.ts @@ -214,8 +214,8 @@ export class LocalPtyProvider implements IPtyProvider { return confirmLocalPtyForegroundProcess(id) } - confirmShellForeground(id: string, options?: { noLiveDescendants?: boolean }): Promise { - return confirmLocalPtyShellForeground(id, options) + confirmShellForeground(id: string): Promise { + return confirmLocalPtyShellForeground(id) } async serialize(_ids: string[]): Promise { diff --git a/src/main/providers/pty/provider-contract.ts b/src/main/providers/pty/provider-contract.ts index 1c24f1a5427b..695f68053f5c 100644 --- a/src/main/providers/pty/provider-contract.ts +++ b/src/main/providers/pty/provider-contract.ts @@ -188,6 +188,8 @@ export type IPtyProvider = { resetInputModes(id: string): Promise /** Sends ESC [ O to a ?1004 program once no viewer is left to blur; hosts that own no viewers omit it. */ reportFocusLost?(id: string): Promise + /** Redraws the program without input; hosts that cannot leave it alone. */ + requestRepaint?(id: string): Promise /** Ends the startup Kitty-query window; OSC 10/11 authority stays with the owner for life. */ closeStartupQueryAuthority?: (id: string) => Promise | number /** Host-wide viewer colours the PTY owner answers OSC 10/11 from. */ @@ -198,12 +200,8 @@ export type IPtyProvider = { getForegroundProcess(id: string): Promise /** Strong process evidence captured after the caller's command boundary. */ confirmForegroundProcess?: (id: string) => Promise - /** Fresh execution-host proof that the spawned shell owns the PTY foreground. `noLiveDescendants` - * (exit proof) also refuses a running background job where the host can see one. */ - confirmShellForeground?: ( - id: string, - options?: { noLiveDescendants?: boolean } - ) => Promise + /** Fresh execution-host proof that the spawned shell owns the PTY foreground. */ + confirmShellForeground?: (id: string) => Promise /** Persist main's live launch where the PTY outlives main; only the daemon keeps one. */ setLaunchNote?: (id: string, change: DaemonLaunchNoteChange) => void serialize(ids: string[]): Promise diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts index 782ff60f493d..6d71e5a12f27 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts @@ -5,15 +5,19 @@ import { getProcessTableIndex } from '../../../../shared/process-observation/tab import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import type { TerminalProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' -/** POSIX: the PTY's root shell owns the terminal's foreground group and nothing under it is stopped. */ -export async function confirmRootShellAloneFromProcessTable(rootPid: number): Promise { +/** POSIX: the PTY's root shell owns the terminal's foreground group and nothing under it is stopped + * (nor, for exit proof, still running). */ +export async function confirmRootShellAloneFromProcessTable( + rootPid: number, + options?: { noLiveDescendants?: boolean } +): Promise { try { const root = getProcessTableIndex(await getFreshProcessTableSnapshot()).byPid.get(rootPid) const executable = root?.command.trim().split(/\s+/, 1)[0] ?? '' if (!isShellProcess(executable)) { return false } - return await confirmShellForegroundProcess(rootPid, executable) + return await confirmShellForegroundProcess(rootPid, executable, options) } catch { return false } From 2ce5f30334be0cdf92b2e4e721358f1173464cb1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:57:17 -0800 Subject: [PATCH 073/125] fix(sleep): a command mark ends a process-less agent only on the host's shell-alone word A shell nested inside a live Codex inherits Orca's prompt marks, so its 133;D alone could retire the conversation. The exit is now recorded only once the host confirms the pane's shell holds its PTY alone. --- .../runtime/agent-hook-runtime-deps.ts | 4 +- src/main/agent-hooks/server/server-state.ts | 2 + .../agent-hooks/server/server-tab-cleanup.ts | 21 +++++++- .../server-pane-saved-sleep.test.ts | 7 +-- .../pane/terminal-pane-status-lifecycle.ts | 49 +++++++++++++------ .../worktree-sleep-resume-recording.test.ts | 10 +++- .../worktree-ps-saved-sleep.test.ts | 5 +- 7 files changed, 75 insertions(+), 23 deletions(-) diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index 6b01868ce1a4..3a6ab0475fef 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -83,10 +83,10 @@ export function agentHookRuntimeDeps( readChildWorkHandles: (subject) => server.getStructuredChildWorkHandles(subject) }, readHookCliWriterObservation: (row) => server.readCliWriterObservation(row), - checkHookAgentPresence: (paneKey, exitedSince, options) => + checkHookAgentPresence: (paneKey, exitedSince) => exitedSince === undefined ? server.checkAgentPresence(paneKey) - : server.checkAgentPresenceSince(paneKey, exitedSince, options), + : server.checkAgentPresenceSince(paneKey, exitedSince), reconcileAgentStatusForEndedProcess: (paneKeys, sleep) => { const keys = [...paneKeys] if (sleep) { diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 0e291d21a4f4..cb8f44820686 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -54,6 +54,8 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract retireSavedRecord?(paneKey: string, exitedAt: number): void readSavedRecord?(paneKey: string): SleepingAgentSessionRecord | undefined confirmProcessExit?(paneKey: string, agent: string): Promise + /** The host's word that the pane's shell holds its PTY alone, whatever launch it ran. */ + confirmShellAlone?(paneKey: string): Promise ownsProcess(paneKey: string, ptyId: string, incarnationId?: string): boolean isStopping(paneKey: string): boolean isReversibleStop(ptyId: string, incarnationId?: string): boolean diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index f96532a0a864..039b41d3e50c 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -23,12 +23,19 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { ): void { const identity = this.paneAgentIdentity(paneKey) const shared = identity?.processTopology === 'shared' + // A command mark can come from a shell nested in a live agent; one with no process to probe + // ends only on the host's word that the pane's shell is alone. + const awaitsHost = options?.confirmedExit === true && !this.hasVerifiableAgentProcess(paneKey) + const confirmedExit = options?.confirmedExit === true && !awaitsHost const { paneKeys, authorityChanged } = this.revokeProcessAuthority(paneKey) const { untouched } = this.reconcileEndedProcess( paneKeys, - { ...options, preserveResumeIdentity: !options?.confirmedExit && !shared }, + { confirmedExit, preserveResumeIdentity: !confirmedExit && !shared }, (key) => this.clearRevokedPaneState(key) ) + if (awaitsHost && identity && !shared) { + void this.confirmCommandFinishedExit(paneKey) + } for (const key of untouched) { this.clearTmuxInnerSubjects(key) this.clearPaneProcessState(key) @@ -39,6 +46,18 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } } + private async confirmCommandFinishedExit(paneKey: string): Promise { + const resolved = this.resolvePaneKeyAlias(paneKey) + const row = this.state.lastStatusByPaneKey.get(resolved) + const alone = await this.terminalPaneLifecycle?.confirmShellAlone?.(resolved) + if (alone === true && this.state.lastStatusByPaneKey.get(resolved) === row) { + this.reconcileEndedProcessForPaneKeys([resolved], { + preserveResumeIdentity: true, + confirmedExit: true + }) + } + } + hasVerifiableAgentProcess(paneKey: string): boolean { const presence = this.state.lastStatusByPaneKey.get( this.resolvePaneKeyAlias(paneKey) diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts index 1e421832d9f6..5a1b1affa736 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-saved-sleep.test.ts @@ -196,7 +196,7 @@ it.each(['claude', 'codex'] as const)( } ) -it('does not recover a saved Interrupted turn after its conversation exited', () => { +it('does not recover a saved Interrupted turn after its conversation exited', async () => { const saved: SleepingAgentSessionRecord = { paneKey: PANE, worktreeId: 'wt-1', @@ -215,11 +215,12 @@ it('does not recover a saved Interrupted turn after its conversation exited', () ownsProcess: () => true, isStopping: () => false, isReversibleStop: () => false, - isPlaced: () => true + isPlaced: () => true, + confirmShellAlone: async () => true }) try { server.retireProcessAuthority(PANE, { confirmedExit: true }) - expect(server.paneAgentIdentity(PANE)?.ended).toBe(true) + await vi.waitFor(() => expect(server.paneAgentIdentity(PANE)?.ended).toBe(true)) server.recordLaunchResumeIdentity({ paneKey: PANE, worktreeId: 'wt-1', diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 535373376d9c..a4301fead726 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -20,28 +20,22 @@ export function bindTerminalPaneStatusLifecycle( agentHookServer.setTerminalPaneLifecycle({ retireSavedRecord: (paneKey, exitedAt) => runtime?.retireExitedPaneResume(paneKey, exitedAt), confirmProcessExit: async (paneKey, agent) => { - if (!runtime) { - return false - } try { - const pane = runtime.resolveTerminalPane(paneKey) - const launch = runtime.getLaunchStatementForPaneKey(paneKey, agent) + const launch = runtime?.getLaunchStatementForPaneKey(paneKey, agent) // A finished command already retired a gone launch; an unknown one (reattach) needs the proof. - if (!pane.ptyId || isRemoteExecutionHostPtyId(pane.ptyId) || launch === null) { - return false - } - const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined) - const current = runtime.resolveTerminalPane(paneKey) return ( - shellAlone === true && - current.ptyId === pane.ptyId && - current.incarnationId === pane.incarnationId && - runtime.getLaunchStatementForPaneKey(paneKey, agent) === launch + launch !== null && + (await paneShellAlone( + runtime, + paneKey, + () => runtime?.getLaunchStatementForPaneKey(paneKey, agent) === launch + )) ) } catch { return false } }, + confirmShellAlone: (paneKey) => paneShellAlone(runtime, paneKey), readSavedRecord: (paneKey) => { try { const worktreeId = runtime?.getTerminalWorktreeIdForPaneKey(paneKey) @@ -111,6 +105,33 @@ export function bindTerminalPaneStatusLifecycle( agentHookServer.pruneUnplacedSleepingPanes() } +/** A local pane's shell alone holds its PTY, and the pane still runs that PTY afterwards. */ +async function paneShellAlone( + runtime: OrcaRuntimeService | undefined, + paneKey: string, + stillCurrent: () => boolean = () => true +): Promise { + if (!runtime) { + return false + } + try { + const pane = runtime.resolveTerminalPane(paneKey) + if (!pane.ptyId || isRemoteExecutionHostPtyId(pane.ptyId)) { + return false + } + const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined) + const current = runtime.resolveTerminalPane(paneKey) + return ( + shellAlone && + current.ptyId === pane.ptyId && + current.incarnationId === pane.incarnationId && + stillCurrent() + ) + } catch { + return false + } +} + /** The shell alone holds the PTY, with no job behind it, stopped or running. A daemon answers * shell ownership from prompt marks, so POSIX reads the PTY's root shell from a fresh process * table instead, local or daemon alike. Windows shells stop no jobs, so the host's job census diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 35116cb6779b..383143766428 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -235,6 +235,7 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini it.each([ ['quit', ['0'], false], ['quit without command marks', ['unmarked'], false], + ['a shell nested in the live Codex finishing a command', ['nested'], true], ['suspended', ['148'], true], ['macOS suspended', ['146'], true], ['suspended, then another command', ['148', '0'], true], @@ -244,6 +245,8 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(1_000) const tick = () => vi.setSystemTime(Date.now() + 1_000) + // The host's word on the pane's shell: alone unless a nested shell marked a command. + let shellAlone = true const fixture = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ sleepingAgentSessionsByPaneKey: { [PANE_KEY]: SLEPT } @@ -262,6 +265,7 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini isPlaced: () => true, readSavedRecord: (paneKey) => fixture.getSession().sleepingAgentSessionsByPaneKey?.[paneKey], confirmProcessExit: async () => true, + confirmShellAlone: async () => shellAlone, retireSavedRecord: (paneKey, at) => runtime.retireExitedPaneResume(paneKey, at) }) const clears: AgentStatusClearIpcPayload[] = [] @@ -341,7 +345,11 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini 'pty-3' ) } else { - runtime.onPtyData('pty-3', `\x1b]133;C\x07\x1b]133;D;${status}\x07`, Date.now()) + shellAlone = status !== 'nested' + const code = status === 'nested' ? '0' : status + runtime.onPtyData('pty-3', `\x1b]133;C\x07\x1b]133;D;${code}\x07`, Date.now()) + // Let the host's shell-alone answer land. + await new Promise((resolve) => setImmediate(resolve)) } } expect(clears.filter((clear) => 'paneKey' in clear && clear.refusedResume)).toEqual( diff --git a/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts b/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts index 821130a091d8..c6b6bb4948e4 100644 --- a/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts +++ b/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts @@ -60,7 +60,8 @@ it.each(['claude', 'codex'] as const)( ownsProcess: () => true, isStopping: () => false, isReversibleStop: () => true, - isPlaced: () => true + isPlaced: () => true, + confirmShellAlone: async () => true }) server.ingestRemote( { @@ -130,6 +131,6 @@ it.each(['claude', 'codex'] as const)( expect(row?.agents[0]?.agentWait).toBeUndefined() server.retireProcessAuthority(PANE, { confirmedExit: true }) - expect((await listed())?.agents).toEqual([]) + await vi.waitFor(async () => expect((await listed())?.agents).toEqual([])) } ) From 53b39c1b50507f030203fbbaa8ab942ed147ccb2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:03:58 -0800 Subject: [PATCH 074/125] test: name the session cast in the SSH shell-return test --- .../pane-agent-shell-lifecycle.test.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.test.ts index 9330643e5633..74299c5cd61c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-shell-lifecycle.test.ts @@ -3,8 +3,9 @@ import type { SleepingAgentSessionRecord } from '../../../../../../shared/agent- import { toAppSshPtyId } from '../../../../../../shared/remote-runtime/ssh/ssh-pty-id' import type { ConnectPanePtySession } from '../connect-pane-pty-session' +const suppressedPtyExitIds: Record = {} const state = { - suppressedPtyExitIds: {} as Record, + suppressedPtyExitIds, agentStatusByPaneKey: new Map(), clearAgentLaunchConfig: vi.fn() } @@ -25,7 +26,7 @@ const record: SleepingAgentSessionRecord = { } function paneOn(ptyId: string, wake?: { record: SleepingAgentSessionRecord; ptyId: string }) { - return { + const pane = { transport: { getPtyId: () => ptyId }, getSleepingRecordForPane: () => ({ paneKey: record.paneKey, record }), hibernatedWakeTarget: wake, @@ -38,6 +39,8 @@ function paneOn(ptyId: string, wake?: { record: SleepingAgentSessionRecord; ptyI reconcileEndedProcessIfPaneQuiet: vi.fn(), settleDeferredCommandFinishedStatusDrop: vi.fn() } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: settlePaneShellForeground reads only these session members. + return { pane, session: pane as unknown as ConnectPanePtySession } } beforeEach(() => { @@ -47,14 +50,14 @@ beforeEach(() => { it('retires a woken SSH agent when its shell comes back, as no host proof reaches main', () => { const ssh = toAppSshPtyId('conn-1', 'pty-7') const quit = paneOn(ssh) - settlePaneShellForeground(quit as unknown as ConnectPanePtySession, 'command-finished') - expect(quit.clearSleepingRecordProviderDuplicates).toHaveBeenCalledOnce() + settlePaneShellForeground(quit.session, 'command-finished') + expect(quit.pane.clearSleepingRecordProviderDuplicates).toHaveBeenCalledOnce() // The sleep's own kill keeps the wake record it is about to resume. const sleeping = paneOn(ssh, { record, ptyId: ssh }) - settlePaneShellForeground(sleeping as unknown as ConnectPanePtySession, 'command-finished') - expect(sleeping.clearSleepingRecordProviderDuplicates).not.toHaveBeenCalled() + settlePaneShellForeground(sleeping.session, 'command-finished') + expect(sleeping.pane.clearSleepingRecordProviderDuplicates).not.toHaveBeenCalled() // A local pane waits for main's shell-alone proof instead. const local = paneOn('pty-local') - settlePaneShellForeground(local as unknown as ConnectPanePtySession, 'command-finished') - expect(local.clearSleepingRecordProviderDuplicates).not.toHaveBeenCalled() + settlePaneShellForeground(local.session, 'command-finished') + expect(local.pane.clearSleepingRecordProviderDuplicates).not.toHaveBeenCalled() }) From ab9caa754b6a05ee3a41976bddb41e69a162412e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:28:10 -0800 Subject: [PATCH 075/125] fix(sleep): persist shared topology, prove exits from login-rooted PTYs, and let a later mark end an agent a nested mark kept - Persist sharedHost with the hook row and restore it on hydration, so a tmux-hosted conversation still gets no checkpoint after a restart. - Stamp the tmux pane Orca itself runs in as ORCA_INHERITED_TMUX so hook scripts don't report it as a tmux started in the pane. - Find the PTY's shell beneath a macOS /usr/bin/login root and read one process table per proof; drop the background-job gate. - When a nested shell's command mark leaves the agent alive, the next mark re-checks the shell alone instead of finding no launch to retire. --- .../scripts/hook-process-capture.ts | 3 +- .../agent-hooks/server/server-hydration.ts | 8 +++ .../agent-hooks/server/server-persistence.ts | 4 +- .../agent-hooks/server/server-tab-cleanup.ts | 35 +++++++++--- src/main/agent-hooks/server/server-types.ts | 2 + .../tmux/server-tmux-legacy-sleep.test.ts | 43 ++++++++++----- .../antigravity/posix-hook-invocation.test.ts | 54 +++++++++++-------- .../pty-subprocess/spawn-environment.ts | 2 + .../terminal-pane-status-lifecycle.test.ts | 6 +-- .../pane/terminal-pane-status-lifecycle.ts | 6 +-- .../agent-process-shell-alone.test.ts | 36 ------------- .../providers/foreground/agent-process.ts | 17 +++--- .../local-pty/local-pty-spawn-environment.ts | 2 + .../pty/shell-startup/inherited-tmux-env.ts | 15 ++++++ .../runtime-construction-dependencies.ts | 3 +- .../run-terminal-shell-alone.test.ts | 39 ++++++++++++++ .../lifecycle/run-terminal-shell-alone.ts | 35 +++++++----- .../terminal-orchestration-authority.ts | 7 ++- .../worktree-sleep-resume-recording.test.ts | 1 + 19 files changed, 203 insertions(+), 115 deletions(-) delete mode 100644 src/main/providers/foreground/agent-process-shell-alone.test.ts create mode 100644 src/main/pty/shell-startup/inherited-tmux-env.ts create mode 100644 src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts diff --git a/src/main/agent-hooks/installation/scripts/hook-process-capture.ts b/src/main/agent-hooks/installation/scripts/hook-process-capture.ts index e49f37b3aca2..718fb3ff9247 100644 --- a/src/main/agent-hooks/installation/scripts/hook-process-capture.ts +++ b/src/main/agent-hooks/installation/scripts/hook-process-capture.ts @@ -53,6 +53,7 @@ export function buildHookProcessCapture(): string[] { export function buildHookTmuxPaneCapture(): string[] { return [ 'orca_tmux_pane=', - 'case "${TMUX_PANE:-}" in %[0-9]*) [ -z "${TMUX:-}" ] || orca_tmux_pane="$TMUX_PANE ${TMUX%,*,*}" ;; esac' + 'case "${TMUX_PANE:-}" in %[0-9]*) [ -z "${TMUX:-}" ] || orca_tmux_pane="$TMUX_PANE ${TMUX%,*,*}" ;; esac', + '[ "$orca_tmux_pane" != "${ORCA_INHERITED_TMUX:-}" ] || orca_tmux_pane=' ] } diff --git a/src/main/agent-hooks/server/server-hydration.ts b/src/main/agent-hooks/server/server-hydration.ts index 180d82d0b809..7aa46d1a6831 100644 --- a/src/main/agent-hooks/server/server-hydration.ts +++ b/src/main/agent-hooks/server/server-hydration.ts @@ -1,3 +1,4 @@ +import { retainTmuxWriterTopology } from './cli-writer-observation' import { admitLegacyAgentStatus, clearLegacyAgentStatuses @@ -98,6 +99,13 @@ export abstract class AgentHookServerHydration extends AgentHookServerTabCleanup : { ...(rawEntry as Record), paneKey: resolvedPaneKey } const entry = sanitizeHydratedEntry(resolvedPaneKey, rawResolvedEntry) if (entry && (entry.paneSleep || entry.receivedAt >= ttlCutoff)) { + // The binding's topology is runtime metadata; a shared host still runs this conversation. + if ( + entry.providerSession && + (rawResolvedEntry as { sharedHost?: unknown } | null)?.sharedHost === true + ) { + retainTmuxWriterTopology(entry.providerSession) + } const launchTokenHash = readPersistedLaunchTokenHash(rawResolvedEntry) if (launchTokenHash) { this.hydratedLaunchTokenHashByPaneKey.set(resolvedPaneKey, launchTokenHash) diff --git a/src/main/agent-hooks/server/server-persistence.ts b/src/main/agent-hooks/server/server-persistence.ts index 1ed4dfdb3c09..f41354e7c795 100644 --- a/src/main/agent-hooks/server/server-persistence.ts +++ b/src/main/agent-hooks/server/server-persistence.ts @@ -19,6 +19,7 @@ import { pruneAgentExits, serializeAgentExits } from './agent-exit-evidence' import { LastStatusStore } from './last-status-store' import { KeyedDeadlines } from '../../../shared/collections/keyed-deadlines' import { rowsOf, selectedStatusEntries } from './last-status-saved-rows' +import { cliWriterTopology } from './cli-writer-topology' import { nextRetryDelayMs } from '../../sqlite/row-cache/row-cache-failure' export abstract class AgentHookServerPersistence extends AgentHookServerHydration { @@ -97,7 +98,8 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio entries[paneKey] = { ...persistedPayload, payload: persistedStatus, - ...(launchTokenHash ? { launchTokenHash } : {}) + ...(launchTokenHash ? { launchTokenHash } : {}), + ...(cliWriterTopology(enrichedPayload) === 'shared' ? { sharedHost: true as const } : {}) } const commitment = this.toAuthorityEvidence(persistedPayload, launchTokenHash) if (commitment && !conflictedCommitments.has(paneKey)) { diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 039b41d3e50c..2e4e6d1488ab 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -16,13 +16,24 @@ import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecy export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { abstract checkAgentPresence(paneKey: string): Promise + /** Panes whose last command mark came while the shell was not alone (a shell nested in the + * agent); their agent's later exit is proved by the next mark instead. */ + private readonly unprovenCommandExitPaneKeys = new Set() retireProcessAuthority( paneKey: string, - options?: Pick + options?: Pick & { launchRetired?: true } ): void { + const resolved = this.resolvePaneKeyAlias(paneKey) + if (options?.launchRetired) { + if (this.unprovenCommandExitPaneKeys.has(resolved)) { + void this.confirmCommandFinishedExit(resolved) + } + return + } const identity = this.paneAgentIdentity(paneKey) const shared = identity?.processTopology === 'shared' + this.unprovenCommandExitPaneKeys.delete(resolved) // A command mark can come from a shell nested in a live agent; one with no process to probe // ends only on the host's word that the pane's shell is alone. const awaitsHost = options?.confirmedExit === true && !this.hasVerifiableAgentProcess(paneKey) @@ -50,12 +61,18 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { const resolved = this.resolvePaneKeyAlias(paneKey) const row = this.state.lastStatusByPaneKey.get(resolved) const alone = await this.terminalPaneLifecycle?.confirmShellAlone?.(resolved) - if (alone === true && this.state.lastStatusByPaneKey.get(resolved) === row) { - this.reconcileEndedProcessForPaneKeys([resolved], { - preserveResumeIdentity: true, - confirmedExit: true - }) + if (this.state.lastStatusByPaneKey.get(resolved) !== row) { + return } + if (alone !== true) { + this.unprovenCommandExitPaneKeys.add(resolved) + return + } + this.unprovenCommandExitPaneKeys.delete(resolved) + this.reconcileEndedProcessForPaneKeys([resolved], { + preserveResumeIdentity: true, + confirmedExit: true + }) } hasVerifiableAgentProcess(paneKey: string): boolean { @@ -140,6 +157,11 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { dropStatusEntriesByTabPrefix(tabId: string): void { this.markTabClosedForAgentStatus(tabId) this.clearTmuxTabSubjects(tabId) + for (const key of this.unprovenCommandExitPaneKeys) { + if (paneCacheKeyMatchesTab(key, tabId)) { + this.unprovenCommandExitPaneKeys.delete(key) + } + } const paneKeysToClear = new Set() const statusPaneKeysToClear = new Set() const statusRowsToClear: EnrichedAgentHookEventPayload[] = [] @@ -259,6 +281,7 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } ): void { const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey) + this.unprovenCommandExitPaneKeys.delete(resolvedPaneKey) if (options?.forgetAgentExit) { this.forgetAgentExit(paneKey) } diff --git a/src/main/agent-hooks/server/server-types.ts b/src/main/agent-hooks/server/server-types.ts index bffd9452e7d9..f53d4c3086aa 100644 --- a/src/main/agent-hooks/server/server-types.ts +++ b/src/main/agent-hooks/server/server-types.ts @@ -84,6 +84,8 @@ export type PersistedAgentHookEventPayload = Omit< | 'replyCandidate' > & { launchTokenHash?: string + /** A tmux or shared server runs this conversation; restores the binding's topology on hydration. */ + sharedHost?: true } export type PersistedAgentHookAuthorityCommitment = { diff --git a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts index fd2107e58e3b..27293651cb56 100644 --- a/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-legacy-sleep.test.ts @@ -1,3 +1,6 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { expect, it, vi } from 'vitest' import { PANE } from '../server.test-fixtures' import { @@ -33,8 +36,8 @@ registerRootTestHarness() const CLIENT: Proc = [4050, 101, 4050, 'tmux -L qa attach', 'S+'] // A pane the runtime places, so the hook's binding keeps the topology it reported. -async function placedServer(): Promise { - const server = await createServer() +async function placedServer(userDataPath?: string): Promise { + const server = await createServer(userDataPath) server.setHookRootEvidenceReader((request) => readHookRootEvidence(request, io)) const identities = new AgentStatusObservedPaneIdentities() const observed = new AgentStatusObservedPaneIdentityCapture(identities) @@ -108,15 +111,8 @@ it.each([ } ) -it('leaves a tmux-hosted conversation no checkpoint, so a restart cannot resume it beside its server', async () => { - const checkpointOf = async (tmuxPane?: string) => { - const server = await placedServer() - await hook(server, 'UserPromptSubmit', { - session: 'detached-session', - pid: 4043, - prompt: 'In tmux', - ...(tmuxPane ? { tmuxPane } : {}) - }) +it('leaves a tmux-hosted conversation no checkpoint, before or after a restart', async () => { + const checkpointOf = (server: RootTestServer) => { const row = server.row() const status = row && resumeStatusFromHookRow(row, undefined) return status @@ -129,7 +125,26 @@ it('leaves a tmux-hosted conversation no checkpoint, so a restart cannot resume }) : null } - expect(await checkpointOf()).toMatchObject({ origin: 'live' }) - // Detached or not, the tmux server keeps the agent; the pane must not resume it after a restart. - expect(await checkpointOf(TMUX_HINT)).toBeNull() + const runIn = async (userDataPath: string, tmuxPane?: string) => { + const server = await placedServer(userDataPath) + await hook(server, 'UserPromptSubmit', { + session: 'detached-session', + pid: 4043, + prompt: 'In tmux', + ...(tmuxPane ? { tmuxPane } : {}) + }) + const before = checkpointOf(server) + server.flushStatusPersistSync() + server.stop() + // A restart hydrates the row; the agent still runs (in tmux, detached or not). + const restarted = await createServer(userDataPath) + const after = restarted.row() && checkpointOf(restarted) + restarted.stop() + return [before, after] + } + expect(await runIn(mkdtempSync(join(tmpdir(), 'orca-pane-')))).toEqual([ + expect.objectContaining({ origin: 'live' }), + expect.objectContaining({ origin: 'live' }) + ]) + expect(await runIn(mkdtempSync(join(tmpdir(), 'orca-tmux-')), TMUX_HINT)).toEqual([null, null]) }) diff --git a/src/main/antigravity/posix-hook-invocation.test.ts b/src/main/antigravity/posix-hook-invocation.test.ts index 76ebd1dc623e..5d65fe923857 100644 --- a/src/main/antigravity/posix-hook-invocation.test.ts +++ b/src/main/antigravity/posix-hook-invocation.test.ts @@ -152,29 +152,37 @@ describe.skipIf(process.platform === 'win32')('Antigravity POSIX hook executable 10000 ) - it('preserves process and tmux evidence in startup spool bodies', async () => { - home = mkdtempSync(join(tmpdir(), 'orca-agy-spool-')) - const endpoint = join(home, 'endpoint.sh') - writeFileSync(endpoint, '# endpoint not ready\n') - const result = await invoke(installedCommand(home, 'PreInvocation'), '{}', { - ...process.env, - ORCA_AGENT_HOOK_ENDPOINT: endpoint, - ORCA_AGENT_HOOK_PORT: '', - ORCA_AGENT_HOOK_TOKEN: '', - ORCA_PANE_KEY: 'test-pane', - ORCA_HOOK_AGENT_PID: '2', - TMUX: '/tmp/agy-test.sock,123,0', - TMUX_PANE: '%4' - }) - expect(result.code).toBe(0) - const spool = join(home, 'spool') - const { records } = readSpoolFile(join(spool, readdirSync(spool)[0])) - expect(records).toHaveLength(1) - const body = buildSpoolHookBody(records[0]) - expect(JSON.parse(String(body.agentProcess))).toMatchObject({ pid: process.pid }) - expect(body.tmuxPane).toBe('%4 /tmp/agy-test.sock') - expect(body.hookEventName).toBe('PreInvocation') - }) + it.each([ + ['a tmux started in the pane', '', '%4 /tmp/agy-test.sock'], + // Orca itself runs in that tmux pane; the pane hosts no tmux of its own. + ["Orca's own tmux", '%4 /tmp/agy-test.sock', ''] + ])( + 'keeps process evidence and reports %s in startup spool bodies', + async (_, inherited, pane) => { + home = mkdtempSync(join(tmpdir(), 'orca-agy-spool-')) + const endpoint = join(home, 'endpoint.sh') + writeFileSync(endpoint, '# endpoint not ready\n') + const result = await invoke(installedCommand(home, 'PreInvocation'), '{}', { + ...process.env, + ORCA_AGENT_HOOK_ENDPOINT: endpoint, + ORCA_AGENT_HOOK_PORT: '', + ORCA_AGENT_HOOK_TOKEN: '', + ORCA_PANE_KEY: 'test-pane', + ORCA_HOOK_AGENT_PID: '2', + TMUX: '/tmp/agy-test.sock,123,0', + TMUX_PANE: '%4', + ORCA_INHERITED_TMUX: inherited + }) + expect(result.code).toBe(0) + const spool = join(home, 'spool') + const { records } = readSpoolFile(join(spool, readdirSync(spool)[0])) + expect(records).toHaveLength(1) + const body = buildSpoolHookBody(records[0]) + expect(JSON.parse(String(body.agentProcess))).toMatchObject({ pid: process.pid }) + expect(body.tmuxPane).toBe(pane) + expect(body.hookEventName).toBe('PreInvocation') + } + ) it.each([ ['PreToolUse', '{"decision":"ask"}'], diff --git a/src/main/daemon/pty-subprocess/spawn-environment.ts b/src/main/daemon/pty-subprocess/spawn-environment.ts index ec603097453f..7c4a514a1dc2 100644 --- a/src/main/daemon/pty-subprocess/spawn-environment.ts +++ b/src/main/daemon/pty-subprocess/spawn-environment.ts @@ -10,6 +10,7 @@ import { stripPiProcessOwnerEnv } from '../../pty/shell-startup/pi-process-owner import { dropIncoherentCondaActivationEnv } from '../../pty/shell-startup/conda-activation-env' import { stripLegacyTerminalShimEnv } from '../../pty/shell-startup/legacy-terminal-shim-dir' import { removeInheritedNoColor } from '../../pty/shell-startup/terminal-color-env' +import { stampInheritedTmuxEnv } from '../../pty/shell-startup/inherited-tmux-env' import { resolvePathEnvKey } from '../../pty/environment/windows-path-segment-merge' import { dropInheritedOrcaHistFile } from '../../pty/history/worktree-history-file-path' import { @@ -194,6 +195,7 @@ export function createDaemonPtyEnvironment(opts: PtySubprocessOptions): Record - rootPid === 4242 && JSON.stringify(options) === '{"noLiveDescendants":true}' - ? proveShellAlone() - : false + confirmRootShellAlone.mockImplementation(async (rootPid: number) => + rootPid === 4242 ? proveShellAlone() : false ) getProviderForPty.mockReturnValue({ listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }], diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index a4301fead726..78ad22c672ff 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -132,7 +132,7 @@ async function paneShellAlone( } } -/** The shell alone holds the PTY, with no job behind it, stopped or running. A daemon answers +/** The shell alone holds the PTY, with no stopped job behind it. A daemon answers * shell ownership from prompt marks, so POSIX reads the PTY's root shell from a fresh process * table instead, local or daemon alike. Windows shells stop no jobs, so the host's job census * finding no child beside a shell foreground suffices there. Never fall back to a foreground @@ -142,9 +142,7 @@ async function confirmShellAlone(ptyId: string, incarnationId?: string): Promise if (process.platform !== 'win32') { const processes = await provider.listProcesses({ ptyIds: [ptyId] }).catch(() => []) const rootPid = processes.find((entry) => entry.id === ptyId)?.rootProcessId - return rootPid - ? confirmRootShellAloneFromProcessTable(rootPid, { noLiveDescendants: true }) - : false + return rootPid ? confirmRootShellAloneFromProcessTable(rootPid) : false } if ((await provider.confirmShellForeground?.(ptyId)) === true) { return true diff --git a/src/main/providers/foreground/agent-process-shell-alone.test.ts b/src/main/providers/foreground/agent-process-shell-alone.test.ts deleted file mode 100644 index 393f1c6f1e2e..000000000000 --- a/src/main/providers/foreground/agent-process-shell-alone.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it, vi } from 'vitest' -import type { ProcessTableRow } from '../../../shared/process-observation/tables/process-table-snapshot' - -const { snapshot } = vi.hoisted(() => ({ snapshot: vi.fn<() => Promise>() })) -vi.mock( - '../../../shared/process-observation/tables/process-table-snapshot-reader', - async (load) => ({ - ...(await load()), - getFreshShellForegroundSnapshot: snapshot - }) -) - -const { confirmShellForegroundProcess } = await import('./agent-process') - -const SHELL: ProcessTableRow = { pid: 100, ppid: 1, stat: 'Ss+', command: '/bin/zsh' } - -it.skipIf(process.platform === 'win32').each([ - ['shell alone', [], false, true], - ['stopped agent (Ctrl-Z)', [{ pid: 101, ppid: 100, stat: 'T', command: 'codex' }], false, false], - [ - 'background agent (Ctrl-Z, then bg), foreground read', - [{ pid: 101, ppid: 100, stat: 'S', command: 'codex' }], - false, - true - ], - [ - 'background agent (Ctrl-Z, then bg), exit proof', - [{ pid: 101, ppid: 100, stat: 'S', command: 'codex' }], - true, - false - ], - ['reaped zombie, exit proof', [{ pid: 101, ppid: 100, stat: 'Z', command: 'codex' }], true, true] -] as const)('confirms the shell alone: %s', async (_, children, noLiveDescendants, expected) => { - snapshot.mockResolvedValue([SHELL, ...children]) - expect(await confirmShellForegroundProcess(100, '/bin/zsh', { noLiveDescendants })).toBe(expected) -}) diff --git a/src/main/providers/foreground/agent-process.ts b/src/main/providers/foreground/agent-process.ts index 3ca3bd876809..26ed3049ec20 100644 --- a/src/main/providers/foreground/agent-process.ts +++ b/src/main/providers/foreground/agent-process.ts @@ -11,7 +11,8 @@ import { } from '../../../shared/process-observation/tables/process-table-snapshot-reader' import { collectDescendantsFromIndex, - getProcessTableIndex + getProcessTableIndex, + type ProcessTableIndex } from '../../../shared/process-observation/tables/process-table-index' import { resolveWindowsAgentForegroundProcessWithAvailability, @@ -46,11 +47,11 @@ type ShellForegroundConfirmationOptions = { | null | Promise | null> readWindowsProcessIdentityTable?: () => Promise - /** Exit proof: a running background job (Ctrl-Z, then bg) also keeps the agent alive. */ - noLiveDescendants?: boolean + /** POSIX: a capture the caller already took, so one proof costs one table read. */ + processIndex?: ProcessTableIndex } -function commandExecutable(command: string): string { +export function commandExecutable(command: string): string { const trimmed = command.trim().replace(/^[-]/, '') if (trimmed.startsWith('"') || trimmed.startsWith("'")) { const closingQuote = trimmed.indexOf(trimmed[0], 1) @@ -85,7 +86,8 @@ export async function confirmShellForegroundProcess( } } try { - const index = getProcessTableIndex(await getFreshShellForegroundSnapshot()) + const index = + options.processIndex ?? getProcessTableIndex(await getFreshShellForegroundSnapshot()) const root = index.byPid.get(shellPid) if (!root) { return false @@ -104,11 +106,6 @@ export async function confirmShellForegroundProcess( return false } const confirmed = foregroundShell?.stat.includes('+') === true - if (confirmed && foregroundShell && options.noLiveDescendants) { - return !collectDescendantsFromIndex(index, foregroundShell.pid).some( - (row) => !row.stat.includes('Z') - ) - } return confirmed } catch { return false diff --git a/src/main/providers/local-pty/local-pty-spawn-environment.ts b/src/main/providers/local-pty/local-pty-spawn-environment.ts index 27f1391b9788..c5dce5621f0f 100644 --- a/src/main/providers/local-pty/local-pty-spawn-environment.ts +++ b/src/main/providers/local-pty/local-pty-spawn-environment.ts @@ -9,6 +9,7 @@ import { removeChromiumDisabledSessionBus } from '../../pty/shell-startup/chromi import { stripInheritedBuildModeEnv } from '../../pty/shell-startup/build-mode-env' import { stripPiProcessOwnerEnv } from '../../pty/shell-startup/pi-process-owner-env' import { removeInheritedNoColor } from '../../pty/shell-startup/terminal-color-env' +import { stampInheritedTmuxEnv } from '../../pty/shell-startup/inherited-tmux-env' import { isWindowsGitBashShellPath } from '../../pty/shell-startup/git-bash' import { applyScrubSafeAgentEnvAliases } from '../../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env' import { removeUnspecifiedPaneIdentityEnv } from './local-pty-launch-context' @@ -71,6 +72,7 @@ export function buildInheritedLocalPtyEnvironment( [ORCA_IMAGE_PROTOCOL_ENV]: ORCA_IMAGE_PROTOCOL_VALUE } satisfies Record removeUnspecifiedPaneIdentityEnv(spawnEnv, explicitEnv) + stampInheritedTmuxEnv(spawnEnv, explicitEnv) stripPiProcessOwnerEnv(spawnEnv) removeAppImageRuntimeEnv(spawnEnv) removeChromiumDisabledSessionBus(spawnEnv) diff --git a/src/main/pty/shell-startup/inherited-tmux-env.ts b/src/main/pty/shell-startup/inherited-tmux-env.ts new file mode 100644 index 000000000000..f5664858b1da --- /dev/null +++ b/src/main/pty/shell-startup/inherited-tmux-env.ts @@ -0,0 +1,15 @@ +export const ORCA_INHERITED_TMUX_ENV = 'ORCA_INHERITED_TMUX' + +/** Names the tmux pane Orca itself runs in, so hooks don't take it for a tmux started in the pane. */ +export function stampInheritedTmuxEnv( + env: Record, + explicitEnv: Record | undefined +): void { + delete env[ORCA_INHERITED_TMUX_ENV] + const { TMUX: tmux, TMUX_PANE: pane } = env + if (!tmux || !pane || explicitEnv?.TMUX !== undefined || explicitEnv?.TMUX_PANE !== undefined) { + return + } + // Same " " shape the hook scripts report: TMUX minus its ",pid,session" tail. + env[ORCA_INHERITED_TMUX_ENV] = `${pane} ${tmux.replace(/,[^,]*,[^,]*$/, '')}` +} diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index d8ec6ddc0672..36d816e3a814 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -71,9 +71,10 @@ export type RuntimeConstructionDependencies = { connectionId: string | null terminalProvenance: 'current_runtime' | 'restored' }) => AgentHookAuthorityAttestation | null + /** `launchRetired`: a command finished after an earlier mark already retired the launch. */ retireAgentHookCompatibilityAuthority?: ( paneKey: string, - options?: { confirmedExit?: boolean } + options?: { confirmedExit?: boolean; launchRetired?: true } ) => void readHookCliWriterObservation?: (row: AgentStatusIpcPayload) => CliWriterObservation | null /** `exitedSince`: also answer `exited` for an exit the hook store proved at or after it. */ diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts new file mode 100644 index 000000000000..68efa3ea2379 --- /dev/null +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts @@ -0,0 +1,39 @@ +import { expect, it, vi } from 'vitest' +import type { ProcessTableRow } from '../../../../shared/process-observation/tables/process-table-snapshot' + +const { snapshot } = vi.hoisted(() => ({ snapshot: vi.fn<() => Promise>() })) +vi.mock( + '../../../../shared/process-observation/tables/process-table-snapshot-reader', + async (load) => ({ + ...(await load()), + getFreshShellForegroundSnapshot: snapshot + }) +) + +const { confirmRootShellAloneFromProcessTable } = await import('./run-terminal-shell-alone') + +const SHELL: ProcessTableRow = { pid: 100, ppid: 1, stat: 'Ss+', command: '/bin/zsh' } +// macOS roots each PTY at login, with the login shell beneath it. +const LOGIN: ProcessTableRow = { pid: 90, ppid: 1, stat: 'Ss', command: '/usr/bin/login -flp me' } +const LOGIN_SHELL: ProcessTableRow = { pid: 100, ppid: 90, stat: 'S+', command: '-zsh' } + +it.skipIf(process.platform === 'win32').each([ + ['a shell root, alone', 100, [SHELL], true], + ['a login root, its shell alone', 90, [LOGIN, LOGIN_SHELL], true], + [ + 'a login root, an agent stopped (Ctrl-Z)', + 90, + [LOGIN, LOGIN_SHELL, { pid: 101, ppid: 100, stat: 'T', command: 'codex' }], + false + ], + [ + 'a login root, an agent in the foreground', + 90, + [LOGIN, { ...LOGIN_SHELL, stat: 'S' }, { pid: 101, ppid: 100, stat: 'S+', command: 'codex' }], + false + ], + ['no shell under the root', 90, [LOGIN], false] +] as const)('confirms the shell alone from %s', async (_, rootPid, rows, expected) => { + snapshot.mockResolvedValue([...rows]) + expect(await confirmRootShellAloneFromProcessTable(rootPid)).toBe(expected) +}) diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts index 6d71e5a12f27..62f0cb935055 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts @@ -1,23 +1,32 @@ /** Read execution-host process tables: daemon shell-ownership changes only after full-screen exit and misses plain failed/finished commands. Observation failure is unproven. */ -import { confirmShellForegroundProcess } from '../../../providers/foreground/agent-process' -import { getFreshProcessTableSnapshot } from '../../../../shared/process-observation/tables/process-table-snapshot-reader' -import { getProcessTableIndex } from '../../../../shared/process-observation/tables/process-table-index' +import { + commandExecutable, + confirmShellForegroundProcess +} from '../../../providers/foreground/agent-process' +import { getFreshShellForegroundSnapshot } from '../../../../shared/process-observation/tables/process-table-snapshot-reader' +import { + collectDescendantsFromIndex, + getProcessTableIndex +} from '../../../../shared/process-observation/tables/process-table-index' import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import type { TerminalProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' -/** POSIX: the PTY's root shell owns the terminal's foreground group and nothing under it is stopped - * (nor, for exit proof, still running). */ -export async function confirmRootShellAloneFromProcessTable( - rootPid: number, - options?: { noLiveDescendants?: boolean } -): Promise { +/** POSIX: the PTY's shell owns the terminal's foreground group and nothing under it is stopped. */ +export async function confirmRootShellAloneFromProcessTable(rootPid: number): Promise { try { - const root = getProcessTableIndex(await getFreshProcessTableSnapshot()).byPid.get(rootPid) - const executable = root?.command.trim().split(/\s+/, 1)[0] ?? '' - if (!isShellProcess(executable)) { + const processIndex = getProcessTableIndex(await getFreshShellForegroundSnapshot()) + const root = processIndex.byPid.get(rootPid) + if (!root) { return false } - return await confirmShellForegroundProcess(rootPid, executable, options) + // macOS roots each PTY at /usr/bin/login, with the login shell beneath it. + const shell = [{ ...root, depth: 0 }, ...collectDescendantsFromIndex(processIndex, rootPid)] + .map((row) => ({ depth: row.depth, executable: commandExecutable(row.command) })) + .filter((row) => isShellProcess(row.executable)) + .sort((left, right) => left.depth - right.depth)[0] + return shell + ? await confirmShellForegroundProcess(rootPid, shell.executable, { processIndex }) + : false } catch { return false } diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 4bfdfdd2d7fc..4f7271db5eab 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -185,10 +185,13 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O const pty = this.retireHeldLaunch(ptyId) const receipt = this.restoredOrchestrationAuthorityByPtyId.get(ptyId) const launch = pty && (pty.launchToken || pty.launchAgent || pty.launchCommandAgent) - if (!pty || (!launch && !receipt)) { + // With nothing held, an earlier mark (maybe a nested shell's) retired the launch this one ends. + if (!pty || (!launch && !receipt && !confirmedExit)) { return } const exited = confirmedExit && Boolean(launch || (receipt && !finishedBefore)) + const retirement = + launch || receipt ? { confirmedExit: exited } : { launchRetired: true as const } // Why: collect before the delete below, which drops the restored-authority receipt a // receipt-only pane's key comes from. const paneKeys = this.collectPaneKeysForPty(ptyId) @@ -199,7 +202,7 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O pty.launchAgent = null pty.launchCommandAgent = null for (const paneKey of paneKeys) { - this.retireAgentHookCompatibilityAuthorityFn?.(paneKey, { confirmedExit: exited }) + this.retireAgentHookCompatibilityAuthorityFn?.(paneKey, retirement) } if (changed) { void this.refreshAgentSenderAssociations().catch(console.warn) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 383143766428..e41cc4fa2666 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -236,6 +236,7 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini ['quit', ['0'], false], ['quit without command marks', ['unmarked'], false], ['a shell nested in the live Codex finishing a command', ['nested'], true], + ['a nested shell finishing a command, then quit', ['nested', '0'], false], ['suspended', ['148'], true], ['macOS suspended', ['146'], true], ['suspended, then another command', ['148', '0'], true], From 02d6d8d95ac641ccb3fed5a148e97315d20c8263 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:49:12 -0800 Subject: [PATCH 076/125] fix(sleep): prove unseen agent exits per pane without rescanning, and keep main's word where no host proof exists - Track panes whose process-less agent may have ended unseen (a nested shell's mark or a job stop) in one tracker: a mark re-proves, one proof per pane at a time, a mark during it asks for one more, and a stale proof can't re-add a cleared pane. - Ctrl-Z, fg, then /quit ends the conversation again. - Remote and Windows panes give no shell proof, so a command mark ends the agent as on main. - Only a stopped agent blocks the proof; a stopped editor from before the launch doesn't. - Cache each PTY's root PID per incarnation instead of listing every terminal per proof. --- src/main/agent-hooks/server/server-state.ts | 5 +- .../agent-hooks/server/server-tab-cleanup.ts | 44 ++++++------- .../server/unproven-agent-exits.test.ts | 22 +++++++ .../server/unproven-agent-exits.ts | 61 +++++++++++++++++++ .../terminal-pane-status-lifecycle.test.ts | 3 +- .../pane/terminal-pane-status-lifecycle.ts | 52 +++++++++++++--- .../providers/foreground/agent-process.ts | 7 ++- .../runtime-construction-dependencies.ts | 2 +- .../run-terminal-shell-alone.test.ts | 15 ++++- .../lifecycle/run-terminal-shell-alone.ts | 17 +++++- .../terminal-orchestration-authority.ts | 11 ++-- .../worktree-sleep-resume-recording.test.ts | 14 +++-- 12 files changed, 199 insertions(+), 54 deletions(-) create mode 100644 src/main/agent-hooks/server/unproven-agent-exits.test.ts create mode 100644 src/main/agent-hooks/server/unproven-agent-exits.ts diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index cb8f44820686..dc8ec491ce6d 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -54,8 +54,9 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract retireSavedRecord?(paneKey: string, exitedAt: number): void readSavedRecord?(paneKey: string): SleepingAgentSessionRecord | undefined confirmProcessExit?(paneKey: string, agent: string): Promise - /** The host's word that the pane's shell holds its PTY alone, whatever launch it ran. */ - confirmShellAlone?(paneKey: string): Promise + /** The host's word that the pane's shell holds its PTY alone, whatever launch it ran; null + * where the host gives none (remote, Windows), so a command mark stands as on main. */ + confirmShellAlone?(paneKey: string): Promise ownsProcess(paneKey: string, ptyId: string, incarnationId?: string): boolean isStopping(paneKey: string): boolean isReversibleStop(ptyId: string, incarnationId?: string): boolean diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 2e4e6d1488ab..455e979bb58e 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -12,30 +12,32 @@ import type { AgentStatusCacheIdentity, RefusedPaneResume } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' +import { UnprovenAgentExits } from './unproven-agent-exits' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { abstract checkAgentPresence(paneKey: string): Promise - /** Panes whose last command mark came while the shell was not alone (a shell nested in the - * agent); their agent's later exit is proved by the next mark instead. */ - private readonly unprovenCommandExitPaneKeys = new Set() + private readonly unprovenExits = new UnprovenAgentExits((paneKey) => + this.confirmCommandFinishedExit(paneKey) + ) retireProcessAuthority( paneKey: string, - options?: Pick & { launchRetired?: true } + options?: Pick & { + jobStopped?: boolean + launchRetired?: true + } ): void { const resolved = this.resolvePaneKeyAlias(paneKey) if (options?.launchRetired) { - if (this.unprovenCommandExitPaneKeys.has(resolved)) { - void this.confirmCommandFinishedExit(resolved) - } + this.unprovenExits.onCommandFinished(resolved) return } const identity = this.paneAgentIdentity(paneKey) const shared = identity?.processTopology === 'shared' - this.unprovenCommandExitPaneKeys.delete(resolved) // A command mark can come from a shell nested in a live agent; one with no process to probe // ends only on the host's word that the pane's shell is alone. + const unprovable = Boolean(identity) && !shared && !this.hasVerifiableAgentProcess(paneKey) const awaitsHost = options?.confirmedExit === true && !this.hasVerifiableAgentProcess(paneKey) const confirmedExit = options?.confirmedExit === true && !awaitsHost const { paneKeys, authorityChanged } = this.revokeProcessAuthority(paneKey) @@ -44,9 +46,9 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { { confirmedExit, preserveResumeIdentity: !confirmedExit && !shared }, (key) => this.clearRevokedPaneState(key) ) - if (awaitsHost && identity && !shared) { - void this.confirmCommandFinishedExit(paneKey) - } + // A stopped job (Ctrl-Z) may later resume and quit at a mark that finds no launch left. + const unseen = unprovable && (awaitsHost || options?.jobStopped === true) + this.unprovenExits.launchRetired(resolved, unseen, awaitsHost) for (const key of untouched) { this.clearTmuxInnerSubjects(key) this.clearPaneProcessState(key) @@ -57,22 +59,20 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } } - private async confirmCommandFinishedExit(paneKey: string): Promise { - const resolved = this.resolvePaneKeyAlias(paneKey) + private async confirmCommandFinishedExit(resolved: string): Promise { const row = this.state.lastStatusByPaneKey.get(resolved) const alone = await this.terminalPaneLifecycle?.confirmShellAlone?.(resolved) if (this.state.lastStatusByPaneKey.get(resolved) !== row) { - return + return true } - if (alone !== true) { - this.unprovenCommandExitPaneKeys.add(resolved) - return + if (alone === false) { + return false } - this.unprovenCommandExitPaneKeys.delete(resolved) this.reconcileEndedProcessForPaneKeys([resolved], { preserveResumeIdentity: true, confirmedExit: true }) + return true } hasVerifiableAgentProcess(paneKey: string): boolean { @@ -157,11 +157,7 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { dropStatusEntriesByTabPrefix(tabId: string): void { this.markTabClosedForAgentStatus(tabId) this.clearTmuxTabSubjects(tabId) - for (const key of this.unprovenCommandExitPaneKeys) { - if (paneCacheKeyMatchesTab(key, tabId)) { - this.unprovenCommandExitPaneKeys.delete(key) - } - } + this.unprovenExits.forgetWhere((key) => paneCacheKeyMatchesTab(key, tabId)) const paneKeysToClear = new Set() const statusPaneKeysToClear = new Set() const statusRowsToClear: EnrichedAgentHookEventPayload[] = [] @@ -281,7 +277,7 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } ): void { const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey) - this.unprovenCommandExitPaneKeys.delete(resolvedPaneKey) + this.unprovenExits.forget(resolvedPaneKey) if (options?.forgetAgentExit) { this.forgetAgentExit(paneKey) } diff --git a/src/main/agent-hooks/server/unproven-agent-exits.test.ts b/src/main/agent-hooks/server/unproven-agent-exits.test.ts new file mode 100644 index 000000000000..9424a456ac50 --- /dev/null +++ b/src/main/agent-hooks/server/unproven-agent-exits.test.ts @@ -0,0 +1,22 @@ +import { expect, it } from 'vitest' +import { UnprovenAgentExits } from './unproven-agent-exits' + +it('re-proves once for a mark that lands while the first proof still reads a live agent', async () => { + const answers: ((settled: boolean) => void)[] = [] + const exits = new UnprovenAgentExits( + () => new Promise((resolve) => answers.push(resolve)) + ) + // A nested shell's mark starts a proof that sees the live agent... + exits.launchRetired('pane', true, true) + // ...which quits at its real mark before that proof answers. + exits.onCommandFinished('pane') + exits.onCommandFinished('pane') + expect(answers).toHaveLength(1) + answers[0](false) + await new Promise((resolve) => setImmediate(resolve)) + expect(answers).toHaveLength(2) + answers[1](true) + await new Promise((resolve) => setImmediate(resolve)) + exits.onCommandFinished('pane') + expect(answers).toHaveLength(2) +}) diff --git a/src/main/agent-hooks/server/unproven-agent-exits.ts b/src/main/agent-hooks/server/unproven-agent-exits.ts new file mode 100644 index 000000000000..36234cbfb11b --- /dev/null +++ b/src/main/agent-hooks/server/unproven-agent-exits.ts @@ -0,0 +1,61 @@ +type UnprovenExit = { proving: boolean; again: boolean } + +/** Panes whose process-less agent may have ended unseen: its launch retired on a job stop, or on + * a command mark the shell-alone proof refused (a shell nested in the live agent). Each later + * mark re-proves; one proof per pane runs at a time, and a mark during it asks for one more. */ +export class UnprovenAgentExits { + private readonly panes = new Map() + + /** `prove` answers whether the pane is settled: its exit was confirmed, or a newer row owns it. */ + constructor(private readonly prove: (paneKey: string) => Promise) {} + + /** A launch retired; `unseen`: its agent may still end unseen, `proveNow`: a mark said it ended. + * Replaces any earlier entry, so a proof still running for that one no longer counts. */ + launchRetired(paneKey: string, unseen: boolean, proveNow: boolean): void { + if (!unseen) { + this.panes.delete(paneKey) + return + } + this.panes.set(paneKey, { proving: false, again: false }) + if (proveNow) { + this.onCommandFinished(paneKey) + } + } + + forget(paneKey: string): void { + this.panes.delete(paneKey) + } + + forgetWhere(matches: (paneKey: string) => boolean): void { + for (const paneKey of this.panes.keys()) { + if (matches(paneKey)) { + this.panes.delete(paneKey) + } + } + } + + onCommandFinished(paneKey: string): void { + const entry = this.panes.get(paneKey) + if (!entry || entry.proving) { + if (entry) { + entry.again = true + } + return + } + entry.proving = true + entry.again = false + void this.prove(paneKey) + .catch(() => false) + .then((settled) => { + if (this.panes.get(paneKey) !== entry) { + return + } + entry.proving = false + if (settled) { + this.panes.delete(paneKey) + } else if (entry.again) { + this.onCommandFinished(paneKey) + } + }) + } +} diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index a0c26e7985d3..df20d4e94a62 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -13,7 +13,8 @@ vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ })) vi.mock('../provider/registry', () => ({ getProviderForPty })) vi.mock('../../../runtime/terminal/lifecycle/run-terminal-shell-alone', () => ({ - confirmRootShellAloneFromProcessTable: confirmRootShellAlone + confirmRootShellAloneFromProcessTable: confirmRootShellAlone, + isStoppedAgent: () => true })) const platform = process.platform diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 78ad22c672ff..b70e5da96041 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -11,7 +11,10 @@ import { getProviderForPty } from '../provider/registry' import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import { isRemoteExecutionHostPtyId } from '../../../../shared/execution-host/remote-execution-host-pty-id' -import { confirmRootShellAloneFromProcessTable } from '../../../runtime/terminal/lifecycle/run-terminal-shell-alone' +import { + confirmRootShellAloneFromProcessTable, + isStoppedAgent +} from '../../../runtime/terminal/lifecycle/run-terminal-shell-alone' export function bindTerminalPaneStatusLifecycle( runtime: OrcaRuntimeService | undefined, @@ -29,13 +32,15 @@ export function bindTerminalPaneStatusLifecycle( runtime, paneKey, () => runtime?.getLaunchStatementForPaneKey(paneKey, agent) === launch - )) + )) === true ) } catch { return false } }, - confirmShellAlone: (paneKey) => paneShellAlone(runtime, paneKey), + // Windows gives a command mark no proof against a nested shell, so the mark stands, as on main. + confirmShellAlone: async (paneKey) => + process.platform === 'win32' ? null : paneShellAlone(runtime, paneKey), readSavedRecord: (paneKey) => { try { const worktreeId = runtime?.getTerminalWorktreeIdForPaneKey(paneKey) @@ -105,20 +110,24 @@ export function bindTerminalPaneStatusLifecycle( agentHookServer.pruneUnplacedSleepingPanes() } -/** A local pane's shell alone holds its PTY, and the pane still runs that PTY afterwards. */ +/** A local pane's shell alone holds its PTY, and the pane still runs that PTY afterwards; null on + * a remote host, which reports no process tree to main. */ async function paneShellAlone( runtime: OrcaRuntimeService | undefined, paneKey: string, stillCurrent: () => boolean = () => true -): Promise { +): Promise { if (!runtime) { return false } try { const pane = runtime.resolveTerminalPane(paneKey) - if (!pane.ptyId || isRemoteExecutionHostPtyId(pane.ptyId)) { + if (!pane.ptyId) { return false } + if (isRemoteExecutionHostPtyId(pane.ptyId)) { + return null + } const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined) const current = runtime.resolveTerminalPane(paneKey) return ( @@ -137,12 +146,37 @@ async function paneShellAlone( * table instead, local or daemon alike. Windows shells stop no jobs, so the host's job census * finding no child beside a shell foreground suffices there. Never fall back to a foreground * name, which a live unrecognized agent shares. */ +// A PTY keeps its root process for its incarnation, so repeated proofs skip the inventory. +const rootPidByPtyIncarnation = new Map() + +async function readPtyRootPid( + provider: ReturnType, + ptyId: string, + incarnationId: string | undefined +): Promise { + const key = `${ptyId}\0${incarnationId ?? ''}` + const known = rootPidByPtyIncarnation.get(key) + if (known) { + return known + } + const processes = await provider.listProcesses({ ptyIds: [ptyId] }).catch(() => []) + const rootPid = processes.find((entry) => entry.id === ptyId)?.rootProcessId + if (rootPid) { + if (rootPidByPtyIncarnation.size >= 64) { + rootPidByPtyIncarnation.delete(rootPidByPtyIncarnation.keys().next().value!) + } + rootPidByPtyIncarnation.set(key, rootPid) + } + return rootPid +} + async function confirmShellAlone(ptyId: string, incarnationId?: string): Promise { const provider = getProviderForPty(ptyId) if (process.platform !== 'win32') { - const processes = await provider.listProcesses({ ptyIds: [ptyId] }).catch(() => []) - const rootPid = processes.find((entry) => entry.id === ptyId)?.rootProcessId - return rootPid ? confirmRootShellAloneFromProcessTable(rootPid) : false + const rootPid = await readPtyRootPid(provider, ptyId, incarnationId) + return rootPid + ? confirmRootShellAloneFromProcessTable(rootPid, { stoppedJobBlocks: isStoppedAgent }) + : false } if ((await provider.confirmShellForeground?.(ptyId)) === true) { return true diff --git a/src/main/providers/foreground/agent-process.ts b/src/main/providers/foreground/agent-process.ts index 26ed3049ec20..deaa69dd515c 100644 --- a/src/main/providers/foreground/agent-process.ts +++ b/src/main/providers/foreground/agent-process.ts @@ -41,7 +41,7 @@ export type AgentForegroundProcessResolution = { anchorPidForeign?: boolean } -type ShellForegroundConfirmationOptions = { +export type ShellForegroundConfirmationOptions = { readWindowsPtyJobProcessIds?: () => | ReadonlySet | null @@ -49,6 +49,8 @@ type ShellForegroundConfirmationOptions = { readWindowsProcessIdentityTable?: () => Promise /** POSIX: a capture the caller already took, so one proof costs one table read. */ processIndex?: ProcessTableIndex + /** POSIX: which stopped jobs deny the shell its foreground; every one by default. */ + stoppedJobBlocks?: (row: ProcessTableRow) => boolean } export function commandExecutable(command: string): string { @@ -102,7 +104,8 @@ export async function confirmShellForegroundProcess( isShellProcess(commandExecutable(row.command)) ) .sort((left, right) => left.depth - right.depth)[0] - if (tree.some((row) => row.depth > 0 && row.stat.includes('T'))) { + const blocks = options.stoppedJobBlocks ?? (() => true) + if (tree.some((row) => row.depth > 0 && row.stat.includes('T') && blocks(row))) { return false } const confirmed = foregroundShell?.stat.includes('+') === true diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 36d816e3a814..21ba14a7a791 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -74,7 +74,7 @@ export type RuntimeConstructionDependencies = { /** `launchRetired`: a command finished after an earlier mark already retired the launch. */ retireAgentHookCompatibilityAuthority?: ( paneKey: string, - options?: { confirmedExit?: boolean; launchRetired?: true } + options?: { confirmedExit?: boolean; jobStopped?: boolean; launchRetired?: true } ) => void readHookCliWriterObservation?: (row: AgentStatusIpcPayload) => CliWriterObservation | null /** `exitedSince`: also answer `exited` for an exit the hook store proved at or after it. */ diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts index 68efa3ea2379..e8f161e7e6c6 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts @@ -10,7 +10,8 @@ vi.mock( }) ) -const { confirmRootShellAloneFromProcessTable } = await import('./run-terminal-shell-alone') +const { confirmRootShellAloneFromProcessTable, isStoppedAgent } = + await import('./run-terminal-shell-alone') const SHELL: ProcessTableRow = { pid: 100, ppid: 1, stat: 'Ss+', command: '/bin/zsh' } // macOS roots each PTY at login, with the login shell beneath it. @@ -32,8 +33,16 @@ it.skipIf(process.platform === 'win32').each([ [LOGIN, { ...LOGIN_SHELL, stat: 'S' }, { pid: 101, ppid: 100, stat: 'S+', command: 'codex' }], false ], - ['no shell under the root', 90, [LOGIN], false] + ['no shell under the root', 90, [LOGIN], false], + [ + 'a login root, an editor stopped before the agent ran', + 90, + [LOGIN, LOGIN_SHELL, { pid: 102, ppid: 100, stat: 'T', command: 'vim notes.md' }], + true + ] ] as const)('confirms the shell alone from %s', async (_, rootPid, rows, expected) => { snapshot.mockResolvedValue([...rows]) - expect(await confirmRootShellAloneFromProcessTable(rootPid)).toBe(expected) + expect( + await confirmRootShellAloneFromProcessTable(rootPid, { stoppedJobBlocks: isStoppedAgent }) + ).toBe(expected) }) diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts index 62f0cb935055..540d324c21ca 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts @@ -1,18 +1,29 @@ /** Read execution-host process tables: daemon shell-ownership changes only after full-screen exit and misses plain failed/finished commands. Observation failure is unproven. */ import { commandExecutable, - confirmShellForegroundProcess + confirmShellForegroundProcess, + type ShellForegroundConfirmationOptions } from '../../../providers/foreground/agent-process' import { getFreshShellForegroundSnapshot } from '../../../../shared/process-observation/tables/process-table-snapshot-reader' import { collectDescendantsFromIndex, getProcessTableIndex } from '../../../../shared/process-observation/tables/process-table-index' +import { recognizeAgentProcessFromCommandLine } from '../../../../shared/agent-status/process/agent-process-recognition' import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import type { TerminalProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' +/** Only a stopped agent keeps an agent's exit unproven; a stopped editor from before its launch + * does not. */ +export function isStoppedAgent(row: { command: string }): boolean { + return recognizeAgentProcessFromCommandLine(row.command) !== null +} + /** POSIX: the PTY's shell owns the terminal's foreground group and nothing under it is stopped. */ -export async function confirmRootShellAloneFromProcessTable(rootPid: number): Promise { +export async function confirmRootShellAloneFromProcessTable( + rootPid: number, + options?: Pick +): Promise { try { const processIndex = getProcessTableIndex(await getFreshShellForegroundSnapshot()) const root = processIndex.byPid.get(rootPid) @@ -25,7 +36,7 @@ export async function confirmRootShellAloneFromProcessTable(rootPid: number): Pr .filter((row) => isShellProcess(row.executable)) .sort((left, right) => left.depth - right.depth)[0] return shell - ? await confirmShellForegroundProcess(rootPid, shell.executable, { processIndex }) + ? await confirmShellForegroundProcess(rootPid, shell.executable, { ...options, processIndex }) : false } catch { return false diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 4f7271db5eab..3146809cbffd 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -179,8 +179,9 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O } } - /** `confirmedExit`: the launched command finished at the shell, so its agent ended. */ - protected retirePtyAgentLaunchAuthority(ptyId: string, confirmedExit = false): void { + /** `confirmedExit`: a command mark said the launched command finished (true) or stopped as a + * job (false); undefined when no mark retires the launch (the PTY exited). */ + protected retirePtyAgentLaunchAuthority(ptyId: string, confirmedExit?: boolean): void { const finishedBefore = this.ptysById.get(ptyId)?.launchEvidence?.kind === 'gone' const pty = this.retireHeldLaunch(ptyId) const receipt = this.restoredOrchestrationAuthorityByPtyId.get(ptyId) @@ -189,9 +190,9 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O if (!pty || (!launch && !receipt && !confirmedExit)) { return } - const exited = confirmedExit && Boolean(launch || (receipt && !finishedBefore)) - const retirement = - launch || receipt ? { confirmedExit: exited } : { launchRetired: true as const } + const exited = confirmedExit === true && Boolean(launch || (receipt && !finishedBefore)) + const ended = { confirmedExit: exited, jobStopped: confirmedExit === false } + const retirement = launch || receipt ? ended : { launchRetired: true as const } // Why: collect before the delete below, which drops the restored-authority receipt a // receipt-only pane's key comes from. const paneKeys = this.collectPaneKeysForPty(ptyId) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index e41cc4fa2666..71f4419d3e11 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -241,13 +241,16 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini ['macOS suspended', ['146'], true], ['suspended, then another command', ['148', '0'], true], ['macOS suspended, then another command', ['146', '0'], true], - ['macOS suspended, then a listing and another command', ['146', 'listing', '0'], true] + ['macOS suspended, then a listing and another command', ['146', 'listing', '0'], true], + ['suspended, resumed (fg), then quit', ['148', 'fg', '0'], false], + ['quit where the host gives no shell proof (remote, Windows)', ['unproven'], false] ] as const)('%s', async (_, finishes, keepsRecovery) => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(1_000) const tick = () => vi.setSystemTime(Date.now() + 1_000) // The host's word on the pane's shell: alone unless a nested shell marked a command. - let shellAlone = true + let shellAlone: boolean | null = true + let stopped = false const fixture = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ sleepingAgentSessionsByPaneKey: { [PANE_KEY]: SLEPT } @@ -333,6 +336,8 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini tick() if (status === 'unmarked') { await server.reconcilePaneProcessExit(PANE_KEY) + } else if (status === 'fg') { + stopped = false } else if (status === 'listing') { // An inventory refresh (`orca worktree ps`) re-mints the restored surface's receipt. // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reaches the protected receipt minter the listing path calls. @@ -346,8 +351,9 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini 'pty-3' ) } else { - shellAlone = status !== 'nested' - const code = status === 'nested' ? '0' : status + stopped ||= status === '148' || status === '146' + shellAlone = status === 'unproven' ? null : status !== 'nested' && !stopped + const code = status === 'nested' || status === 'unproven' ? '0' : status runtime.onPtyData('pty-3', `\x1b]133;C\x07\x1b]133;D;${code}\x07`, Date.now()) // Let the host's shell-alone answer land. await new Promise((resolve) => setImmediate(resolve)) From d4c32240de8e6df6c21eeb29f08ca59cff8a3cda Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:59:26 -0800 Subject: [PATCH 077/125] fix(sleep): prove the quit of an agent typed at the prompt, and keep proving when a row changes mid-proof - A command mark with no launch held now arms a pane whose live process-less identity no retirement armed (an agent typed at the prompt), so its /quit retires the record. - A row replaced while a proof runs may be the same conversation's; keep tracking instead of treating it as settled. --- src/main/agent-hooks/server/server-tab-cleanup.ts | 15 +++++++++------ .../agent-hooks/server/unproven-agent-exits.ts | 8 ++++++-- .../stop/worktree-sleep-resume-recording.test.ts | 7 ++++++- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 455e979bb58e..da31c7889cb3 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -29,15 +29,17 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } ): void { const resolved = this.resolvePaneKeyAlias(paneKey) - if (options?.launchRetired) { - this.unprovenExits.onCommandFinished(resolved) - return - } const identity = this.paneAgentIdentity(paneKey) const shared = identity?.processTopology === 'shared' // A command mark can come from a shell nested in a live agent; one with no process to probe // ends only on the host's word that the pane's shell is alone. - const unprovable = Boolean(identity) && !shared && !this.hasVerifiableAgentProcess(paneKey) + const unprovable = + identity?.ended === false && !shared && !this.hasVerifiableAgentProcess(paneKey) + if (options?.launchRetired) { + // An agent typed at the prompt holds no launch; its quit is proved the same way. + this.unprovenExits.onCommandFinished(resolved, unprovable) + return + } const awaitsHost = options?.confirmedExit === true && !this.hasVerifiableAgentProcess(paneKey) const confirmedExit = options?.confirmedExit === true && !awaitsHost const { paneKeys, authorityChanged } = this.revokeProcessAuthority(paneKey) @@ -62,8 +64,9 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { private async confirmCommandFinishedExit(resolved: string): Promise { const row = this.state.lastStatusByPaneKey.get(resolved) const alone = await this.terminalPaneLifecycle?.confirmShellAlone?.(resolved) + // A newer row may be the same conversation's; only a later proof can settle it. if (this.state.lastStatusByPaneKey.get(resolved) !== row) { - return true + return false } if (alone === false) { return false diff --git a/src/main/agent-hooks/server/unproven-agent-exits.ts b/src/main/agent-hooks/server/unproven-agent-exits.ts index 36234cbfb11b..065e22d74445 100644 --- a/src/main/agent-hooks/server/unproven-agent-exits.ts +++ b/src/main/agent-hooks/server/unproven-agent-exits.ts @@ -6,7 +6,7 @@ type UnprovenExit = { proving: boolean; again: boolean } export class UnprovenAgentExits { private readonly panes = new Map() - /** `prove` answers whether the pane is settled: its exit was confirmed, or a newer row owns it. */ + /** `prove` answers whether the pane is settled: its agent's exit was confirmed. */ constructor(private readonly prove: (paneKey: string) => Promise) {} /** A launch retired; `unseen`: its agent may still end unseen, `proveNow`: a mark said it ended. @@ -34,7 +34,11 @@ export class UnprovenAgentExits { } } - onCommandFinished(paneKey: string): void { + /** `unseen`: arm a pane no earlier retirement armed, whose agent may still end unseen. */ + onCommandFinished(paneKey: string, unseen = false): void { + if (unseen && !this.panes.has(paneKey)) { + this.panes.set(paneKey, { proving: false, again: false }) + } const entry = this.panes.get(paneKey) if (!entry || entry.proving) { if (entry) { diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 71f4419d3e11..cee8c88adc8f 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -243,7 +243,8 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini ['macOS suspended, then another command', ['146', '0'], true], ['macOS suspended, then a listing and another command', ['146', 'listing', '0'], true], ['suspended, resumed (fg), then quit', ['148', 'fg', '0'], false], - ['quit where the host gives no shell proof (remote, Windows)', ['unproven'], false] + ['quit where the host gives no shell proof (remote, Windows)', ['unproven'], false], + ['quit of an agent no Orca launch held (typed at the prompt)', ['typed'], false] ] as const)('%s', async (_, finishes, keepsRecovery) => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(1_000) @@ -336,6 +337,10 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini tick() if (status === 'unmarked') { await server.reconcilePaneProcessExit(PANE_KEY) + } else if (status === 'typed') { + // The runtime's notice for a mark that finds no launch held. + server.retireProcessAuthority(PANE_KEY, { confirmedExit: true, launchRetired: true }) + await new Promise((resolve) => setImmediate(resolve)) } else if (status === 'fg') { stopped = false } else if (status === 'listing') { From 7e603940a11178cfb69a8d120e13dc030c6afb9d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:02:44 -0800 Subject: [PATCH 078/125] perf(sleep): read an exit proof's root PID from its PTY alone, not every terminal The local provider builds rows only for the requested PTYs, and the proof's root lookup uses the daemon's targeted owner read; neither reads a PTY's absence as its end. --- .../ipc/pty/pane/terminal-pane-status-lifecycle.ts | 4 +++- src/main/providers/local-pty/local-pty-provider.ts | 3 +-- .../local-pty/local-pty-session-operations.ts | 10 ++++++++-- src/main/providers/pty/provider-contract.ts | 3 ++- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index b70e5da96041..cccf904725ac 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -159,7 +159,9 @@ async function readPtyRootPid( if (known) { return known } - const processes = await provider.listProcesses({ ptyIds: [ptyId] }).catch(() => []) + const processes = await provider + .listProcesses({ ptyIds: [ptyId], targetOwnerOnly: true }) + .catch(() => []) const rootPid = processes.find((entry) => entry.id === ptyId)?.rootProcessId if (rootPid) { if (rootPidByPtyIncarnation.size >= 64) { diff --git a/src/main/providers/local-pty/local-pty-provider.ts b/src/main/providers/local-pty/local-pty-provider.ts index 2631c5f058a1..1b76ea2bc489 100644 --- a/src/main/providers/local-pty/local-pty-provider.ts +++ b/src/main/providers/local-pty/local-pty-provider.ts @@ -226,8 +226,7 @@ export class LocalPtyProvider implements IPtyProvider { } async listProcesses(opts?: { ptyIds?: readonly string[] }): Promise { - const rows = await listLocalPtyProcesses() - return opts?.ptyIds ? rows.filter((row) => opts.ptyIds?.includes(row.id)) : rows + return listLocalPtyProcesses(opts?.ptyIds) } getDefaultShell(): Promise { diff --git a/src/main/providers/local-pty/local-pty-session-operations.ts b/src/main/providers/local-pty/local-pty-session-operations.ts index f586521d2a30..d4bb32c36fa2 100644 --- a/src/main/providers/local-pty/local-pty-session-operations.ts +++ b/src/main/providers/local-pty/local-pty-session-operations.ts @@ -124,8 +124,14 @@ export function closeLocalPtyStartupQueryAuthority(id: string): number { return startupIngressByPty.get(id)?.closeQueryAuthority() ?? 0 } -export async function listLocalPtyProcesses(): Promise { - return Array.from(ptyProcesses.entries()).map(([id, proc]) => ({ +export async function listLocalPtyProcesses(ptyIds?: readonly string[]): Promise { + const entries = ptyIds + ? ptyIds.flatMap((id) => { + const proc = ptyProcesses.get(id) + return proc ? [[id, proc] as const] : [] + }) + : Array.from(ptyProcesses.entries()) + return entries.map(([id, proc]) => ({ id, ...(ptyIncarnations.get(id) ? { incarnationId: ptyIncarnations.get(id) } : {}), ...(proc.pid > 0 ? { rootProcessId: proc.pid } : {}), diff --git a/src/main/providers/pty/provider-contract.ts b/src/main/providers/pty/provider-contract.ts index 695f68053f5c..a512012cb530 100644 --- a/src/main/providers/pty/provider-contract.ts +++ b/src/main/providers/pty/provider-contract.ts @@ -213,7 +213,8 @@ export type IPtyProvider = { worktreeId?: string /** Scope route validation to these PTYs; absence still requires a complete inventory. */ ptyIds?: readonly string[] - /** Foreground proof only: read `ptyIds` from their established owner. Never exit proof or a census. */ + /** Foreground proof and root-PID lookups only: read `ptyIds` from their established owner. + * Never a census or an exit proof that reads a PTY's absence as its end. */ targetOwnerOnly?: boolean /** Diagnostic display only: include generations whose routing owner is unverifiable. */ includeUnrouted?: boolean From 4297ba1c926fdee8aea1767bfcda67d749772fcb Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:12:53 -0800 Subject: [PATCH 079/125] fix(sleep): read hydrated sharedHost through a type guard; expect jobStopped in the authority spec --- src/main/agent-hooks/server/server-hydration.ts | 5 ++++- .../terminal-creation-and-readiness.spec.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/agent-hooks/server/server-hydration.ts b/src/main/agent-hooks/server/server-hydration.ts index 7aa46d1a6831..f9b2eb6dcba4 100644 --- a/src/main/agent-hooks/server/server-hydration.ts +++ b/src/main/agent-hooks/server/server-hydration.ts @@ -102,7 +102,10 @@ export abstract class AgentHookServerHydration extends AgentHookServerTabCleanup // The binding's topology is runtime metadata; a shared host still runs this conversation. if ( entry.providerSession && - (rawResolvedEntry as { sharedHost?: unknown } | null)?.sharedHost === true + typeof rawResolvedEntry === 'object' && + rawResolvedEntry !== null && + 'sharedHost' in rawResolvedEntry && + rawResolvedEntry.sharedHost === true ) { retainTmuxWriterTopology(entry.providerSession) } diff --git a/src/main/runtime/orchestration/terminal-authority/terminal-creation-and-readiness.spec.ts b/src/main/runtime/orchestration/terminal-authority/terminal-creation-and-readiness.spec.ts index dea2907fc516..6977c79f6d3c 100644 --- a/src/main/runtime/orchestration/terminal-authority/terminal-creation-and-readiness.spec.ts +++ b/src/main/runtime/orchestration/terminal-authority/terminal-creation-and-readiness.spec.ts @@ -79,7 +79,8 @@ describe('OrcaRuntimeService', () => { runtime.onPtyData('pty-authority', `\x1b]133;D;${status}\x07`, 100) expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { - confirmedExit: exited + confirmedExit: exited, + jobStopped: !exited }) expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull() expect((await runtime.listTerminals()).terminals).toEqual([ From eeb3729b92da589855c7525ef720b728527e887b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:17:20 -0800 Subject: [PATCH 080/125] perf(sleep): keep each live PTY's root PID until its teardown instead of a bounded cache An exit proof pays one inventory per PTY incarnation at most; cycling more PTYs than a cache held no longer re-reads the whole daemon session list. --- .../pane/terminal-pane-status-lifecycle.ts | 21 +++++++------------ src/main/ipc/pty/provider/ownership-state.ts | 2 ++ src/main/ipc/pty/provider/state-cleanup.ts | 8 ++++++- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index cccf904725ac..31e86f648b42 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -5,7 +5,7 @@ import { toSshExecutionHostId } from '../../../../shared/execution-host/executio import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import { paneKeyPtyId } from './key-state' -import { ptyIncarnationById } from '../provider/ownership-state' +import { ptyIncarnationById, ptyRootPidById } from '../provider/ownership-state' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { getProviderForPty } from '../provider/registry' import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' @@ -146,28 +146,23 @@ async function paneShellAlone( * table instead, local or daemon alike. Windows shells stop no jobs, so the host's job census * finding no child beside a shell foreground suffices there. Never fall back to a foreground * name, which a live unrecognized agent shares. */ -// A PTY keeps its root process for its incarnation, so repeated proofs skip the inventory. -const rootPidByPtyIncarnation = new Map() - +// A PTY keeps its root process for its incarnation, so it pays at most one inventory per life. async function readPtyRootPid( provider: ReturnType, ptyId: string, incarnationId: string | undefined ): Promise { - const key = `${ptyId}\0${incarnationId ?? ''}` - const known = rootPidByPtyIncarnation.get(key) - if (known) { - return known + const known = ptyRootPidById.get(ptyId) + if (known && known.incarnationId === incarnationId) { + return known.rootPid } const processes = await provider .listProcesses({ ptyIds: [ptyId], targetOwnerOnly: true }) .catch(() => []) const rootPid = processes.find((entry) => entry.id === ptyId)?.rootProcessId - if (rootPid) { - if (rootPidByPtyIncarnation.size >= 64) { - rootPidByPtyIncarnation.delete(rootPidByPtyIncarnation.keys().next().value!) - } - rootPidByPtyIncarnation.set(key, rootPid) + // Only a live incarnation main still tracks is cached; the PTY's teardown drops it. + if (rootPid && incarnationId && ptyIncarnationById.get(ptyId) === incarnationId) { + ptyRootPidById.set(ptyId, { incarnationId, rootPid }) } return rootPid } diff --git a/src/main/ipc/pty/provider/ownership-state.ts b/src/main/ipc/pty/provider/ownership-state.ts index f2cd9fcdb350..c0c7cff13e06 100644 --- a/src/main/ipc/pty/provider/ownership-state.ts +++ b/src/main/ipc/pty/provider/ownership-state.ts @@ -8,6 +8,8 @@ import { // Later write/resize/kill requests carry only PTY ID; preserve its execution host for routing. export const ptyOwnership = new Map() export const ptyIncarnationById = new Map() +/** Exit proofs' root process per live PTY incarnation; teardown drops it with the PTY. */ +export const ptyRootPidById = new Map() export function isCurrentPtyExit(payload: { id: string; incarnationId?: string }): boolean { const current = ptyIncarnationById.get(payload.id) diff --git a/src/main/ipc/pty/provider/state-cleanup.ts b/src/main/ipc/pty/provider/state-cleanup.ts index 71374e4e2bbb..9ae8e7840134 100644 --- a/src/main/ipc/pty/provider/state-cleanup.ts +++ b/src/main/ipc/pty/provider/state-cleanup.ts @@ -12,7 +12,12 @@ import { } from '../delivery/pty-hidden-delivery-gate' import { agentSessionOwners } from '../pane/agent-session-owners' import { paneKeyPtyId, paneKeyTeardownListeners, ptyPaneKey } from '../pane/key-state' -import { getPtyIdsForConnection, ptyIncarnationById, ptyOwnership } from './ownership-state' +import { + getPtyIdsForConnection, + ptyIncarnationById, + ptyOwnership, + ptyRootPidById +} from './ownership-state' import { clearBackgroundedDeliverySyncForPty } from './listener-lifecycle' import { activeRendererPtys, @@ -56,6 +61,7 @@ export function clearProviderPtyState( piTitlebarExtensionService.clearPty(id) ptySizes.delete(id) ptyIncarnationById.delete(id) + ptyRootPidById.delete(id) lastInputAtByPty.delete(id) interactiveOutputCharsByPty.delete(id) const activeChanged = activeRendererPtys.delete(id) From 138d13f4ac93d70bccbafec21760d42af8968b98 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:23:50 -0800 Subject: [PATCH 081/125] fix(sleep): only the pane's own stopped agent keeps its exit unproven Another agent suspended earlier in the same shell no longer blocks the proof, so quitting the agent after it still retires its record. --- src/main/agent-hooks/server/server-state.ts | 2 +- .../agent-hooks/server/server-tab-cleanup.ts | 3 ++- .../terminal-pane-status-lifecycle.test.ts | 2 +- .../pane/terminal-pane-status-lifecycle.ts | 20 +++++++++++++------ .../run-terminal-shell-alone.test.ts | 12 +++++++++-- .../lifecycle/run-terminal-shell-alone.ts | 11 ++++++---- 6 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index dc8ec491ce6d..4d8d7efddc88 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -56,7 +56,7 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract confirmProcessExit?(paneKey: string, agent: string): Promise /** The host's word that the pane's shell holds its PTY alone, whatever launch it ran; null * where the host gives none (remote, Windows), so a command mark stands as on main. */ - confirmShellAlone?(paneKey: string): Promise + confirmShellAlone?(paneKey: string, agent?: string): Promise ownsProcess(paneKey: string, ptyId: string, incarnationId?: string): boolean isStopping(paneKey: string): boolean isReversibleStop(ptyId: string, incarnationId?: string): boolean diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index da31c7889cb3..1a50dd54355c 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -63,7 +63,8 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { private async confirmCommandFinishedExit(resolved: string): Promise { const row = this.state.lastStatusByPaneKey.get(resolved) - const alone = await this.terminalPaneLifecycle?.confirmShellAlone?.(resolved) + const agent = this.paneAgentIdentity(resolved)?.status.agentType + const alone = await this.terminalPaneLifecycle?.confirmShellAlone?.(resolved, agent) // A newer row may be the same conversation's; only a later proof can settle it. if (this.state.lastStatusByPaneKey.get(resolved) !== row) { return false diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index df20d4e94a62..b25e4021b381 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -14,7 +14,7 @@ vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ vi.mock('../provider/registry', () => ({ getProviderForPty })) vi.mock('../../../runtime/terminal/lifecycle/run-terminal-shell-alone', () => ({ confirmRootShellAloneFromProcessTable: confirmRootShellAlone, - isStoppedAgent: () => true + stoppedAgentBlocks: () => () => true })) const platform = process.platform diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 31e86f648b42..a34e6cfb8a22 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -13,7 +13,7 @@ import { isShellProcess } from '../../../../shared/agent-status/process/shell-pr import { isRemoteExecutionHostPtyId } from '../../../../shared/execution-host/remote-execution-host-pty-id' import { confirmRootShellAloneFromProcessTable, - isStoppedAgent + stoppedAgentBlocks } from '../../../runtime/terminal/lifecycle/run-terminal-shell-alone' export function bindTerminalPaneStatusLifecycle( @@ -31,6 +31,7 @@ export function bindTerminalPaneStatusLifecycle( (await paneShellAlone( runtime, paneKey, + agent, () => runtime?.getLaunchStatementForPaneKey(paneKey, agent) === launch )) === true ) @@ -39,8 +40,8 @@ export function bindTerminalPaneStatusLifecycle( } }, // Windows gives a command mark no proof against a nested shell, so the mark stands, as on main. - confirmShellAlone: async (paneKey) => - process.platform === 'win32' ? null : paneShellAlone(runtime, paneKey), + confirmShellAlone: async (paneKey, agent) => + process.platform === 'win32' ? null : paneShellAlone(runtime, paneKey, agent), readSavedRecord: (paneKey) => { try { const worktreeId = runtime?.getTerminalWorktreeIdForPaneKey(paneKey) @@ -115,6 +116,7 @@ export function bindTerminalPaneStatusLifecycle( async function paneShellAlone( runtime: OrcaRuntimeService | undefined, paneKey: string, + agent: string | undefined, stillCurrent: () => boolean = () => true ): Promise { if (!runtime) { @@ -128,7 +130,7 @@ async function paneShellAlone( if (isRemoteExecutionHostPtyId(pane.ptyId)) { return null } - const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined) + const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined, agent) const current = runtime.resolveTerminalPane(paneKey) return ( shellAlone && @@ -167,12 +169,18 @@ async function readPtyRootPid( return rootPid } -async function confirmShellAlone(ptyId: string, incarnationId?: string): Promise { +async function confirmShellAlone( + ptyId: string, + incarnationId?: string, + agent?: string +): Promise { const provider = getProviderForPty(ptyId) if (process.platform !== 'win32') { const rootPid = await readPtyRootPid(provider, ptyId, incarnationId) return rootPid - ? confirmRootShellAloneFromProcessTable(rootPid, { stoppedJobBlocks: isStoppedAgent }) + ? confirmRootShellAloneFromProcessTable(rootPid, { + stoppedJobBlocks: stoppedAgentBlocks(agent) + }) : false } if ((await provider.confirmShellForeground?.(ptyId)) === true) { diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts index e8f161e7e6c6..9026252aecdd 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts @@ -10,7 +10,7 @@ vi.mock( }) ) -const { confirmRootShellAloneFromProcessTable, isStoppedAgent } = +const { confirmRootShellAloneFromProcessTable, stoppedAgentBlocks } = await import('./run-terminal-shell-alone') const SHELL: ProcessTableRow = { pid: 100, ppid: 1, stat: 'Ss+', command: '/bin/zsh' } @@ -39,10 +39,18 @@ it.skipIf(process.platform === 'win32').each([ 90, [LOGIN, LOGIN_SHELL, { pid: 102, ppid: 100, stat: 'T', command: 'vim notes.md' }], true + ], + [ + 'a login root, another agent suspended before this one ran', + 90, + [LOGIN, LOGIN_SHELL, { pid: 103, ppid: 100, stat: 'T', command: 'claude' }], + true ] ] as const)('confirms the shell alone from %s', async (_, rootPid, rows, expected) => { snapshot.mockResolvedValue([...rows]) expect( - await confirmRootShellAloneFromProcessTable(rootPid, { stoppedJobBlocks: isStoppedAgent }) + await confirmRootShellAloneFromProcessTable(rootPid, { + stoppedJobBlocks: stoppedAgentBlocks('codex') + }) ).toBe(expected) }) diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts index 540d324c21ca..af11428daa3b 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts @@ -13,10 +13,13 @@ import { recognizeAgentProcessFromCommandLine } from '../../../../shared/agent-s import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import type { TerminalProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' -/** Only a stopped agent keeps an agent's exit unproven; a stopped editor from before its launch - * does not. */ -export function isStoppedAgent(row: { command: string }): boolean { - return recognizeAgentProcessFromCommandLine(row.command) !== null +/** Only a stopped job running the pane's agent (any agent when unknown) keeps its exit unproven; + * a stopped editor or another agent suspended before it does not. */ +export function stoppedAgentBlocks(agent?: string): (row: { command: string }) => boolean { + return (row) => { + const recognized = recognizeAgentProcessFromCommandLine(row.command) + return recognized !== null && (!agent || recognized.agent === agent) + } } /** POSIX: the PTY's shell owns the terminal's foreground group and nothing under it is stopped. */ From f954dfacd32b65d1cc056f5ef2e411ddb784611d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:28:22 -0800 Subject: [PATCH 082/125] perf(sleep): take an exit proof's root PID from the PID its PTY published at spawn Main already keeps each local PTY's spawn PID; only a host that published none falls back to the targeted inventory, so proofs no longer move the daemon's session list. --- .../pane/terminal-pane-status-lifecycle.ts | 23 ++++++++----------- src/main/ipc/pty/provider/ownership-state.ts | 2 -- src/main/ipc/pty/provider/state-cleanup.ts | 8 +------ src/main/memory/pty-registry.ts | 5 ++++ 4 files changed, 15 insertions(+), 23 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index a34e6cfb8a22..7964ba69cd8c 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -5,7 +5,8 @@ import { toSshExecutionHostId } from '../../../../shared/execution-host/executio import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import { paneKeyPtyId } from './key-state' -import { ptyIncarnationById, ptyRootPidById } from '../provider/ownership-state' +import { ptyIncarnationById } from '../provider/ownership-state' +import { getRegisteredPtyPid } from '../../../memory/pty-registry' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { getProviderForPty } from '../provider/registry' import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' @@ -148,25 +149,19 @@ async function paneShellAlone( * table instead, local or daemon alike. Windows shells stop no jobs, so the host's job census * finding no child beside a shell foreground suffices there. Never fall back to a foreground * name, which a live unrecognized agent shares. */ -// A PTY keeps its root process for its incarnation, so it pays at most one inventory per life. +// Spawn and adoption publish the shell PID; only a host that published none needs the inventory. async function readPtyRootPid( provider: ReturnType, - ptyId: string, - incarnationId: string | undefined + ptyId: string ): Promise { - const known = ptyRootPidById.get(ptyId) - if (known && known.incarnationId === incarnationId) { - return known.rootPid + const registered = getRegisteredPtyPid(ptyId) + if (registered) { + return registered } const processes = await provider .listProcesses({ ptyIds: [ptyId], targetOwnerOnly: true }) .catch(() => []) - const rootPid = processes.find((entry) => entry.id === ptyId)?.rootProcessId - // Only a live incarnation main still tracks is cached; the PTY's teardown drops it. - if (rootPid && incarnationId && ptyIncarnationById.get(ptyId) === incarnationId) { - ptyRootPidById.set(ptyId, { incarnationId, rootPid }) - } - return rootPid + return processes.find((entry) => entry.id === ptyId)?.rootProcessId } async function confirmShellAlone( @@ -176,7 +171,7 @@ async function confirmShellAlone( ): Promise { const provider = getProviderForPty(ptyId) if (process.platform !== 'win32') { - const rootPid = await readPtyRootPid(provider, ptyId, incarnationId) + const rootPid = await readPtyRootPid(provider, ptyId) return rootPid ? confirmRootShellAloneFromProcessTable(rootPid, { stoppedJobBlocks: stoppedAgentBlocks(agent) diff --git a/src/main/ipc/pty/provider/ownership-state.ts b/src/main/ipc/pty/provider/ownership-state.ts index c0c7cff13e06..f2cd9fcdb350 100644 --- a/src/main/ipc/pty/provider/ownership-state.ts +++ b/src/main/ipc/pty/provider/ownership-state.ts @@ -8,8 +8,6 @@ import { // Later write/resize/kill requests carry only PTY ID; preserve its execution host for routing. export const ptyOwnership = new Map() export const ptyIncarnationById = new Map() -/** Exit proofs' root process per live PTY incarnation; teardown drops it with the PTY. */ -export const ptyRootPidById = new Map() export function isCurrentPtyExit(payload: { id: string; incarnationId?: string }): boolean { const current = ptyIncarnationById.get(payload.id) diff --git a/src/main/ipc/pty/provider/state-cleanup.ts b/src/main/ipc/pty/provider/state-cleanup.ts index 9ae8e7840134..71374e4e2bbb 100644 --- a/src/main/ipc/pty/provider/state-cleanup.ts +++ b/src/main/ipc/pty/provider/state-cleanup.ts @@ -12,12 +12,7 @@ import { } from '../delivery/pty-hidden-delivery-gate' import { agentSessionOwners } from '../pane/agent-session-owners' import { paneKeyPtyId, paneKeyTeardownListeners, ptyPaneKey } from '../pane/key-state' -import { - getPtyIdsForConnection, - ptyIncarnationById, - ptyOwnership, - ptyRootPidById -} from './ownership-state' +import { getPtyIdsForConnection, ptyIncarnationById, ptyOwnership } from './ownership-state' import { clearBackgroundedDeliverySyncForPty } from './listener-lifecycle' import { activeRendererPtys, @@ -61,7 +56,6 @@ export function clearProviderPtyState( piTitlebarExtensionService.clearPty(id) ptySizes.delete(id) ptyIncarnationById.delete(id) - ptyRootPidById.delete(id) lastInputAtByPty.delete(id) interactiveOutputCharsByPty.delete(id) const activeChanged = activeRendererPtys.delete(id) diff --git a/src/main/memory/pty-registry.ts b/src/main/memory/pty-registry.ts index 997ffe520d30..468fb41317e8 100644 --- a/src/main/memory/pty-registry.ts +++ b/src/main/memory/pty-registry.ts @@ -27,6 +27,11 @@ export function unregisterPty(ptyId: string): void { } } +/** The shell PID a PTY published at spawn or adoption; null when its host published none. */ +export function getRegisteredPtyPid(ptyId: string): number | null { + return registry.get(ptyId)?.pid ?? null +} + export function hasRegisteredPtyWithPid(): boolean { return registeredWithPid > 0 } From 1948bb6708733d6c524bba8ae04f77a15d0d5a37 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:38:43 -0800 Subject: [PATCH 083/125] fix(sleep): a proof doesn't count once input reached the PTY, and launchless marks read only indexed pane keys - Typing (say `codex resume `) while a shell-alone proof runs voids that proof; the next mark proves again. - A command mark with no launch held reads the PTY's recorded pane key and its indexed leaves, never a main-owned layout's pane search. --- .../terminal-pane-status-lifecycle.test.ts | 27 ++++++++++++++++ .../pane/terminal-pane-status-lifecycle.ts | 4 +++ .../terminal/lifecycle/daemon-launch-note.ts | 32 ++++++++++++++++++- .../terminal-orchestration-authority.ts | 7 ++-- 4 files changed, 65 insertions(+), 5 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index b25e4021b381..2d388f79764b 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -130,3 +130,30 @@ it.each([ ).toBe(expected) } ) + +it('does not count a shell-alone proof once input reached the PTY while it ran', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin' }) + const { lastInputAtByPty } = await import('../delivery/visibility-state') + let typed = false + // The user types `codex resume ` after the table was read but before the proof returns. + confirmRootShellAlone.mockImplementation(async () => { + if (typed) { + lastInputAtByPty.set('pty-1', performance.now()) + } + return true + }) + getProviderForPty.mockReturnValue({ + listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }] + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the proof only resolves the pane. + const runtime = { + resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }) + } as unknown as OrcaRuntimeService + bindTerminalPaneStatusLifecycle(runtime, undefined) + const lifecycle = setTerminalPaneLifecycle.mock.lastCall![0] + const paneKey = 'tab:11111111-1111-4111-8111-111111111111' + expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(true) + typed = true + expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(false) + lastInputAtByPty.delete('pty-1') +}) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 7964ba69cd8c..0b43bdf5a439 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -7,6 +7,7 @@ import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-top import { paneKeyPtyId } from './key-state' import { ptyIncarnationById } from '../provider/ownership-state' import { getRegisteredPtyPid } from '../../../memory/pty-registry' +import { lastInputAtByPty } from '../delivery/visibility-state' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { getProviderForPty } from '../provider/registry' import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' @@ -131,10 +132,13 @@ async function paneShellAlone( if (isRemoteExecutionHostPtyId(pane.ptyId)) { return null } + // Input during the proof may start the next agent (`codex resume`) after the table was read. + const inputBefore = lastInputAtByPty.get(pane.ptyId) const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined, agent) const current = runtime.resolveTerminalPane(paneKey) return ( shellAlone && + lastInputAtByPty.get(pane.ptyId) === inputBefore && current.ptyId === pane.ptyId && current.incarnationId === pane.incarnationId && stillCurrent() diff --git a/src/main/runtime/terminal/lifecycle/daemon-launch-note.ts b/src/main/runtime/terminal/lifecycle/daemon-launch-note.ts index 59d596a43792..65317f1c7149 100644 --- a/src/main/runtime/terminal/lifecycle/daemon-launch-note.ts +++ b/src/main/runtime/terminal/lifecycle/daemon-launch-note.ts @@ -2,7 +2,16 @@ import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent import type { PtyIncarnationId } from '../../../../shared/terminal/pty/lifecycle/pty-incarnation' import type { DaemonLaunchNote } from '../../../daemon/protocol/daemon-launch-note-protocol' import type { LaunchedAgentForeground } from '../wait/launched-agent-foreground' -import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' +import type { + RuntimeLeafRecord, + RuntimePtyWorktreeRecord +} from '../records/runtime-terminal-state-records' +import { + isTerminalLeafId, + makePaneKey, + parsePaneKey +} from '../../../../shared/workspace-layout/stable-pane-id' +import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { holdLaunch, recordReattachedLaunch, @@ -36,6 +45,27 @@ export abstract class OrcaRuntimeWithDaemonLaunchNote extends OrcaRuntimeWithInv } } + protected abstract getLeavesForPty(ptyId: string): readonly RuntimeLeafRecord[] + + /** A command finished with no launch held; an earlier mark (a nested shell's) or an agent typed + * at the prompt may have left an agent's exit unproven. Runs per mark, so indexed reads only. */ + protected noticeLaunchlessCommandMark(ptyId: string, confirmedExit: boolean | undefined): void { + const pty = this.ptysById.get(ptyId) + if (!pty || !confirmedExit) { + return + } + const recorded = pty.paneKey + const paneKeys = new Set(recorded && parsePaneKey(recorded) ? [recorded] : []) + for (const leaf of this.getLeavesForPty(ptyId)) { + if (isValidTerminalTabId(leaf.tabId) && isTerminalLeafId(leaf.leafId)) { + paneKeys.add(makePaneKey(leaf.tabId, leaf.leafId)) + } + } + for (const paneKey of paneKeys) { + this.retireAgentHookCompatibilityAuthorityFn?.(paneKey, { launchRetired: true }) + } + } + /** A finished command or confirmed exit; the daemon outlives main, so a reattach must not re-arm it. */ protected retireHeldLaunch(ptyId: string): RuntimePtyWorktreeRecord | undefined { const pty = this.ptysById.get(ptyId) diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 3146809cbffd..04d7c26f9c30 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -186,13 +186,12 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O const pty = this.retireHeldLaunch(ptyId) const receipt = this.restoredOrchestrationAuthorityByPtyId.get(ptyId) const launch = pty && (pty.launchToken || pty.launchAgent || pty.launchCommandAgent) - // With nothing held, an earlier mark (maybe a nested shell's) retired the launch this one ends. - if (!pty || (!launch && !receipt && !confirmedExit)) { + if (!pty || (!launch && !receipt)) { + this.noticeLaunchlessCommandMark(ptyId, confirmedExit) return } const exited = confirmedExit === true && Boolean(launch || (receipt && !finishedBefore)) - const ended = { confirmedExit: exited, jobStopped: confirmedExit === false } - const retirement = launch || receipt ? ended : { launchRetired: true as const } + const retirement = { confirmedExit: exited, jobStopped: confirmedExit === false } // Why: collect before the delete below, which drops the restored-authority receipt a // receipt-only pane's key comes from. const paneKeys = this.collectPaneKeysForPty(ptyId) From dcd0c2facc1e808aebaf44e10f5a491908952a6e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:43:04 -0800 Subject: [PATCH 084/125] perf(sleep): a PTY whose host published no PID pays one root inventory per incarnation The answer, a root or none, lasts until the PTY's teardown, so repeated proofs on such a PTY don't re-read the daemon's sessions. --- .../pane/terminal-pane-status-lifecycle.ts | 22 ++++++++++++++----- src/main/ipc/pty/provider/ownership-state.ts | 6 +++++ src/main/ipc/pty/provider/state-cleanup.ts | 8 ++++++- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 0b43bdf5a439..5da6c44c9389 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -5,7 +5,7 @@ import { toSshExecutionHostId } from '../../../../shared/execution-host/executio import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import { paneKeyPtyId } from './key-state' -import { ptyIncarnationById } from '../provider/ownership-state' +import { ptyFallbackRootPidById, ptyIncarnationById } from '../provider/ownership-state' import { getRegisteredPtyPid } from '../../../memory/pty-registry' import { lastInputAtByPty } from '../delivery/visibility-state' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' @@ -153,19 +153,29 @@ async function paneShellAlone( * table instead, local or daemon alike. Windows shells stop no jobs, so the host's job census * finding no child beside a shell foreground suffices there. Never fall back to a foreground * name, which a live unrecognized agent shares. */ -// Spawn and adoption publish the shell PID; only a host that published none needs the inventory. +// Spawn and adoption publish the shell PID; a host that published none pays one targeted +// inventory per PTY incarnation, whose answer (a root or none) lasts until the PTY's teardown. async function readPtyRootPid( provider: ReturnType, - ptyId: string + ptyId: string, + incarnationId: string | undefined ): Promise { const registered = getRegisteredPtyPid(ptyId) if (registered) { return registered } + const known = ptyFallbackRootPidById.get(ptyId) + if (known && known.incarnationId === incarnationId) { + return known.rootPid ?? undefined + } const processes = await provider .listProcesses({ ptyIds: [ptyId], targetOwnerOnly: true }) - .catch(() => []) - return processes.find((entry) => entry.id === ptyId)?.rootProcessId + .catch(() => null) + const rootPid = processes?.find((entry) => entry.id === ptyId)?.rootProcessId + if (processes && incarnationId && ptyIncarnationById.get(ptyId) === incarnationId) { + ptyFallbackRootPidById.set(ptyId, { incarnationId, rootPid: rootPid ?? null }) + } + return rootPid } async function confirmShellAlone( @@ -175,7 +185,7 @@ async function confirmShellAlone( ): Promise { const provider = getProviderForPty(ptyId) if (process.platform !== 'win32') { - const rootPid = await readPtyRootPid(provider, ptyId) + const rootPid = await readPtyRootPid(provider, ptyId, incarnationId) return rootPid ? confirmRootShellAloneFromProcessTable(rootPid, { stoppedJobBlocks: stoppedAgentBlocks(agent) diff --git a/src/main/ipc/pty/provider/ownership-state.ts b/src/main/ipc/pty/provider/ownership-state.ts index f2cd9fcdb350..505c1270bb16 100644 --- a/src/main/ipc/pty/provider/ownership-state.ts +++ b/src/main/ipc/pty/provider/ownership-state.ts @@ -8,6 +8,12 @@ import { // Later write/resize/kill requests carry only PTY ID; preserve its execution host for routing. export const ptyOwnership = new Map() export const ptyIncarnationById = new Map() +/** Exit proofs' root process for a live PTY incarnation whose host published no PID; null when + * its inventory had none. Teardown drops it with the PTY. */ +export const ptyFallbackRootPidById = new Map< + string, + { incarnationId: string; rootPid: number | null } +>() export function isCurrentPtyExit(payload: { id: string; incarnationId?: string }): boolean { const current = ptyIncarnationById.get(payload.id) diff --git a/src/main/ipc/pty/provider/state-cleanup.ts b/src/main/ipc/pty/provider/state-cleanup.ts index 71374e4e2bbb..89e2348d87ed 100644 --- a/src/main/ipc/pty/provider/state-cleanup.ts +++ b/src/main/ipc/pty/provider/state-cleanup.ts @@ -12,7 +12,12 @@ import { } from '../delivery/pty-hidden-delivery-gate' import { agentSessionOwners } from '../pane/agent-session-owners' import { paneKeyPtyId, paneKeyTeardownListeners, ptyPaneKey } from '../pane/key-state' -import { getPtyIdsForConnection, ptyIncarnationById, ptyOwnership } from './ownership-state' +import { + getPtyIdsForConnection, + ptyFallbackRootPidById, + ptyIncarnationById, + ptyOwnership +} from './ownership-state' import { clearBackgroundedDeliverySyncForPty } from './listener-lifecycle' import { activeRendererPtys, @@ -56,6 +61,7 @@ export function clearProviderPtyState( piTitlebarExtensionService.clearPty(id) ptySizes.delete(id) ptyIncarnationById.delete(id) + ptyFallbackRootPidById.delete(id) lastInputAtByPty.delete(id) interactiveOutputCharsByPty.delete(id) const activeChanged = activeRendererPtys.delete(id) From b8d1fc5bcf6dedfdff72e2726f7a0f43999818ae Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:50:23 -0800 Subject: [PATCH 085/125] refactor(sleep): a command mark asks the host whether the agent ended, whatever its exit status Drop the 145..150 'job stopped' reading of OSC 133;D statuses. Every mark now starts the existing proof: a process-less agent's shell-alone check refuses a stopped (Ctrl-Z) agent and confirms a real exit at once; an agent with a local process keeps its identity for its presence probe to decide. Hosts with no proof (remote, Windows) keep main's rule that the mark ends it. --- .../agent-hooks/server/server-tab-cleanup.ts | 23 ++-- .../runtime-construction-dependencies.ts | 2 +- .../terminal-creation-and-readiness.spec.ts | 115 ++++++++---------- .../terminal-orchestration-authority.ts | 6 +- .../terminal/output/terminal-title-tracker.ts | 3 +- .../output/terminal-transient-facts.ts | 3 +- .../worktree-sleep-resume-recording.test.ts | 9 +- .../agent-identity/pane-agent-identity.ts | 8 +- .../terminal-osc133-command-finished.ts | 8 -- 9 files changed, 80 insertions(+), 97 deletions(-) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 1a50dd54355c..fad5b4271fef 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -13,6 +13,7 @@ import type { RefusedPaneResume } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import { UnprovenAgentExits } from './unproven-agent-exits' +import { isLocalHookConnectionId } from '../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { @@ -23,34 +24,34 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { retireProcessAuthority( paneKey: string, - options?: Pick & { - jobStopped?: boolean - launchRetired?: true - } + options?: Pick & { launchRetired?: true } ): void { const resolved = this.resolvePaneKeyAlias(paneKey) const identity = this.paneAgentIdentity(paneKey) const shared = identity?.processTopology === 'shared' // A command mark can come from a shell nested in a live agent; one with no process to probe // ends only on the host's word that the pane's shell is alone. - const unprovable = - identity?.ended === false && !shared && !this.hasVerifiableAgentProcess(paneKey) + const verifiable = this.hasVerifiableAgentProcess(paneKey) + const unprovable = identity?.ended === false && !shared && !verifiable if (options?.launchRetired) { // An agent typed at the prompt holds no launch; its quit is proved the same way. this.unprovenExits.onCommandFinished(resolved, unprovable) return } - const awaitsHost = options?.confirmedExit === true && !this.hasVerifiableAgentProcess(paneKey) - const confirmedExit = options?.confirmedExit === true && !awaitsHost + // A mark's exit status can't tell a quit from a stop (Ctrl-Z). A local process answers through + // its presence probe, a stopped one included; a remote one can't be probed, so its mark stands. + const awaitsHost = options?.confirmedExit === true && !verifiable + const connectionId = this.state.lastStatusByPaneKey.get(resolved)?.connectionId ?? null + const confirmedExit = + options?.confirmedExit === true && verifiable && !isLocalHookConnectionId(connectionId) const { paneKeys, authorityChanged } = this.revokeProcessAuthority(paneKey) const { untouched } = this.reconcileEndedProcess( paneKeys, { confirmedExit, preserveResumeIdentity: !confirmedExit && !shared }, (key) => this.clearRevokedPaneState(key) ) - // A stopped job (Ctrl-Z) may later resume and quit at a mark that finds no launch left. - const unseen = unprovable && (awaitsHost || options?.jobStopped === true) - this.unprovenExits.launchRetired(resolved, unseen, awaitsHost) + // A stopped agent (Ctrl-Z) refuses the proof, and a later mark proves its quit. + this.unprovenExits.launchRetired(resolved, unprovable && awaitsHost, awaitsHost) for (const key of untouched) { this.clearTmuxInnerSubjects(key) this.clearPaneProcessState(key) diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 21ba14a7a791..36d816e3a814 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -74,7 +74,7 @@ export type RuntimeConstructionDependencies = { /** `launchRetired`: a command finished after an earlier mark already retired the launch. */ retireAgentHookCompatibilityAuthority?: ( paneKey: string, - options?: { confirmedExit?: boolean; jobStopped?: boolean; launchRetired?: true } + options?: { confirmedExit?: boolean; launchRetired?: true } ) => void readHookCliWriterObservation?: (row: AgentStatusIpcPayload) => CliWriterObservation | null /** `exitedSince`: also answer `exited` for an exit the hook store proved at or after it. */ diff --git a/src/main/runtime/orchestration/terminal-authority/terminal-creation-and-readiness.spec.ts b/src/main/runtime/orchestration/terminal-authority/terminal-creation-and-readiness.spec.ts index 6977c79f6d3c..f18d42a86bc5 100644 --- a/src/main/runtime/orchestration/terminal-authority/terminal-creation-and-readiness.spec.ts +++ b/src/main/runtime/orchestration/terminal-authority/terminal-creation-and-readiness.spec.ts @@ -22,72 +22,63 @@ import { spawnedPtyEnv } from '../../terminal/launch/spawned-pty-env-fixtures' import '../../../../shared/agent-launch/startup/jcode-runtime-dir' describe('OrcaRuntimeService', () => { - it.each([ - ['exits', 0, true], - ['is suspended', 148, false] - ] as const)( - 'retires inherited launch authority when the agent command %s', - async (_, status, exited) => { - const spawn = vi.fn().mockResolvedValue({ id: 'pty-authority', incarnationId: 'process-1' }) - const retireAuthority = vi.fn() - const runtime = new OrcaRuntimeService(store, undefined, { - attestAgentHookCompatibilityAuthority: (candidate) => ({ - paneKey: candidate.paneKey, - source: 'current_hook' - }), - retireAgentHookCompatibilityAuthority: retireAuthority - }) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession: vi.fn().mockResolvedValue({ tabId: 'tab-authority' }), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + it('retires inherited launch authority when the agent command exits', async () => { + const spawn = vi.fn().mockResolvedValue({ id: 'pty-authority', incarnationId: 'process-1' }) + const retireAuthority = vi.fn() + const runtime = new OrcaRuntimeService(store, undefined, { + attestAgentHookCompatibilityAuthority: (candidate) => ({ + paneKey: candidate.paneKey, + source: 'current_hook' + }), + retireAgentHookCompatibilityAuthority: retireAuthority + }) + runtime.setPtyController({ + spawn: committingSpawn(runtime, spawn), + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + runtime.setNotifier({ + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession: vi.fn().mockResolvedValue({ tabId: 'tab-authority' }), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + focusTerminal: vi.fn(), + closeTerminal: vi.fn(), + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + runtime.attachWindow(1) + await runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const terminal = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'codex', - launchAgent: 'codex', - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} } - }) - const spawnEnv = spawnedPtyEnv(spawn.mock.calls[0]?.[0]) - const evidence = { - terminalHandle: terminal.handle, - paneKey: spawnEnv.ORCA_PANE_KEY, - launchToken: spawnEnv.ORCA_AGENT_LAUNCH_TOKEN - } + const terminal = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { + command: 'codex', + launchAgent: 'codex', + launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} } + }) + const spawnEnv = spawnedPtyEnv(spawn.mock.calls[0]?.[0]) + const evidence = { + terminalHandle: terminal.handle, + paneKey: spawnEnv.ORCA_PANE_KEY, + launchToken: spawnEnv.ORCA_AGENT_LAUNCH_TOKEN + } - expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).not.toBeNull() - expect((await runtime.listTerminals()).terminals).toEqual([ - expect.objectContaining({ handle: terminal.handle, agentIdentity: 'codex' }) - ]) + expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).not.toBeNull() + expect((await runtime.listTerminals()).terminals).toEqual([ + expect.objectContaining({ handle: terminal.handle, agentIdentity: 'codex' }) + ]) - runtime.onPtyData('pty-authority', `\x1b]133;D;${status}\x07`, 100) + runtime.onPtyData('pty-authority', '\x1b]133;D;0\x07', 100) - expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { - confirmedExit: exited, - jobStopped: !exited - }) - expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull() - expect((await runtime.listTerminals()).terminals).toEqual([ - expect.not.objectContaining({ agentIdentity: expect.anything() }) - ]) - } - ) + expect(retireAuthority).toHaveBeenCalledWith(spawnEnv.ORCA_PANE_KEY, { confirmedExit: true }) + expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull() + expect((await runtime.listTerminals()).terminals).toEqual([ + expect.not.objectContaining({ agentIdentity: expect.anything() }) + ]) + }) it('restores a retained coordinator handle after a late controller inventory', async () => { const paneKey = makePaneKey('host-tab', HEADLESS_LEAF_ID) diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 04d7c26f9c30..7fd7ba34cfb1 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -179,8 +179,8 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O } } - /** `confirmedExit`: a command mark said the launched command finished (true) or stopped as a - * job (false); undefined when no mark retires the launch (the PTY exited). */ + /** `confirmedExit`: a command mark finished the launched command (whether its agent quit or + * stopped is the host's proof to tell); undefined when the PTY exited. */ protected retirePtyAgentLaunchAuthority(ptyId: string, confirmedExit?: boolean): void { const finishedBefore = this.ptysById.get(ptyId)?.launchEvidence?.kind === 'gone' const pty = this.retireHeldLaunch(ptyId) @@ -191,7 +191,7 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O return } const exited = confirmedExit === true && Boolean(launch || (receipt && !finishedBefore)) - const retirement = { confirmedExit: exited, jobStopped: confirmedExit === false } + const retirement = { confirmedExit: exited } // Why: collect before the delete below, which drops the restored-authority receipt a // receipt-only pane's key comes from. const paneKeys = this.collectPaneKeysForPty(ptyId) diff --git a/src/main/runtime/terminal/output/terminal-title-tracker.ts b/src/main/runtime/terminal/output/terminal-title-tracker.ts index 9691888a29f3..898563930dd4 100644 --- a/src/main/runtime/terminal/output/terminal-title-tracker.ts +++ b/src/main/runtime/terminal/output/terminal-title-tracker.ts @@ -1,5 +1,4 @@ import { OrcaRuntimeWithEmitDaemonPtyTransientFact } from './terminal-transient-facts' -import { isJobStopStatus } from '../../../../shared/terminal/output/terminal-osc133-command-finished' import { getDecorativeTitleGateKey } from '../../../../shared/agent-status/title/agent-decorative-title-signature' import { shouldEmitTitleFactForFrame } from './decorative-title-fact-emission' import type { RuntimePtyTitleTrackerEntry } from '../records/runtime-terminal-state-records' @@ -167,7 +166,7 @@ export abstract class OrcaRuntimeWithGetUnpersistedTrackedTitleForPty extends Or }, onCommandFinished: (exitCode: number | null) => { void this.recheckHookAgentPresenceForPty(ptyId) - this.retirePtyAgentLaunchAuthority(ptyId, !isJobStopStatus(exitCode)) + this.retirePtyAgentLaunchAuthority(ptyId, true) this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode }) this.openCodeRunLifetime.onCommandFinished(ptyId, exitCode) }, diff --git a/src/main/runtime/terminal/output/terminal-transient-facts.ts b/src/main/runtime/terminal/output/terminal-transient-facts.ts index 9ff82506e76c..45437c118dfb 100644 --- a/src/main/runtime/terminal/output/terminal-transient-facts.ts +++ b/src/main/runtime/terminal/output/terminal-transient-facts.ts @@ -1,6 +1,5 @@ import { OrcaRuntimeWithScheduleWaitBlockedCheck } from '../wait/terminal-wait-blocked-checks' import type { PtyTransientFact } from '../../../providers/pty/events' -import { isJobStopStatus } from '../../../../shared/terminal/output/terminal-osc133-command-finished' import type { TerminalSideEffectBatch, TerminalSideEffectFact @@ -33,7 +32,7 @@ export abstract class OrcaRuntimeWithEmitDaemonPtyTransientFact extends OrcaRunt this.recordTerminalSideEffectFact(ptyId, { kind: 'bell' }) return case 'command-finished': - this.retirePtyAgentLaunchAuthority(ptyId, !isJobStopStatus(fact.exitCode)) + this.retirePtyAgentLaunchAuthority(ptyId, true) this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode: fact.exitCode diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index cee8c88adc8f..e9ce93a6dee9 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -243,6 +243,8 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini ['macOS suspended, then another command', ['146', '0'], true], ['macOS suspended, then a listing and another command', ['146', 'listing', '0'], true], ['suspended, resumed (fg), then quit', ['148', 'fg', '0'], false], + // A stop-like status is no proof: an agent that exits 146 for real is gone at that mark. + ['quit with a stop-like exit status', ['exit146'], false], ['quit where the host gives no shell proof (remote, Windows)', ['unproven'], false], ['quit of an agent no Orca launch held (typed at the prompt)', ['typed'], false] ] as const)('%s', async (_, finishes, keepsRecovery) => { @@ -358,7 +360,12 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini } else { stopped ||= status === '148' || status === '146' shellAlone = status === 'unproven' ? null : status !== 'nested' && !stopped - const code = status === 'nested' || status === 'unproven' ? '0' : status + const code = + status === 'exit146' + ? '146' + : status === 'nested' || status === 'unproven' + ? '0' + : status runtime.onPtyData('pty-3', `\x1b]133;C\x07\x1b]133;D;${code}\x07`, Date.now()) // Let the host's shell-alone answer land. await new Promise((resolve) => setImmediate(resolve)) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-identity.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-identity.ts index 7336de3c6099..5cf8e6d03917 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-identity.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pane-agent-identity.ts @@ -1,5 +1,4 @@ import { settlePaneShellForeground } from './pane-agent-shell-lifecycle' -import { isJobStopStatus } from '../../../../../../shared/terminal/output/terminal-osc133-command-finished' import { agentTypeToIconAgent } from '../../../../../../shared/agent-status/presentation/agent-type-icon-agent' import { dismissRetainedProgramResult } from '@/lib/program-status/result-retention' import { isRetainedProgramResult } from '../../../../../../shared/program-status/program-status-row' @@ -182,14 +181,9 @@ export function installPaneAgentIdentity(session: ConnectPanePtySession): void { session.handleCommandFinished = (bestEffortExitCode: number | null): void => { session.clearCommandInferredPaneAgentAfterPtySideEffects() session.visibleForegroundSamplePending = false + const shouldDeferStatusDrop = session.paneForegroundAgentTracker.onCommandFinished() // Commands can change HEAD/index; nudge git UI immediately instead of waiting for polling. dispatchTerminalCommandFinishedEvent(session.deps.worktreeId, bestEffortExitCode) - if (isJobStopStatus(bestEffortExitCode)) { - session.deferredCommandFinishedStatusDrop = null - session.deferredConfirmedShellReconcile = null - return - } - const shouldDeferStatusDrop = session.paneForegroundAgentTracker.onCommandFinished() const state = useAppStore.getState() const entry = state.agentStatusByPaneKey.get(session.cacheKey) const inferenceResult = session.flushPendingInterruptInference() diff --git a/src/shared/terminal/output/terminal-osc133-command-finished.ts b/src/shared/terminal/output/terminal-osc133-command-finished.ts index 89f35a81aa71..7b0c30032dfe 100644 --- a/src/shared/terminal/output/terminal-osc133-command-finished.ts +++ b/src/shared/terminal/output/terminal-osc133-command-finished.ts @@ -8,9 +8,6 @@ type OscTerminator = { } const OSC_133_PREFIX = '\x1b]133;' -// 128 + SIGSTOP/SIGTSTP/SIGTTIN/SIGTTOU, as numbered on macOS (17, 18, 21, 22) and Linux (19, 20, 21, 22). -// Conservative ambiguity exception, not suspension proof: 145/146 are stops only on macOS (SIGSTOP/SIGTSTP). -const JOB_STOP_STATUSES: ReadonlySet = new Set([145, 146, 147, 148, 149, 150]) const MAX_OSC_CARRY_LENGTH = 4096 function findOscTerminator(data: string, startIndex: number): OscTerminator | null { @@ -141,8 +138,3 @@ export function createOsc133CommandFinishedScanner( } } } - -/** A suspended job (Ctrl-Z) finishes its command with a stop status while its process lives on. */ -export function isJobStopStatus(exitCode: number | null): boolean { - return exitCode !== null && JOB_STOP_STATUSES.has(exitCode) -} From 3f1fb88b099425eb0af9a7f4d82cd1b459d75bd8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:12:48 -0800 Subject: [PATCH 086/125] fix(sleep): sleep reads the quit its exit proof is still deciding; plain shells skip the saved-record read; tmux stays shared - Sleep capture's presence check waits for a pane's in-flight shell-alone proof, so a quit just before sleep is retired instead of saved. - A launchless command mark on a pane with no hook row and no tracked proof returns before reading saved records, which can search every repo in main-owned layouts. - An unverified writer no longer strips a tmux host's shared topology. --- .../agent-hooks/server/agent-hook-server.ts | 17 +++++++++++++++++ .../server/cli-writer-observation.ts | 4 ++++ .../server/cli-writer-topology.test.ts | 17 +++++++++++++++++ .../agent-hooks/server/server-tab-cleanup.ts | 12 ++++++------ .../server/unproven-agent-exits.ts | 16 ++++++++++++++-- .../worktree-sleep-resume-recording.test.ts | 19 ++++++++++++++++++- 6 files changed, 76 insertions(+), 9 deletions(-) create mode 100644 src/main/agent-hooks/server/cli-writer-topology.test.ts diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 48a44a0e9ebf..e139838666f1 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -107,6 +107,8 @@ export class AgentHookServer extends AgentHookServerLifecycle { paneKey: string, exitedSince: number ): Promise { + // A quit whose shell-alone proof is still running must be read as that proof decides. + await this.unprovenExits.settled(this.resolvePaneKeyAlias(paneKey)) const verdict = await this.checkAgentPresence(paneKey) // A replaced owner's probe result counts only if its exit was retained. if (verdict !== null && verdict !== 'exited') { @@ -123,6 +125,21 @@ export class AgentHookServer extends AgentHookServerLifecycle { return exit !== undefined && exit.at >= exitedSince ? 'exited' : null } + /** A prompt's mark with no launch held: an agent typed there, or one an earlier mark left + * unproven, may have ended. Only a hook row or a tracked pane can hold one, so the mark of a + * plain shell, which lands on every prompt, skips the saved-record read. */ + protected noticeLaunchlessCommandMark(resolved: string): void { + if (!this.unprovenExits.has(resolved) && !this.state.lastStatusByPaneKey.has(resolved)) { + return + } + const identity = this.paneAgentIdentity(resolved) + const unseen = + identity?.ended === false && + identity.processTopology !== 'shared' && + !this.hasVerifiableAgentProcess(resolved) + this.unprovenExits.onCommandFinished(resolved, unseen) + } + checkAgentPresence(paneKey: string): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) this.followClaudeSessionContinuation(resolved) diff --git a/src/main/agent-hooks/server/cli-writer-observation.ts b/src/main/agent-hooks/server/cli-writer-observation.ts index 3efa242a1cb8..d9d18f8b39eb 100644 --- a/src/main/agent-hooks/server/cli-writer-observation.ts +++ b/src/main/agent-hooks/server/cli-writer-observation.ts @@ -165,6 +165,10 @@ export function deriveCliWriterTopology( ) { return row } + // A tmux host outlives an unverified writer too; only an unverified pane-owned claim is dropped. + if (binding[OPEN_CODE_WRITER_TOPOLOGY] === 'shared') { + return row + } return { ...row, providerSession: { ...binding } } } diff --git a/src/main/agent-hooks/server/cli-writer-topology.test.ts b/src/main/agent-hooks/server/cli-writer-topology.test.ts new file mode 100644 index 000000000000..7dec40eacced --- /dev/null +++ b/src/main/agent-hooks/server/cli-writer-topology.test.ts @@ -0,0 +1,17 @@ +import { expect, it } from 'vitest' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import { deriveCliWriterTopology, retainTmuxWriterTopology } from './cli-writer-observation' +import { cliWriterTopology } from './cli-writer-topology' + +it('keeps a tmux-hosted conversation shared when an unverified writer reports it', () => { + const providerSession = { key: 'session_id' as const, id: 'claude-in-tmux' } + retainTmuxWriterTopology(providerSession) + const row: AgentHookEventPayload = { + paneKey: 'tab-1:pane-1', + connectionId: null, + payload: { state: 'working', prompt: '', agentType: 'claude' }, + providerSession + } + // No execution matcher can vouch for the writer; a pane-owned claim would be dropped here. + expect(cliWriterTopology(deriveCliWriterTopology(row, undefined, null))).toBe('shared') +}) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index fad5b4271fef..86b904a02a2c 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -18,7 +18,8 @@ import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecy export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { abstract checkAgentPresence(paneKey: string): Promise - private readonly unprovenExits = new UnprovenAgentExits((paneKey) => + protected abstract noticeLaunchlessCommandMark(resolvedPaneKey: string): void + protected readonly unprovenExits = new UnprovenAgentExits((paneKey) => this.confirmCommandFinishedExit(paneKey) ) @@ -27,17 +28,16 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { options?: Pick & { launchRetired?: true } ): void { const resolved = this.resolvePaneKeyAlias(paneKey) + if (options?.launchRetired) { + this.noticeLaunchlessCommandMark(resolved) + return + } const identity = this.paneAgentIdentity(paneKey) const shared = identity?.processTopology === 'shared' // A command mark can come from a shell nested in a live agent; one with no process to probe // ends only on the host's word that the pane's shell is alone. const verifiable = this.hasVerifiableAgentProcess(paneKey) const unprovable = identity?.ended === false && !shared && !verifiable - if (options?.launchRetired) { - // An agent typed at the prompt holds no launch; its quit is proved the same way. - this.unprovenExits.onCommandFinished(resolved, unprovable) - return - } // A mark's exit status can't tell a quit from a stop (Ctrl-Z). A local process answers through // its presence probe, a stopped one included; a remote one can't be probed, so its mark stands. const awaitsHost = options?.confirmedExit === true && !verifiable diff --git a/src/main/agent-hooks/server/unproven-agent-exits.ts b/src/main/agent-hooks/server/unproven-agent-exits.ts index 065e22d74445..d91f0cd08c70 100644 --- a/src/main/agent-hooks/server/unproven-agent-exits.ts +++ b/src/main/agent-hooks/server/unproven-agent-exits.ts @@ -1,4 +1,4 @@ -type UnprovenExit = { proving: boolean; again: boolean } +type UnprovenExit = { proving: boolean; again: boolean; proof?: Promise } /** Panes whose process-less agent may have ended unseen: its launch retired on a job stop, or on * a command mark the shell-alone proof refused (a shell nested in the live agent). Each later @@ -22,6 +22,10 @@ export class UnprovenAgentExits { } } + has(paneKey: string): boolean { + return this.panes.has(paneKey) + } + forget(paneKey: string): void { this.panes.delete(paneKey) } @@ -48,7 +52,7 @@ export class UnprovenAgentExits { } entry.proving = true entry.again = false - void this.prove(paneKey) + entry.proof = this.prove(paneKey) .catch(() => false) .then((settled) => { if (this.panes.get(paneKey) !== entry) { @@ -62,4 +66,12 @@ export class UnprovenAgentExits { } }) } + + /** Resolves once no proof for the pane is running, a queued re-proof included, so a sleep + * capture reads the quit it is still proving. */ + async settled(paneKey: string): Promise { + for (let entry = this.panes.get(paneKey); entry?.proving; entry = this.panes.get(paneKey)) { + await entry.proof + } + } } diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index e9ce93a6dee9..c0b6d81c14c5 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -245,6 +245,7 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini ['suspended, resumed (fg), then quit', ['148', 'fg', '0'], false], // A stop-like status is no proof: an agent that exits 146 for real is gone at that mark. ['quit with a stop-like exit status', ['exit146'], false], + ['quit, then sleep while its exit proof still runs', ['quit-then-sleep'], false], ['quit where the host gives no shell proof (remote, Windows)', ['unproven'], false], ['quit of an agent no Orca launch held (typed at the prompt)', ['typed'], false] ] as const)('%s', async (_, finishes, keepsRecovery) => { @@ -254,6 +255,7 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini // The host's word on the pane's shell: alone unless a nested shell marked a command. let shellAlone: boolean | null = true let stopped = false + let proofGate: Promise = Promise.resolve() const fixture = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ sleepingAgentSessionsByPaneKey: { [PANE_KEY]: SLEPT } @@ -272,7 +274,10 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini isPlaced: () => true, readSavedRecord: (paneKey) => fixture.getSession().sleepingAgentSessionsByPaneKey?.[paneKey], confirmProcessExit: async () => true, - confirmShellAlone: async () => shellAlone, + confirmShellAlone: async () => { + await proofGate + return shellAlone + }, retireSavedRecord: (paneKey, at) => runtime.retireExitedPaneResume(paneKey, at) }) const clears: AgentStatusClearIpcPayload[] = [] @@ -343,6 +348,18 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini // The runtime's notice for a mark that finds no launch held. server.retireProcessAuthority(PANE_KEY, { confirmedExit: true, launchRetired: true }) await new Promise((resolve) => setImmediate(resolve)) + } else if (status === 'quit-then-sleep') { + let release = (): void => {} + proofGate = new Promise((resolve) => { + release = resolve + }) + shellAlone = true + runtime.onPtyData('pty-3', '\x1b]133;C\x07\x1b]133;D;0\x07', Date.now()) + // The sleep starts before the process table answers; it must read the quit it proves. + const slept = sleep() + await new Promise((resolve) => setImmediate(resolve)) + release() + expect(await slept).toBeUndefined() } else if (status === 'fg') { stopped = false } else if (status === 'listing') { From 0113e9506ce948a81016d13df40656eb469b8a7b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:29:09 -0800 Subject: [PATCH 087/125] fix(sleep): CLI and mobile input void a running exit proof; sleep waits only for the proof in flight; proofs read the pane's PTY from the spawn index - The input fence also reads the runtime's input facts, which CLI and mobile writes update. - Sleep capture waits for a pane's running proof, not queued re-proofs, so marks arriving faster than proofs can't hold a sleep back. - A proof resolves the pane's PTY from the spawn-time index before searching the runtime's panes, as ownsProcess does. --- .../server/unproven-agent-exits.ts | 9 ++- .../terminal-pane-status-lifecycle.test.ts | 60 +++++++++++-------- .../pane/terminal-pane-status-lifecycle.ts | 26 ++++++-- 3 files changed, 59 insertions(+), 36 deletions(-) diff --git a/src/main/agent-hooks/server/unproven-agent-exits.ts b/src/main/agent-hooks/server/unproven-agent-exits.ts index d91f0cd08c70..57d4f0abfb25 100644 --- a/src/main/agent-hooks/server/unproven-agent-exits.ts +++ b/src/main/agent-hooks/server/unproven-agent-exits.ts @@ -67,11 +67,10 @@ export class UnprovenAgentExits { }) } - /** Resolves once no proof for the pane is running, a queued re-proof included, so a sleep - * capture reads the quit it is still proving. */ + /** Resolves once the pane's running proof answers, so a sleep capture reads the quit it is + * still proving. A queued re-proof isn't awaited: marks arriving faster than proofs can't hold + * a sleep back. */ async settled(paneKey: string): Promise { - for (let entry = this.panes.get(paneKey); entry?.proving; entry = this.panes.get(paneKey)) { - await entry.proof - } + await this.panes.get(paneKey)?.proof } } diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index 2d388f79764b..acb65ad6fbbf 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -121,6 +121,7 @@ it.each([ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this exit probe only reads these two runtime capabilities. const runtime = { resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }), + terminalRunFacts: { readLastInputAt: () => null }, getLaunchStatementForPaneKey: () => currentLaunch } as unknown as OrcaRuntimeService bindTerminalPaneStatusLifecycle(runtime, undefined) @@ -131,29 +132,36 @@ it.each([ } ) -it('does not count a shell-alone proof once input reached the PTY while it ran', async () => { - Object.defineProperty(process, 'platform', { value: 'darwin' }) - const { lastInputAtByPty } = await import('../delivery/visibility-state') - let typed = false - // The user types `codex resume ` after the table was read but before the proof returns. - confirmRootShellAlone.mockImplementation(async () => { - if (typed) { - lastInputAtByPty.set('pty-1', performance.now()) - } - return true - }) - getProviderForPty.mockReturnValue({ - listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }] - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the proof only resolves the pane. - const runtime = { - resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }) - } as unknown as OrcaRuntimeService - bindTerminalPaneStatusLifecycle(runtime, undefined) - const lifecycle = setTerminalPaneLifecycle.mock.lastCall![0] - const paneKey = 'tab:11111111-1111-4111-8111-111111111111' - expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(true) - typed = true - expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(false) - lastInputAtByPty.delete('pty-1') -}) +it.each(['desktop', 'CLI or mobile'] as const)( + 'does not count a shell-alone proof once %s input reached the PTY while it ran', + async (source) => { + Object.defineProperty(process, 'platform', { value: 'darwin' }) + const { lastInputAtByPty } = await import('../delivery/visibility-state') + let typed = false + let runtimeInputAt = 1 + // The user sends `codex resume ` after the table was read but before the proof returns. + confirmRootShellAlone.mockImplementation(async () => { + if (typed && source === 'desktop') { + lastInputAtByPty.set('pty-1', performance.now()) + } else if (typed) { + runtimeInputAt += 1 + } + return true + }) + getProviderForPty.mockReturnValue({ + listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }] + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the proof only resolves the pane and reads its input facts. + const runtime = { + resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }), + terminalRunFacts: { readLastInputAt: () => runtimeInputAt } + } as unknown as OrcaRuntimeService + bindTerminalPaneStatusLifecycle(runtime, undefined) + const lifecycle = setTerminalPaneLifecycle.mock.lastCall![0] + const paneKey = 'tab:11111111-1111-4111-8111-111111111111' + expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(true) + typed = true + expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(false) + lastInputAtByPty.delete('pty-1') + } +) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 5da6c44c9389..235193f34f27 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -115,6 +115,19 @@ export function bindTerminalPaneStatusLifecycle( /** A local pane's shell alone holds its PTY, and the pane still runs that PTY afterwards; null on * a remote host, which reports no process tree to main. */ +/** The pane's PTY from the spawn-time index, else the runtime's pane search. */ +function resolvePanePty( + runtime: OrcaRuntimeService, + paneKey: string +): { ptyId: string | null; incarnationId: string | null } { + const ptyId = paneKeyPtyId.get(paneKey) + if (ptyId) { + return { ptyId, incarnationId: ptyIncarnationById.get(ptyId) ?? null } + } + const pane = runtime.resolveTerminalPane(paneKey) + return { ptyId: pane.ptyId ?? null, incarnationId: pane.incarnationId ?? null } +} + async function paneShellAlone( runtime: OrcaRuntimeService | undefined, paneKey: string, @@ -125,20 +138,23 @@ async function paneShellAlone( return false } try { - const pane = runtime.resolveTerminalPane(paneKey) + const pane = resolvePanePty(runtime, paneKey) if (!pane.ptyId) { return false } if (isRemoteExecutionHostPtyId(pane.ptyId)) { return null } - // Input during the proof may start the next agent (`codex resume`) after the table was read. - const inputBefore = lastInputAtByPty.get(pane.ptyId) + // Input during the proof (desktop, CLI or mobile) may start the next agent (`codex resume`) + // after the table was read. + const inputStamp = (ptyId: string): string => + `${lastInputAtByPty.get(ptyId)}|${runtime.terminalRunFacts.readLastInputAt(ptyId)}` + const inputBefore = inputStamp(pane.ptyId) const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined, agent) - const current = runtime.resolveTerminalPane(paneKey) + const current = resolvePanePty(runtime, paneKey) return ( shellAlone && - lastInputAtByPty.get(pane.ptyId) === inputBefore && + inputStamp(pane.ptyId) === inputBefore && current.ptyId === pane.ptyId && current.incarnationId === pane.incarnationId && stillCurrent() From 84a99cd089f1b8789f7ec0eead0e3e86f9ec3d86 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:37:55 -0800 Subject: [PATCH 088/125] fix(sleep): a WSL or SSH agent's command mark ends it as on main Only a hook row the presence probe can reach (connectionId null) keeps its identity for the probe; WSL and SSH rows have no probe, so their mark retires them. --- src/main/agent-hooks/server/server-tab-cleanup.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 86b904a02a2c..c9b406b94fcd 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -13,7 +13,6 @@ import type { RefusedPaneResume } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import { UnprovenAgentExits } from './unproven-agent-exits' -import { isLocalHookConnectionId } from '../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { @@ -39,11 +38,11 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { const verifiable = this.hasVerifiableAgentProcess(paneKey) const unprovable = identity?.ended === false && !shared && !verifiable // A mark's exit status can't tell a quit from a stop (Ctrl-Z). A local process answers through - // its presence probe, a stopped one included; a remote one can't be probed, so its mark stands. + // its presence probe, a stopped one included; one the probe can't reach (SSH, WSL) lets the + // mark stand, as on main. const awaitsHost = options?.confirmedExit === true && !verifiable - const connectionId = this.state.lastStatusByPaneKey.get(resolved)?.connectionId ?? null - const confirmedExit = - options?.confirmedExit === true && verifiable && !isLocalHookConnectionId(connectionId) + const probed = this.state.lastStatusByPaneKey.get(resolved)?.connectionId === null + const confirmedExit = options?.confirmedExit === true && verifiable && !probed const { paneKeys, authorityChanged } = this.revokeProcessAuthority(paneKey) const { untouched } = this.reconcileEndedProcess( paneKeys, From a551ae1ed132716bc8cb2ba78e1f10f945b9dc26 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:40:31 -0800 Subject: [PATCH 089/125] perf(sleep): a quit checkpoint reads terminal identity once for all saved panes Each saved pane's live-terminal check shares one identity read context instead of scanning every leaf and PTY per pane. --- .../db/runtime-orchestration-database-access.ts | 6 +++++- .../session-tabs/layout/main-layout-agent-launch-tabs.ts | 4 ++-- .../terminal/stop/worktree-sleep-resume-recording.ts | 8 ++++++-- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts b/src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts index 15e381da184d..1d51a1a70e0d 100644 --- a/src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts +++ b/src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts @@ -1,3 +1,4 @@ +import type { TerminalIdentityReadContext } from '../../terminal/query/terminal-identity-read-context' import { getWorkerTerminalAutoReleaseScheduler } from '../terminal-authority/release/worker-terminal-auto-release-scheduler' import { OrchestrationDb } from './orchestration-db' import { OrchestrationDbMaintenance } from './maintenance/orchestration-db-maintenance' @@ -20,7 +21,10 @@ export abstract class RuntimeOrchestrationDatabaseAccess extends OrcaRuntimeWith protected abstract scheduleRestoredMessageRepoints(): void - abstract hasLiveTerminalForPaneKey(paneKey: string): boolean + abstract hasLiveTerminalForPaneKey( + paneKey: string, + context?: TerminalIdentityReadContext + ): boolean /** Mail a worker left unread when it reported before a restart still continues it. */ protected abstract continueRestoredWorkerMail(db: OrchestrationDb): void diff --git a/src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts b/src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts index 2d990389120a..50201e51c44d 100644 --- a/src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts +++ b/src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts @@ -30,8 +30,8 @@ export abstract class OrcaRuntimeWithMainLayoutAgentLaunchTabs extends OrcaRunti ): RuntimePtyWorktreeRecord | null /** Whether a running process holds this pane now: such a pane is attached to, never launched into. */ - hasLiveTerminalForPaneKey(paneKey: string): boolean { - const pty = this.getPtyRecordForPaneKey(paneKey) + hasLiveTerminalForPaneKey(paneKey: string, context?: TerminalIdentityReadContext): boolean { + const pty = this.getPtyRecordForPaneKey(paneKey, context) // Main's bound terminal may survive listing gaps; only certified exit frees its pane. return ORCA_LAYOUT_OWNER_IS_MAIN ? !!pty && this.getPtyLivenessVerdict(pty.ptyId)?.status !== 'exited' diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 7452ec8c5d7e..902c47e3b01f 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -238,11 +238,15 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu /** A layout-owner build's quit capture of the agents of the panes one partition holds. */ quitResumeRecordsFor(session: WorkspaceSessionState): SleepingAgentSessionRecord[] { // A saved-only pane quits only while its terminal runs; an asleep pane keeps its sleep record - // and a live checkpoint stays as saved, as main leaves both. + // and a live checkpoint stays as saved, as main leaves both. One identity read for every pane. + const context = this.createTerminalIdentityReadContext() const paneKeys = new Set([ ...(this.getAgentProviderSessionSnapshotFn?.() ?? []).map((row) => row.paneKey), ...Object.values(session.sleepingAgentSessionsByPaneKey ?? {}) - .filter((saved) => saved.origin !== 'live' && this.hasLiveTerminalForPaneKey(saved.paneKey)) + .filter( + (saved) => + saved.origin !== 'live' && this.hasLiveTerminalForPaneKey(saved.paneKey, context) + ) .map((saved) => saved.paneKey) ]) const statuses = [...paneKeys].flatMap((paneKey) => { From 0dec9ec30ec2b72af919e7f46a640345e78567e7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:42:27 -0800 Subject: [PATCH 090/125] fix(sleep): query replies don't void exit proofs; launchless marks arm only provable panes; a Claude continuation stays shared - The input fence reads the runtime's input facts alone, which skip a terminal's automatic query replies (a prompt's cursor-position request no longer voids every proof). - A launchless mark arms only a local POSIX pane; on SSH, WSL and Windows, main ends no agent at such a mark and neither does this. - Following a Claude session continuation keeps a tmux host's shared topology. --- .../agent-hooks/server/agent-hook-server.ts | 17 +++++- .../terminal-pane-status-lifecycle.test.ts | 60 +++++++++---------- .../pane/terminal-pane-status-lifecycle.ts | 7 +-- 3 files changed, 45 insertions(+), 39 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index e139838666f1..8b505e648e69 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -4,7 +4,11 @@ import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normal import { parseFormEncodedBody } from '../../../shared/agent-hook-listener/request-body' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' -import { cliWriterTopology, type CliWriterObservation } from './cli-writer-observation' +import { + cliWriterTopology, + retainTmuxWriterTopology, + type CliWriterObservation +} from './cli-writer-observation' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' import { @@ -129,11 +133,16 @@ export class AgentHookServer extends AgentHookServerLifecycle { * unproven, may have ended. Only a hook row or a tracked pane can hold one, so the mark of a * plain shell, which lands on every prompt, skips the saved-record read. */ protected noticeLaunchlessCommandMark(resolved: string): void { - if (!this.unprovenExits.has(resolved) && !this.state.lastStatusByPaneKey.has(resolved)) { + const row = this.state.lastStatusByPaneKey.get(resolved) + if (!this.unprovenExits.has(resolved) && !row) { return } const identity = this.paneAgentIdentity(resolved) + // Main ends no agent at a launchless mark; only a host that can prove the shell alone (local + // POSIX) may, so SSH, WSL and Windows panes aren't armed here. const unseen = + row?.connectionId === null && + process.platform !== 'win32' && identity?.ended === false && identity.processTopology !== 'shared' && !this.hasVerifiableAgentProcess(resolved) @@ -213,6 +222,10 @@ export class AgentHookServer extends AgentHookServerLifecycle { paneKey ) if (next) { + // The conversation moved, not its host: a tmux server still runs it. + if (cliWriterTopology(row) === 'shared') { + retainTmuxWriterTopology(next) + } this.applyNormalizedStatus( { ...row, diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index acb65ad6fbbf..428d8384e1ca 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -132,36 +132,30 @@ it.each([ } ) -it.each(['desktop', 'CLI or mobile'] as const)( - 'does not count a shell-alone proof once %s input reached the PTY while it ran', - async (source) => { - Object.defineProperty(process, 'platform', { value: 'darwin' }) - const { lastInputAtByPty } = await import('../delivery/visibility-state') - let typed = false - let runtimeInputAt = 1 - // The user sends `codex resume ` after the table was read but before the proof returns. - confirmRootShellAlone.mockImplementation(async () => { - if (typed && source === 'desktop') { - lastInputAtByPty.set('pty-1', performance.now()) - } else if (typed) { - runtimeInputAt += 1 - } - return true - }) - getProviderForPty.mockReturnValue({ - listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }] - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the proof only resolves the pane and reads its input facts. - const runtime = { - resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }), - terminalRunFacts: { readLastInputAt: () => runtimeInputAt } - } as unknown as OrcaRuntimeService - bindTerminalPaneStatusLifecycle(runtime, undefined) - const lifecycle = setTerminalPaneLifecycle.mock.lastCall![0] - const paneKey = 'tab:11111111-1111-4111-8111-111111111111' - expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(true) - typed = true - expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(false) - lastInputAtByPty.delete('pty-1') - } -) +it('does not count a shell-alone proof once input reached the PTY while it ran', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin' }) + let typed = false + let lastInputAt = 1 + // The user sends `codex resume ` (desktop, CLI or mobile) after the table was read but + // before the proof returns; a terminal's automatic query reply is not recorded as input. + confirmRootShellAlone.mockImplementation(async () => { + if (typed) { + lastInputAt += 1 + } + return true + }) + getProviderForPty.mockReturnValue({ + listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }] + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the proof only resolves the pane and reads its input facts. + const runtime = { + resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }), + terminalRunFacts: { readLastInputAt: () => lastInputAt } + } as unknown as OrcaRuntimeService + bindTerminalPaneStatusLifecycle(runtime, undefined) + const lifecycle = setTerminalPaneLifecycle.mock.lastCall![0] + const paneKey = 'tab:11111111-1111-4111-8111-111111111111' + expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(true) + typed = true + expect(await lifecycle.confirmShellAlone?.(paneKey, 'codex')).toBe(false) +}) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 235193f34f27..96450efca241 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -7,7 +7,6 @@ import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-top import { paneKeyPtyId } from './key-state' import { ptyFallbackRootPidById, ptyIncarnationById } from '../provider/ownership-state' import { getRegisteredPtyPid } from '../../../memory/pty-registry' -import { lastInputAtByPty } from '../delivery/visibility-state' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { getProviderForPty } from '../provider/registry' import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' @@ -146,9 +145,9 @@ async function paneShellAlone( return null } // Input during the proof (desktop, CLI or mobile) may start the next agent (`codex resume`) - // after the table was read. - const inputStamp = (ptyId: string): string => - `${lastInputAtByPty.get(ptyId)}|${runtime.terminalRunFacts.readLastInputAt(ptyId)}` + // after the table was read; run facts skip a terminal's automatic query replies. + const inputStamp = (ptyId: string): number | null => + runtime.terminalRunFacts.readLastInputAt(ptyId) const inputBefore = inputStamp(pane.ptyId) const shellAlone = await confirmShellAlone(pane.ptyId, pane.incarnationId ?? undefined, agent) const current = resolvePanePty(runtime, paneKey) From 30d88e22254980a7838f35cb97fe7861998c9f6a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:53:31 -0800 Subject: [PATCH 091/125] fix(sleep): a trusted WSL or SSH command mark retires the agent's checkpoint too The presence probe can't reach a WSL or SSH process, so the mark that ends such an agent also records its exit instead of leaving the saved checkpoint to be resumed. --- src/main/agent-hooks/server/server-cleanup.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 837f982576e5..3848b8018f0e 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -131,10 +131,11 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { | undefined const endedPresence = options?.endedPresence ?? - // A proved process gets its exit from the presence probe, not a possibly newer row; a - // shared server (tmux, OpenCode) outlives the command that finished at the pane's shell. + // A process the presence probe reaches gets its exit from the probe, not a possibly newer + // row (WSL/SSH have no probe, so their mark stands); a shared server (tmux, OpenCode) + // outlives the command that finished at the pane's shell. (options?.confirmedExit && - !previous?.agentPresence?.process && + (!previous?.agentPresence?.process || previous.connectionId !== null) && this.paneAgentIdentity(resolvedPaneKey)?.processTopology !== 'shared' ? previous ? endedPresenceOf(previous) From 0421185d1f5b8b3b28cbf61e5c10fcf8652f3eb0 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:00:19 -0800 Subject: [PATCH 092/125] fix(sleep): a sleep re-proves a tracked pane once; quit checkpoints reuse one identity read for launch lookups - A sleep capture runs one fresh shell-alone proof for a pane still tracked, so a quit whose last proof was voided by typed input is retired instead of resumed. - The quit checkpoint's launch lookups reuse its shared identity read context. --- .../agent-hooks/server/unproven-agent-exits.test.ts | 13 +++++++++++++ src/main/agent-hooks/server/unproven-agent-exits.ts | 12 ++++++++---- .../stop/worktree-sleep-resume-recording.ts | 9 +++++++-- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/src/main/agent-hooks/server/unproven-agent-exits.test.ts b/src/main/agent-hooks/server/unproven-agent-exits.test.ts index 9424a456ac50..8eecc0500a7c 100644 --- a/src/main/agent-hooks/server/unproven-agent-exits.test.ts +++ b/src/main/agent-hooks/server/unproven-agent-exits.test.ts @@ -20,3 +20,16 @@ it('re-proves once for a mark that lands while the first proof still reads a liv exits.onCommandFinished('pane') expect(answers).toHaveLength(2) }) + +it('proves a tracked pane afresh for a sleep, whose last proof was voided', async () => { + const answers: boolean[] = [false, true] + let proofs = 0 + const exits = new UnprovenAgentExits(async () => answers[proofs++] ?? false) + exits.launchRetired('pane', true, true) + await new Promise((resolve) => setImmediate(resolve)) + expect(exits.has('pane')).toBe(true) + // Sleep asks once more; the quit is proved now and the pane settles. + await exits.settled('pane') + await new Promise((resolve) => setImmediate(resolve)) + expect(exits.has('pane')).toBe(false) +}) diff --git a/src/main/agent-hooks/server/unproven-agent-exits.ts b/src/main/agent-hooks/server/unproven-agent-exits.ts index 57d4f0abfb25..ce479a5ad440 100644 --- a/src/main/agent-hooks/server/unproven-agent-exits.ts +++ b/src/main/agent-hooks/server/unproven-agent-exits.ts @@ -67,10 +67,14 @@ export class UnprovenAgentExits { }) } - /** Resolves once the pane's running proof answers, so a sleep capture reads the quit it is - * still proving. A queued re-proof isn't awaited: marks arriving faster than proofs can't hold - * a sleep back. */ + /** Answers a sleep capture with one current proof: the running one, else a fresh one for a pane + * still tracked (its last proof may have been voided by input). Queued re-proofs aren't + * awaited, so marks arriving faster than proofs can't hold a sleep back. */ async settled(paneKey: string): Promise { - await this.panes.get(paneKey)?.proof + const entry = this.panes.get(paneKey) + if (entry && !entry.proving) { + this.onCommandFinished(paneKey) + } + await entry?.proof } } diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 902c47e3b01f..fa34beb3e1b1 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -1,3 +1,4 @@ +import type { TerminalIdentityReadContext } from '../query/terminal-identity-read-context' import { sleepingRecordsEquivalentIgnoringCaptureTime } from '../../../../shared/agent-session/lifecycle/resume/agent-resume-record-equivalence' import { OrcaRuntimeWithStopTerminalsForWorktree } from './worktree-terminal-stop' import { launchStatement } from '../launch/launch-evidence' @@ -150,7 +151,10 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu >() private hookStatusResumeWrites: Promise = Promise.resolve() - protected abstract getPtyRecordForPaneKey(paneKey: string): RuntimePtyWorktreeRecord | null + protected abstract getPtyRecordForPaneKey( + paneKey: string, + context?: TerminalIdentityReadContext + ): RuntimePtyWorktreeRecord | null /** Main's word on the Orca launch running in this pane now; the one check every saved note passes. */ getLaunchStatementForPaneKey: PaneLaunchConfigOf = (paneKey, agent) => @@ -267,7 +271,8 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu statuses, session, worktreeIdOf: (paneKey) => this.getTerminalWorktreeIdForPaneKey(paneKey), - launchConfigOf: this.getLaunchStatementForPaneKey, + launchConfigOf: (paneKey, agent) => + launchStatement(this.getPtyRecordForPaneKey(paneKey, context), agent), capturedAt: Date.now() }) } From 43ff8f333d4b78ac02cdc5257f85fe86f075c0a3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:09:46 -0800 Subject: [PATCH 093/125] fix(sleep): only a sleep capture re-proves a tracked pane, and it waits for a re-proof already queued Other presence readers (resume ownership, federation snapshots) await only a running proof, so polling them starts no process-table reads. A sleep also awaits a quit's re-proof queued behind a nested mark's proof. --- .../runtime/agent-hook-runtime-deps.ts | 4 ++-- .../agent-hooks/server/agent-hook-server.ts | 5 +++-- .../server/unproven-agent-exits.test.ts | 22 ++++++++++++++++++- .../server/unproven-agent-exits.ts | 19 ++++++++++++---- .../runtime-construction-dependencies.ts | 4 +++- .../stop/worktree-sleep-resume-recording.ts | 3 ++- 6 files changed, 46 insertions(+), 11 deletions(-) diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index 3a6ab0475fef..6b01868ce1a4 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -83,10 +83,10 @@ export function agentHookRuntimeDeps( readChildWorkHandles: (subject) => server.getStructuredChildWorkHandles(subject) }, readHookCliWriterObservation: (row) => server.readCliWriterObservation(row), - checkHookAgentPresence: (paneKey, exitedSince) => + checkHookAgentPresence: (paneKey, exitedSince, options) => exitedSince === undefined ? server.checkAgentPresence(paneKey) - : server.checkAgentPresenceSince(paneKey, exitedSince), + : server.checkAgentPresenceSince(paneKey, exitedSince, options), reconcileAgentStatusForEndedProcess: (paneKeys, sleep) => { const keys = [...paneKeys] if (sleep) { diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 8b505e648e69..6e6616a646e6 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -109,10 +109,11 @@ export class AgentHookServer extends AgentHookServerLifecycle { /** Include retained exits proven at or after `exitedSince`. */ async checkAgentPresenceSince( paneKey: string, - exitedSince: number + exitedSince: number, + options?: { forSleep?: true } ): Promise { // A quit whose shell-alone proof is still running must be read as that proof decides. - await this.unprovenExits.settled(this.resolvePaneKeyAlias(paneKey)) + await this.unprovenExits.settled(this.resolvePaneKeyAlias(paneKey), options?.forSleep) const verdict = await this.checkAgentPresence(paneKey) // A replaced owner's probe result counts only if its exit was retained. if (verdict !== null && verdict !== 'exited') { diff --git a/src/main/agent-hooks/server/unproven-agent-exits.test.ts b/src/main/agent-hooks/server/unproven-agent-exits.test.ts index 8eecc0500a7c..af541a65a635 100644 --- a/src/main/agent-hooks/server/unproven-agent-exits.test.ts +++ b/src/main/agent-hooks/server/unproven-agent-exits.test.ts @@ -29,7 +29,27 @@ it('proves a tracked pane afresh for a sleep, whose last proof was voided', asyn await new Promise((resolve) => setImmediate(resolve)) expect(exits.has('pane')).toBe(true) // Sleep asks once more; the quit is proved now and the pane settles. - await exits.settled('pane') + await exits.settled('pane', true) await new Promise((resolve) => setImmediate(resolve)) expect(exits.has('pane')).toBe(false) }) + +it('has a sleep wait for the re-proof a quit queued behind a nested mark proof', async () => { + const answers: ((settled: boolean) => void)[] = [] + const exits = new UnprovenAgentExits( + () => new Promise((resolve) => answers.push(resolve)) + ) + // A nested mark's proof runs; the real quit's mark queues another; then the sleep starts. + exits.launchRetired('pane', true, true) + exits.onCommandFinished('pane') + let slept = false + const sleep = exits.settled('pane', true).then(() => { + slept = true + }) + answers[0](false) + await new Promise((resolve) => setImmediate(resolve)) + expect(slept).toBe(false) + answers[1](true) + await sleep + expect(exits.has('pane')).toBe(false) +}) diff --git a/src/main/agent-hooks/server/unproven-agent-exits.ts b/src/main/agent-hooks/server/unproven-agent-exits.ts index ce479a5ad440..1293cd2215d9 100644 --- a/src/main/agent-hooks/server/unproven-agent-exits.ts +++ b/src/main/agent-hooks/server/unproven-agent-exits.ts @@ -67,14 +67,25 @@ export class UnprovenAgentExits { }) } - /** Answers a sleep capture with one current proof: the running one, else a fresh one for a pane - * still tracked (its last proof may have been voided by input). Queued re-proofs aren't - * awaited, so marks arriving faster than proofs can't hold a sleep back. */ - async settled(paneKey: string): Promise { + /** Other readers await only the running proof. A sleep capture gets one current proof: the + * running one, else a fresh one for a pane + * still tracked (its last proof may have been voided by input), plus a re-proof already queued. + * Marks arriving after the sleep starts aren't awaited, so they can't hold it back. */ + async settled(paneKey: string, forSleep = false): Promise { const entry = this.panes.get(paneKey) + if (!forSleep) { + await entry?.proof + return + } if (entry && !entry.proving) { this.onCommandFinished(paneKey) } + // A mark seen before the sleep (a quit after a nested mark) already queued the proof that + // decides it; await that one too, but none queued later. + const queued = entry?.again === true await entry?.proof + if (queued && this.panes.get(paneKey) === entry && entry?.proving) { + await entry.proof + } } } diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 36d816e3a814..981381d13489 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -78,9 +78,11 @@ export type RuntimeConstructionDependencies = { ) => void readHookCliWriterObservation?: (row: AgentStatusIpcPayload) => CliWriterObservation | null /** `exitedSince`: also answer `exited` for an exit the hook store proved at or after it. */ + /** `forSleep`: a sleep capture, which re-proves a pane whose agent may have ended unseen. */ checkHookAgentPresence?: ( paneKey: string, - exitedSince?: number + exitedSince?: number, + options?: { forSleep?: true } ) => Promise<'live' | 'unverifiable' | 'exited' | null> reconcileAgentStatusForEndedProcess?: ( paneKeys: Iterable, diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index fa34beb3e1b1..0882e18217ad 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -124,7 +124,8 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu readSavedRecord: (paneKey) => this.readSavedResumeSource(worktreeId, paneKey), readIdentity: (paneKey, savedRecord) => this.readPaneAgentIdentity(paneKey, savedRecord), checkAgentPresence: (paneKey, since) => - this.checkHookAgentPresenceFn?.(paneKey, since) ?? Promise.resolve(null), + this.checkHookAgentPresenceFn?.(paneKey, since, { forSleep: true }) ?? + Promise.resolve(null), capturedAt: Date.now() }) }, From e2498cbb392f58260f14160ad5d0b04c1af3443a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:16:22 -0800 Subject: [PATCH 094/125] perf(sleep): a sleep settles all panes' exit proofs together and resolves its saved-record host once --- .../runtime/agent-hook-runtime-deps.ts | 8 ++++--- .../agent-hooks/server/agent-hook-server.ts | 12 +++++++--- .../runtime-construction-dependencies.ts | 5 +++-- .../stop/worktree-sleep-resume-recording.ts | 22 +++++++++++++------ 4 files changed, 32 insertions(+), 15 deletions(-) diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index 6b01868ce1a4..a596b1cb6434 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -84,9 +84,11 @@ export function agentHookRuntimeDeps( }, readHookCliWriterObservation: (row) => server.readCliWriterObservation(row), checkHookAgentPresence: (paneKey, exitedSince, options) => - exitedSince === undefined - ? server.checkAgentPresence(paneKey) - : server.checkAgentPresenceSince(paneKey, exitedSince, options), + options?.settleForSleep + ? server.settleExitProofForSleep(paneKey) + : exitedSince === undefined + ? server.checkAgentPresence(paneKey) + : server.checkAgentPresenceSince(paneKey, exitedSince), reconcileAgentStatusForEndedProcess: (paneKeys, sleep) => { const keys = [...paneKeys] if (sleep) { diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 6e6616a646e6..30c4a9b1a757 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -107,13 +107,19 @@ export class AgentHookServer extends AgentHookServerLifecycle { } /** Include retained exits proven at or after `exitedSince`. */ + /** A sleep settles every pane's exit proofs together, so their fresh process-table reads + * coalesce into one; the capture's own presence reads then find them answered. */ + async settleExitProofForSleep(paneKey: string): Promise { + await this.unprovenExits.settled(this.resolvePaneKeyAlias(paneKey), true) + return null + } + async checkAgentPresenceSince( paneKey: string, - exitedSince: number, - options?: { forSleep?: true } + exitedSince: number ): Promise { // A quit whose shell-alone proof is still running must be read as that proof decides. - await this.unprovenExits.settled(this.resolvePaneKeyAlias(paneKey), options?.forSleep) + await this.unprovenExits.settled(this.resolvePaneKeyAlias(paneKey)) const verdict = await this.checkAgentPresence(paneKey) // A replaced owner's probe result counts only if its exit was retained. if (verdict !== null && verdict !== 'exited') { diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 981381d13489..8a11616ad7c0 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -78,11 +78,12 @@ export type RuntimeConstructionDependencies = { ) => void readHookCliWriterObservation?: (row: AgentStatusIpcPayload) => CliWriterObservation | null /** `exitedSince`: also answer `exited` for an exit the hook store proved at or after it. */ - /** `forSleep`: a sleep capture, which re-proves a pane whose agent may have ended unseen. */ + /** `settleForSleep`: only settle the pane's exit proofs for a sleep capture (a fresh one for a + * pane whose agent may have ended unseen); answers null without probing. */ checkHookAgentPresence?: ( paneKey: string, exitedSince?: number, - options?: { forSleep?: true } + options?: { settleForSleep?: true } ) => Promise<'live' | 'unverifiable' | 'exited' | null> reconcileAgentStatusForEndedProcess?: ( paneKeys: Iterable, diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 0882e18217ad..43e98c9f4304 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -36,12 +36,13 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu /** Capture after earlier status writes so their saved copy participates in exact cleanup. */ readSavedResumeSource( worktreeId: string, - paneKey: string + paneKey: string, + /** A capture resolves its workspace's host once for every pane. */ + hostId = this.getWorkspaceSessionHostIdForWorktree(worktreeId) ): Promise { return this.inResumeRecordOrder( async () => - this.store?.getWorkspaceSession?.(this.getWorkspaceSessionHostIdForWorktree(worktreeId)) - ?.sleepingAgentSessionsByPaneKey?.[paneKey] + this.store?.getWorkspaceSession?.(hostId)?.sleepingAgentSessionsByPaneKey?.[paneKey] ) } @@ -112,20 +113,27 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu } protected readonly sleepResumeRecords: WorktreeSleepResumeRecorder = { - capture: (worktreeId, ptyIds) => { + capture: async (worktreeId, ptyIds) => { const paneKeysByPtyId = new Map( [...ptyIds].map((ptyId) => [ptyId, this.collectAgentStatusPaneKeysForPty(ptyId)]) ) + // Settle every pane's exit proof at once, so their process-table reads coalesce. + const paneKeys = new Set([...paneKeysByPtyId.values()].flatMap((keys) => [...keys])) + await Promise.all( + [...paneKeys].map((paneKey) => + this.checkHookAgentPresenceFn?.(paneKey, 0, { settleForSleep: true }) + ) + ) + const hostId = this.getWorkspaceSessionHostIdForWorktree(worktreeId) return captureWorktreeSleepResumeRecords({ worktreeId, paneKeysByPtyId, launchByPtyId: new Map([...ptyIds].map((ptyId) => [ptyId, this.ptysById.get(ptyId)])), readRowsForPane: (paneKey) => this.getAgentProviderSessionRowsForPaneFn?.(paneKey) ?? [], - readSavedRecord: (paneKey) => this.readSavedResumeSource(worktreeId, paneKey), + readSavedRecord: (paneKey) => this.readSavedResumeSource(worktreeId, paneKey, hostId), readIdentity: (paneKey, savedRecord) => this.readPaneAgentIdentity(paneKey, savedRecord), checkAgentPresence: (paneKey, since) => - this.checkHookAgentPresenceFn?.(paneKey, since, { forSleep: true }) ?? - Promise.resolve(null), + this.checkHookAgentPresenceFn?.(paneKey, since) ?? Promise.resolve(null), capturedAt: Date.now() }) }, From 86fde5e5e85483cd51f91a70536f1efbeb538c95 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:20:08 -0800 Subject: [PATCH 095/125] fix(sleep): the pane's agent still running in the background keeps its exit unproven --- .../terminal-pane-status-lifecycle.test.ts | 2 +- .../pane/terminal-pane-status-lifecycle.ts | 4 +-- .../providers/foreground/agent-process.ts | 2 +- .../run-terminal-shell-alone.test.ts | 10 +++++-- .../lifecycle/run-terminal-shell-alone.ts | 26 ++++++++++++------- 5 files changed, 29 insertions(+), 15 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index 428d8384e1ca..53d20a0e08ef 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -14,7 +14,7 @@ vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ vi.mock('../provider/registry', () => ({ getProviderForPty })) vi.mock('../../../runtime/terminal/lifecycle/run-terminal-shell-alone', () => ({ confirmRootShellAloneFromProcessTable: confirmRootShellAlone, - stoppedAgentBlocks: () => () => true + paneAgentProcess: () => () => true })) const platform = process.platform diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 96450efca241..f0c9a8ecea41 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -14,7 +14,7 @@ import { isShellProcess } from '../../../../shared/agent-status/process/shell-pr import { isRemoteExecutionHostPtyId } from '../../../../shared/execution-host/remote-execution-host-pty-id' import { confirmRootShellAloneFromProcessTable, - stoppedAgentBlocks + paneAgentProcess } from '../../../runtime/terminal/lifecycle/run-terminal-shell-alone' export function bindTerminalPaneStatusLifecycle( @@ -203,7 +203,7 @@ async function confirmShellAlone( const rootPid = await readPtyRootPid(provider, ptyId, incarnationId) return rootPid ? confirmRootShellAloneFromProcessTable(rootPid, { - stoppedJobBlocks: stoppedAgentBlocks(agent) + paneAgent: paneAgentProcess(agent) }) : false } diff --git a/src/main/providers/foreground/agent-process.ts b/src/main/providers/foreground/agent-process.ts index deaa69dd515c..7b291eb0bc37 100644 --- a/src/main/providers/foreground/agent-process.ts +++ b/src/main/providers/foreground/agent-process.ts @@ -41,7 +41,7 @@ export type AgentForegroundProcessResolution = { anchorPidForeign?: boolean } -export type ShellForegroundConfirmationOptions = { +type ShellForegroundConfirmationOptions = { readWindowsPtyJobProcessIds?: () => | ReadonlySet | null diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts index 9026252aecdd..0b4ae347ee69 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts @@ -10,7 +10,7 @@ vi.mock( }) ) -const { confirmRootShellAloneFromProcessTable, stoppedAgentBlocks } = +const { confirmRootShellAloneFromProcessTable, paneAgentProcess } = await import('./run-terminal-shell-alone') const SHELL: ProcessTableRow = { pid: 100, ppid: 1, stat: 'Ss+', command: '/bin/zsh' } @@ -33,6 +33,12 @@ it.skipIf(process.platform === 'win32').each([ [LOGIN, { ...LOGIN_SHELL, stat: 'S' }, { pid: 101, ppid: 100, stat: 'S+', command: 'codex' }], false ], + [ + 'a login root, the agent running in the background', + 90, + [LOGIN, LOGIN_SHELL, { pid: 101, ppid: 100, stat: 'S', command: 'codex exec task' }], + false + ], ['no shell under the root', 90, [LOGIN], false], [ 'a login root, an editor stopped before the agent ran', @@ -50,7 +56,7 @@ it.skipIf(process.platform === 'win32').each([ snapshot.mockResolvedValue([...rows]) expect( await confirmRootShellAloneFromProcessTable(rootPid, { - stoppedJobBlocks: stoppedAgentBlocks('codex') + paneAgent: paneAgentProcess('codex') }) ).toBe(expected) }) diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts index af11428daa3b..c8f9daa0d659 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts @@ -1,8 +1,7 @@ /** Read execution-host process tables: daemon shell-ownership changes only after full-screen exit and misses plain failed/finished commands. Observation failure is unproven. */ import { commandExecutable, - confirmShellForegroundProcess, - type ShellForegroundConfirmationOptions + confirmShellForegroundProcess } from '../../../providers/foreground/agent-process' import { getFreshShellForegroundSnapshot } from '../../../../shared/process-observation/tables/process-table-snapshot-reader' import { @@ -13,19 +12,20 @@ import { recognizeAgentProcessFromCommandLine } from '../../../../shared/agent-s import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' import type { TerminalProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' -/** Only a stopped job running the pane's agent (any agent when unknown) keeps its exit unproven; - * a stopped editor or another agent suspended before it does not. */ -export function stoppedAgentBlocks(agent?: string): (row: { command: string }) => boolean { +/** The pane's agent (any agent when unknown) still alive under the shell, stopped or in the + * background, keeps its exit unproven; a stopped editor or another agent suspended before it does not. */ +export function paneAgentProcess(agent?: string): (row: { command: string }) => boolean { return (row) => { const recognized = recognizeAgentProcessFromCommandLine(row.command) return recognized !== null && (!agent || recognized.agent === agent) } } -/** POSIX: the PTY's shell owns the terminal's foreground group and nothing under it is stopped. */ +/** POSIX: the PTY's shell owns the terminal's foreground group and nothing under it is stopped + * (or, given `paneAgent`, no process under it runs the pane's agent, in any state). */ export async function confirmRootShellAloneFromProcessTable( rootPid: number, - options?: Pick + options?: { paneAgent?: (row: { command: string }) => boolean } ): Promise { try { const processIndex = getProcessTableIndex(await getFreshShellForegroundSnapshot()) @@ -34,12 +34,20 @@ export async function confirmRootShellAloneFromProcessTable( return false } // macOS roots each PTY at /usr/bin/login, with the login shell beneath it. - const shell = [{ ...root, depth: 0 }, ...collectDescendantsFromIndex(processIndex, rootPid)] + const tree = [{ ...root, depth: 0 }, ...collectDescendantsFromIndex(processIndex, rootPid)] + const paneAgent = options?.paneAgent + if (paneAgent && tree.some((row) => row.depth > 0 && paneAgent(row))) { + return false + } + const shell = tree .map((row) => ({ depth: row.depth, executable: commandExecutable(row.command) })) .filter((row) => isShellProcess(row.executable)) .sort((left, right) => left.depth - right.depth)[0] return shell - ? await confirmShellForegroundProcess(rootPid, shell.executable, { ...options, processIndex }) + ? await confirmShellForegroundProcess(rootPid, shell.executable, { + processIndex, + ...(paneAgent ? { stoppedJobBlocks: () => false } : {}) + }) : false } catch { return false From 099a7cf20879b3675adc675ccf27d68236773f15 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:26:39 -0800 Subject: [PATCH 096/125] fix(sleep): settle proofs only when the hook server is wired --- .../terminal/stop/worktree-sleep-resume-recording.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 43e98c9f4304..023cf20aff92 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -119,11 +119,10 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu ) // Settle every pane's exit proof at once, so their process-table reads coalesce. const paneKeys = new Set([...paneKeysByPtyId.values()].flatMap((keys) => [...keys])) - await Promise.all( - [...paneKeys].map((paneKey) => - this.checkHookAgentPresenceFn?.(paneKey, 0, { settleForSleep: true }) - ) - ) + const settle = this.checkHookAgentPresenceFn + if (settle) { + await Promise.all([...paneKeys].map((key) => settle(key, 0, { settleForSleep: true }))) + } const hostId = this.getWorkspaceSessionHostIdForWorktree(worktreeId) return captureWorktreeSleepResumeRecords({ worktreeId, From f15281ca7b03497e7d3df9eb7f88105179ef00b2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:28:33 -0800 Subject: [PATCH 097/125] perf(sleep): a capture that read no saved record says so, so identity doesn't route the read again --- src/main/agent-hooks/server/server-state.ts | 12 +++++++----- .../construction/runtime-agent-status-sources.ts | 4 ++-- .../runtime-construction-dependencies.ts | 3 ++- .../terminal/stop/worktree-sleep-resume-records.ts | 5 +++-- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 4d8d7efddc88..29994ee336eb 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -69,20 +69,22 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract this.terminalPaneLifecycle = lifecycle } - /** Which agent conversation this pane holds; see paneAgentIdentity. */ + /** Which agent conversation this pane holds; see paneAgentIdentity. A null `savedRecord` was + * already read and found absent, so it isn't read again. */ paneAgentIdentity( paneKey: string, - savedRecord?: SleepingAgentSessionRecord, - worktreeId = savedRecord?.worktreeId + passedRecord?: SleepingAgentSessionRecord | null, + worktreeId = passedRecord?.worktreeId ): PaneAgentIdentity | null { + let savedRecord = passedRecord ?? undefined const resolved = this.resolvePaneKeyAlias(paneKey) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this server stores enriched accepted rows in the listener's base-typed cache. const legacy = this.state.lastStatusByPaneKey.get(resolved) as | EnrichedAgentHookEventPayload | undefined const row = legacy ?? this.getTmuxSelectedStatus(resolved) - if (!row) { - savedRecord ??= this.terminalPaneLifecycle?.readSavedRecord?.(resolved) + if (!row && passedRecord === undefined) { + savedRecord = this.terminalPaneLifecycle?.readSavedRecord?.(resolved) } worktreeId ??= savedRecord?.worktreeId const exit = diff --git a/src/main/runtime/construction/runtime-agent-status-sources.ts b/src/main/runtime/construction/runtime-agent-status-sources.ts index 7e0fbfcc7001..4ca0035f359b 100644 --- a/src/main/runtime/construction/runtime-agent-status-sources.ts +++ b/src/main/runtime/construction/runtime-agent-status-sources.ts @@ -15,7 +15,7 @@ export abstract class RuntimeAgentStatusSources extends OrcaRuntimeWithTerminalD readPaneAgentIdentity( paneKey: string, - savedRecord?: SleepingAgentSessionRecord, + savedRecord?: SleepingAgentSessionRecord | null, row?: AgentStatusIpcPayload ) { return this.getPaneAgentIdentityFn @@ -27,7 +27,7 @@ export abstract class RuntimeAgentStatusSources extends OrcaRuntimeWithTerminalD this.getAgentProviderSessionRowsForPaneFn?.(paneKey).find( (row) => row.paneKey === paneKey ), - savedRecord, + savedRecord: savedRecord ?? undefined, worktreeId: savedRecord?.worktreeId }) } diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index 8a11616ad7c0..fa87196bcbf3 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -39,9 +39,10 @@ export type RuntimeConstructionDependencies = { onTerminalProgramStatusFacet?: (event: RuntimeTerminalProgramStatusFacetEvent) => void onTerminalSideEffects?: (batch: TerminalSideEffectBatch) => void onClaudeTerminalEvidence?: (paneKey: string, evidence: ClaudeTerminalEvidence) => void + /** `savedRecord` null: the caller already read it and found none. */ getPaneAgentIdentity?: ( paneKey: string, - savedRecord?: SleepingAgentSessionRecord + savedRecord?: SleepingAgentSessionRecord | null ) => ReturnType getAgentStatusSnapshot?: () => AgentStatusIpcPayload[] getAgentStatusSnapshotForPane?: (paneKey: string) => AgentStatusIpcPayload[] diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts index 8a140fca1b72..fcd80592bfda 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts @@ -45,9 +45,10 @@ export async function captureWorktreeSleepResumeRecords(args: { /** Read after each presence probe, so a conversation started during it is the one captured. */ readRowsForPane: (paneKey: string) => readonly AgentStatusIpcPayload[] readSavedRecord?: (paneKey: string) => Promise + /** `savedRecord` null: read and absent. */ readIdentity?: ( paneKey: string, - savedRecord?: SleepingAgentSessionRecord + savedRecord?: SleepingAgentSessionRecord | null ) => ReturnType checkAgentPresence: | ((paneKey: string, exitedSince?: number) => Promise) @@ -71,7 +72,7 @@ export async function captureWorktreeSleepResumeRecords(args: { .catch(() => null) const savedRecord = await args.readSavedRecord?.(paneKey) const identity = args.readIdentity - ? args.readIdentity(paneKey, savedRecord) + ? args.readIdentity(paneKey, savedRecord ?? (args.readSavedRecord ? null : undefined)) : paneAgentIdentity({ paneKey, row: args.readRowsForPane(paneKey).find((candidate) => candidate.paneKey === paneKey), From 35bbecc0ecfedc4acf5ab53707bcd38867451c4b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:39:32 -0800 Subject: [PATCH 098/125] perf(sleep): a quit's exit proof reads the launch through the pane's indexed PTY; retiring an exit routes its host once --- src/main/agent-hooks/server/server-state.ts | 6 +++--- .../terminal-pane-status-lifecycle.test.ts | 2 +- .../pane/terminal-pane-status-lifecycle.ts | 16 +++++++------- .../stop/worktree-sleep-resume-recording.ts | 21 ++++++++++++++----- .../worktree-ps-saved-sleep.test.ts | 2 ++ 5 files changed, 31 insertions(+), 16 deletions(-) diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 29994ee336eb..dd1c3765f8c6 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -51,7 +51,8 @@ import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/l export abstract class AgentHookServerState extends AgentHookServerStateContract { protected terminalPaneLifecycle: { - retireSavedRecord?(paneKey: string, exitedAt: number): void + /** Answers the record that was saved when the agent quit. */ + retireSavedRecord?(paneKey: string, exitedAt: number): SleepingAgentSessionRecord | undefined readSavedRecord?(paneKey: string): SleepingAgentSessionRecord | undefined confirmProcessExit?(paneKey: string, agent: string): Promise /** The host's word that the pane's shell holds its PTY alone, whatever launch it ran; null @@ -132,8 +133,7 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract exitedAt: number ): void { for (const key of paneKeys) { - const saved = this.terminalPaneLifecycle?.readSavedRecord?.(key) - this.terminalPaneLifecycle?.retireSavedRecord?.(key, exitedAt) + const saved = this.terminalPaneLifecycle?.retireSavedRecord?.(key, exitedAt) const agent = status?.agentType ?? saved?.agent const providerSession = status?.providerSession ?? saved?.providerSession if (agent && providerSession) { diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index 53d20a0e08ef..7ebabe5e0476 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -122,7 +122,7 @@ it.each([ const runtime = { resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }), terminalRunFacts: { readLastInputAt: () => null }, - getLaunchStatementForPaneKey: () => currentLaunch + getLaunchStatementForPty: () => currentLaunch } as unknown as OrcaRuntimeService bindTerminalPaneStatusLifecycle(runtime, undefined) const lifecycle = setTerminalPaneLifecycle.mock.lastCall![0] diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index f0c9a8ecea41..8c19551ebaa8 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -24,17 +24,19 @@ export function bindTerminalPaneStatusLifecycle( agentHookServer.setTerminalPaneLifecycle({ retireSavedRecord: (paneKey, exitedAt) => runtime?.retireExitedPaneResume(paneKey, exitedAt), confirmProcessExit: async (paneKey, agent) => { + if (!runtime) { + return false + } try { - const launch = runtime?.getLaunchStatementForPaneKey(paneKey, agent) + const launchOf = () => { + const { ptyId } = resolvePanePty(runtime, paneKey) + return ptyId ? runtime.getLaunchStatementForPty(ptyId, agent) : null + } + const launch = launchOf() // A finished command already retired a gone launch; an unknown one (reattach) needs the proof. return ( launch !== null && - (await paneShellAlone( - runtime, - paneKey, - agent, - () => runtime?.getLaunchStatementForPaneKey(paneKey, agent) === launch - )) === true + (await paneShellAlone(runtime, paneKey, agent, () => launchOf() === launch)) === true ) } catch { return false diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 023cf20aff92..7fcf47057d18 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -46,22 +46,28 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu ) } - /** A confirmed quit retires its saved recovery, which the next coalesced save persists. */ - retireExitedPaneResume(paneKey: string, exitedAt: number): void { + /** A confirmed quit retires its saved recovery, which the next coalesced save persists; answers + * the record saved when it quit, read through the same host route. */ + retireExitedPaneResume( + paneKey: string, + exitedAt: number + ): SleepingAgentSessionRecord | undefined { + this.previousHookStatusByPaneKey.delete(paneKey) const worktreeId = this.getTerminalWorktreeIdForPaneKey(paneKey) if (!worktreeId) { - return + return undefined } + const hostId = this.getWorkspaceSessionHostIdForWorktree(worktreeId) this.inResumeRecordOrder(async () => { this.store?.retireSleepingAgentSession?.( paneKey, (saved) => saved.updatedAt <= exitedAt, - this.getWorkspaceSessionHostIdForWorktree(worktreeId) + hostId ) }).catch((error) => console.warn('[runtime] could not retire an exited agent resume record', error) ) - this.previousHookStatusByPaneKey.delete(paneKey) + return this.store?.getWorkspaceSession?.(hostId)?.sleepingAgentSessionsByPaneKey?.[paneKey] } /** Forgets a pane's saved resume the host refused because a chat is its conversation's home, @@ -168,6 +174,11 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu getLaunchStatementForPaneKey: PaneLaunchConfigOf = (paneKey, agent) => launchStatement(this.getPtyRecordForPaneKey(paneKey), agent) + /** The same word for a pane whose PTY the caller already resolved. */ + getLaunchStatementForPty(ptyId: string, agent: string | null | undefined) { + return launchStatement(this.ptysById.get(ptyId), agent) + } + // Main records accepted status for its panes even without windows, preserving window resume rules; serialize writes so statuses read prior records. recordHookStatusResume(row: AgentStatusIpcPayload): void { const status = resumeStatusFromHookRow(row, this.previousHookStatusByPaneKey.get(row.paneKey)) diff --git a/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts b/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts index c6b6bb4948e4..b62b3e2cb5fb 100644 --- a/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts +++ b/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts @@ -55,7 +55,9 @@ it.each(['claude', 'codex'] as const)( server.setTerminalPaneLifecycle({ readSavedRecord: (paneKey) => session.sleepingAgentSessionsByPaneKey?.[paneKey], retireSavedRecord: (paneKey) => { + const saved = session.sleepingAgentSessionsByPaneKey?.[paneKey] delete session.sleepingAgentSessionsByPaneKey?.[paneKey] + return saved }, ownsProcess: () => true, isStopping: () => false, From fe92eecef3e9a039369b07655879b8f1f6bc12a9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:50:27 -0800 Subject: [PATCH 099/125] perf(terminal): an exit confirmation reuses its presence check's pane keys for suspension --- .../input/terminal-agent-status-and-submission.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts b/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts index 58a614f5124b..f64191f23fa3 100644 --- a/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts +++ b/src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts @@ -76,13 +76,14 @@ export abstract class OrcaRuntimeWithSerializeAgentPromptSubmission extends Orca protected async recheckHookAgentPresenceForPty( ptyId: string, - exitedSince?: number + exitedSince?: number, + paneKeys: Iterable = this.collectAgentStatusPaneKeysForPty(ptyId) ): Promise<'live' | 'unverifiable' | 'exited' | null> { if (!this.checkHookAgentPresenceFn) { return null } const verdicts = await Promise.all( - Array.from(this.collectAgentStatusPaneKeysForPty(ptyId), (paneKey) => + Array.from(paneKeys, (paneKey) => // SAFETY: Keep the original TypeError if collecting pane keys invalidates this callback. exitedSince === undefined ? this.checkHookAgentPresenceFn!(paneKey) @@ -101,14 +102,14 @@ export abstract class OrcaRuntimeWithSerializeAgentPromptSubmission extends Orca protected confirmPtyAgentExit(ptyId: string, recoverCompletedHook = false): void { const current = this.ptysById.get(ptyId) const incarnation = current?.incarnationId - void this.recheckHookAgentPresenceForPty(ptyId).then((verdict) => { + const paneKeys = [...this.collectAgentStatusPaneKeysForPty(ptyId)] + void this.recheckHookAgentPresenceForPty(ptyId, undefined, paneKeys).then((verdict) => { if (this.ptysById.get(ptyId) !== current || current?.incarnationId !== incarnation) { return } - const suspended = Array.from(this.collectAgentStatusPaneKeysForPty(ptyId)).some( - (paneKey) => this.readPaneAgentIdentity(paneKey)?.suspended === true - ) - if (verdict === 'unverifiable' && suspended) { + const suspended = () => + paneKeys.some((paneKey) => this.readPaneAgentIdentity(paneKey)?.suspended === true) + if (verdict === 'unverifiable' && suspended()) { this.ptyTitleTrackersByPtyId.get(ptyId)?.tracker.restoreLastAgentExit() } else if (verdict === null || verdict === 'unverifiable') { this.confirmLegacyPtyAgentExit(ptyId, recoverCompletedHook, verdict === 'unverifiable') From 4e9cc25a3c5c117f6226bcbff04155672e23c06b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:04:16 -0800 Subject: [PATCH 100/125] perf(sleep): materialization passes its absent record; an agent that gains a verifiable process drops its shell-proof retry --- .../agent-hooks/server/agent-hook-server.ts | 19 +++++++++++++++++-- .../agent-session-resume-ownership.ts | 5 +---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 30c4a9b1a757..e889da6a1122 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -110,10 +110,22 @@ export class AgentHookServer extends AgentHookServerLifecycle { /** A sleep settles every pane's exit proofs together, so their fresh process-table reads * coalesce into one; the capture's own presence reads then find them answered. */ async settleExitProofForSleep(paneKey: string): Promise { - await this.unprovenExits.settled(this.resolvePaneKeyAlias(paneKey), true) + const resolved = this.resolvePaneKeyAlias(paneKey) + if (!this.forgetUnprovenExitOfVerifiableOwner(resolved)) { + await this.unprovenExits.settled(resolved, true) + } return null } + /** An agent that now reports a process its presence probe can check needs no shell proof. */ + private forgetUnprovenExitOfVerifiableOwner(resolved: string): boolean { + if (!this.unprovenExits.has(resolved) || !this.hasVerifiableAgentProcess(resolved)) { + return false + } + this.unprovenExits.forget(resolved) + return true + } + async checkAgentPresenceSince( paneKey: string, exitedSince: number @@ -141,7 +153,10 @@ export class AgentHookServer extends AgentHookServerLifecycle { * plain shell, which lands on every prompt, skips the saved-record read. */ protected noticeLaunchlessCommandMark(resolved: string): void { const row = this.state.lastStatusByPaneKey.get(resolved) - if (!this.unprovenExits.has(resolved) && !row) { + if ( + (!this.unprovenExits.has(resolved) && !row) || + this.forgetUnprovenExitOfVerifiableOwner(resolved) + ) { return } const identity = this.paneAgentIdentity(resolved) diff --git a/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts b/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts index b503700ca12e..72de9e564f69 100644 --- a/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts +++ b/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts @@ -70,10 +70,7 @@ export abstract class OrcaRuntimeWithAgentSessionResumeOwnership extends OrcaRun tab: RuntimeMobileSessionTerminalTab ): Promise | undefined> { const stored = this.getPaneSleepingAgentRecord(worktreeId, tab) - const identity = this.readPaneAgentIdentity( - makePaneKey(tab.parentTabId, tab.leafId), - stored ?? undefined - ) + const identity = this.readPaneAgentIdentity(makePaneKey(tab.parentTabId, tab.leafId), stored) if (identity?.ended || identity?.processTopology === 'shared') { return {} } From 1536777baf6afc1a40e8609e10761cc58cc626ab Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:15:23 -0800 Subject: [PATCH 101/125] perf(sleep): spawn, exit and reconcile callbacks check their row and stop gates before reading a saved record --- .../agent-hooks/server/server-pane-sleep.ts | 37 +++++++++++-------- src/main/agent-hooks/server/server-state.ts | 9 +++++ 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index a63bc19793fd..1dfa099e0fb0 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -35,7 +35,11 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF const row = this.state.lastStatusByPaneKey.get(resolved) as | EnrichedAgentHookEventPayload | undefined - if (this.paneAgentIdentity(resolved)?.processTopology === 'shared') { + // Only a live or tmux row can be shared; a saved record never is, so a plain spawn reads none. + if ( + (row ?? this.getTmuxSelectedStatus(resolved)) && + this.paneAgentIdentity(resolved)?.processTopology === 'shared' + ) { this.dropStatusEntry(resolved, { preserveResumeIdentity: false }) this.emitPaneStatusCleared({ paneKey: resolved }) return @@ -85,10 +89,25 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF const legacy = this.state.lastStatusByPaneKey.get(resolved) as | EnrichedAgentHookEventPayload | undefined + const live = legacy ?? this.getTmuxSelectedStatus(resolved) + if ( + live?.paneSleep?.ptyId === ptyId && + (!live.paneSleep.incarnationId || + !incarnationId || + live.paneSleep.incarnationId === incarnationId) + ) { + return true + } + if ( + this.terminalPaneLifecycle?.ownsProcess(resolved, ptyId, incarnationId) !== true || + this.terminalPaneLifecycle.isReversibleStop(ptyId, incarnationId) !== true + ) { + return false + } + // Only a reversible stop of the pane's own process reads its saved conversation. const identity = this.paneAgentIdentity(resolved) const previous: EnrichedAgentHookEventPayload | undefined = - legacy ?? - this.getTmuxSelectedStatus(resolved) ?? + live ?? (identity ? { paneKey: resolved, @@ -101,22 +120,10 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF payload: pickParsedAgentStatusPayload(identity.status) } : undefined) - if ( - previous?.paneSleep?.ptyId === ptyId && - (!previous.paneSleep.incarnationId || - !incarnationId || - previous.paneSleep.incarnationId === incarnationId) - ) { - return true - } - if (this.terminalPaneLifecycle?.ownsProcess(resolved, ptyId, incarnationId) !== true) { - return false - } if ( !previous || !identity || identity.ended || - this.terminalPaneLifecycle?.isReversibleStop(ptyId, incarnationId) !== true || this.terminalPaneLifecycle.isPlaced(previous) !== true ) { return false diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index dd1c3765f8c6..55a427a0f674 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -169,6 +169,15 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract /** A stopping pane's agent keeps its row for the sleep gate, whatever shape it rests in. */ protected preservesStoppingAgent(paneKey: string): boolean { + const resolved = this.resolvePaneKeyAlias(paneKey) + // A saved record never rests in sleep, so only a stopping pane reads it. + if ( + !this.state.lastStatusByPaneKey.has(resolved) && + !this.getTmuxSelectedStatus(resolved) && + this.terminalPaneLifecycle?.isStopping(paneKey) !== true + ) { + return false + } const identity = this.paneAgentIdentity(paneKey) return ( identity !== null && From 52d42fe129603ee3d36a6f6684e1bf4b3349a2fa Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:25:40 -0800 Subject: [PATCH 102/125] perf(sleep): a proven quiet exit reuses its pre-proof identity; row-only reads pass an absent record --- src/main/agent-hooks/server/server-cleanup.ts | 15 ++++++----- .../agent-hooks/server/server-pane-sleep.ts | 5 +--- src/main/agent-hooks/server/server-state.ts | 25 +++++++------------ .../agent-hooks/server/server-tab-cleanup.ts | 9 ++++--- 4 files changed, 25 insertions(+), 29 deletions(-) diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 3848b8018f0e..9a90794d333c 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -24,6 +24,8 @@ export type EndedProcessReconciliationOptions = { confirmedExit?: boolean /** Keep resume identity when the pane survives the agent. */ preserveResumeIdentity?: boolean + /** One pane's identity, already read while its row stayed unchanged. */ + known?: { paneKey: string; identity: ReturnType } } export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { @@ -129,6 +131,10 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { const previous = this.state.lastStatusByPaneKey.get(resolvedPaneKey) as | EnrichedAgentHookEventPayload | undefined + let identity = + options?.known?.paneKey === resolvedPaneKey ? options.known.identity : undefined + const identityOf = () => + identity === undefined ? (identity = this.paneAgentIdentity(resolvedPaneKey)) : identity const endedPresence = options?.endedPresence ?? // A process the presence probe reaches gets its exit from the probe, not a possibly newer @@ -136,16 +142,13 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { // outlives the command that finished at the pane's shell. (options?.confirmedExit && (!previous?.agentPresence?.process || previous.connectionId !== null) && - this.paneAgentIdentity(resolvedPaneKey)?.processTopology !== 'shared' + identityOf()?.processTopology !== 'shared' ? previous ? endedPresenceOf(previous) - : { - agent: this.paneAgentIdentity(resolvedPaneKey)?.status.agentType ?? 'unknown', - ended: true - } + : { agent: identityOf()?.status.agentType ?? 'unknown', ended: true } : undefined) if (endedPresence) { - this.recordPaneAgentExit(paneKey, endedPresence) + this.recordPaneAgentExit(paneKey, endedPresence, identityOf()?.status) } if (!this.hasLiveClaimsForPaneKey(resolvedPaneKey)) { untouched.push(resolvedPaneKey) diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index 1dfa099e0fb0..7722b5a475af 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -36,10 +36,7 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF | EnrichedAgentHookEventPayload | undefined // Only a live or tmux row can be shared; a saved record never is, so a plain spawn reads none. - if ( - (row ?? this.getTmuxSelectedStatus(resolved)) && - this.paneAgentIdentity(resolved)?.processTopology === 'shared' - ) { + if (this.paneAgentIdentity(resolved, null)?.processTopology === 'shared') { this.dropStatusEntry(resolved, { preserveResumeIdentity: false }) this.emitPaneStatusCleared({ paneKey: resolved }) return diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 55a427a0f674..0f71ebd481c3 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -113,10 +113,13 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract : null } - protected recordPaneAgentExit(paneKey: string, endedPresence: AgentProcessPresence): void { + protected recordPaneAgentExit( + paneKey: string, + endedPresence: AgentProcessPresence, + status = this.paneAgentIdentity(paneKey)?.status + ): void { const paneKeys = this.paneKeysWithAliases(paneKey) const exitedAt = Date.now() - const status = this.paneAgentIdentity(paneKey)?.status recordAgentExit(this.agentExitedAtByPaneKey, paneKeys, endedPresence, exitedAt) this.retirePaneResume(paneKeys, status, exitedAt) } @@ -169,21 +172,11 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract /** A stopping pane's agent keeps its row for the sleep gate, whatever shape it rests in. */ protected preservesStoppingAgent(paneKey: string): boolean { - const resolved = this.resolvePaneKeyAlias(paneKey) - // A saved record never rests in sleep, so only a stopping pane reads it. - if ( - !this.state.lastStatusByPaneKey.has(resolved) && - !this.getTmuxSelectedStatus(resolved) && - this.terminalPaneLifecycle?.isStopping(paneKey) !== true - ) { - return false - } - const identity = this.paneAgentIdentity(paneKey) + // A saved record never rests in sleep, so only a stopping pane reads one. + const stopping = this.terminalPaneLifecycle?.isStopping(paneKey) === true + const identity = this.paneAgentIdentity(paneKey, stopping ? undefined : null) return ( - identity !== null && - !identity.ended && - (identity.status.paneSleep !== undefined || - this.terminalPaneLifecycle?.isStopping(paneKey) === true) + identity !== null && !identity.ended && (identity.status.paneSleep !== undefined || stopping) ) } protected canWriteLegacyStatusRow(entry: AgentHookEventPayload): boolean { diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index c9b406b94fcd..ee5f52b69c1e 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -63,7 +63,8 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { private async confirmCommandFinishedExit(resolved: string): Promise { const row = this.state.lastStatusByPaneKey.get(resolved) - const agent = this.paneAgentIdentity(resolved)?.status.agentType + const identity = this.paneAgentIdentity(resolved) + const agent = identity?.status.agentType const alone = await this.terminalPaneLifecycle?.confirmShellAlone?.(resolved, agent) // A newer row may be the same conversation's; only a later proof can settle it. if (this.state.lastStatusByPaneKey.get(resolved) !== row) { @@ -74,7 +75,8 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } this.reconcileEndedProcessForPaneKeys([resolved], { preserveResumeIdentity: true, - confirmedExit: true + confirmedExit: true, + known: { paneKey: resolved, identity } }) return true } @@ -108,7 +110,8 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } this.reconcileEndedProcessForPaneKeys([resolved], { preserveResumeIdentity: true, - confirmedExit: confirmedExit === true + confirmedExit: confirmedExit === true, + known: { paneKey: resolved, identity } }) } From 66eea73528eaf31983cacde71d1984f43e71de2a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:33:23 -0800 Subject: [PATCH 103/125] fix(sleep): a mark on a restored surface whose launch already finished goes to the shell-alone proof, so a typed agent's quit retires it --- .../output/terminal-orchestration-authority.ts | 10 ++++++---- .../stop/worktree-sleep-resume-recording.test.ts | 2 ++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 7fd7ba34cfb1..62237edd0b0b 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -186,12 +186,14 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O const pty = this.retireHeldLaunch(ptyId) const receipt = this.restoredOrchestrationAuthorityByPtyId.get(ptyId) const launch = pty && (pty.launchToken || pty.launchAgent || pty.launchCommandAgent) - if (!pty || (!launch && !receipt)) { + // A restored receipt whose launch already finished retires nothing; an agent typed since is + // the launchless mark's to prove. + if (!pty || (!launch && (!receipt || finishedBefore))) { + this.restoredOrchestrationAuthorityByPtyId.delete(ptyId) this.noticeLaunchlessCommandMark(ptyId, confirmedExit) return } - const exited = confirmedExit === true && Boolean(launch || (receipt && !finishedBefore)) - const retirement = { confirmedExit: exited } + const exited = confirmedExit === true && Boolean(launch || receipt) // Why: collect before the delete below, which drops the restored-authority receipt a // receipt-only pane's key comes from. const paneKeys = this.collectPaneKeysForPty(ptyId) @@ -202,7 +204,7 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O pty.launchAgent = null pty.launchCommandAgent = null for (const paneKey of paneKeys) { - this.retireAgentHookCompatibilityAuthorityFn?.(paneKey, retirement) + this.retireAgentHookCompatibilityAuthorityFn?.(paneKey, { confirmedExit: exited }) } if (changed) { void this.refreshAgentSenderAssociations().catch(console.warn) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index c0b6d81c14c5..219ed324a4b8 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -243,6 +243,8 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini ['macOS suspended, then another command', ['146', '0'], true], ['macOS suspended, then a listing and another command', ['146', 'listing', '0'], true], ['suspended, resumed (fg), then quit', ['148', 'fg', '0'], false], + // A restored receipt whose launch already finished leaves the quit to the shell-alone proof. + ['macOS suspended, resumed (fg), a listing, then quit', ['146', 'fg', 'listing', '0'], false], // A stop-like status is no proof: an agent that exits 146 for real is gone at that mark. ['quit with a stop-like exit status', ['exit146'], false], ['quit, then sleep while its exit proof still runs', ['quit-then-sleep'], false], From b049621beaf79be9242f150b4b01cffeefe93807 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:44:56 -0800 Subject: [PATCH 104/125] fix(hooks): a Codex Stop read from its transcript keeps the tmux host's shared topology --- src/main/agent-hooks/server/server-status-retries.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/agent-hooks/server/server-status-retries.ts b/src/main/agent-hooks/server/server-status-retries.ts index ba727e2e90fc..34e8b4ee0660 100644 --- a/src/main/agent-hooks/server/server-status-retries.ts +++ b/src/main/agent-hooks/server/server-status-retries.ts @@ -1,4 +1,5 @@ import { ClaudeHelperKillPoller } from '../../../shared/agent-hook-listener/providers/claude/transcripts/claude-helper-kill-poller' +import { retainTmuxHookWriterTopology } from './cli-writer-observation' import { pollCodexTranscriptStatus, readCodexTranscriptPoll, @@ -105,11 +106,7 @@ export abstract class AgentHookServerStatusRetries extends AgentHookServerStatus } protected clearAssistantMessageRetry(paneKey: string): void { - const timer = this.assistantMessageRetryTimers.get(paneKey) - if (!timer) { - return - } - clearTimeout(timer) + clearTimeout(this.assistantMessageRetryTimers.get(paneKey)) this.assistantMessageRetryTimers.delete(paneKey) } @@ -242,6 +239,8 @@ export abstract class AgentHookServerStatusRetries extends AgentHookServerStatus if (!normalized) { return } + // A poll's Stop is read from the hook body too, so a tmux host keeps its shared topology. + retainTmuxHookWriterTopology(normalized, body) const update = transcriptPollUpdate(source, original, normalized) const next = update ? this.applyNormalizedStatus(update) : original if (next) { From 7848b715857adc45e3a2e3f795722a8d09ce7b1f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:54:42 -0800 Subject: [PATCH 105/125] fix(sleep): a typed agent's quit on Windows or WSL retires its record, as main's returning shell did --- src/main/agent-hooks/server/agent-hook-server.ts | 8 ++++---- .../stop/worktree-sleep-resume-recording.test.ts | 10 +++++++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index e889da6a1122..5d2b0a8bf324 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -1,4 +1,5 @@ import type { ClaudePermissionHolds } from './claude-permission-hook-hold' +import { isLocalHookConnectionId } from '../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { clearAllListenerCaches } from '../../../shared/agent-hook-listener/listener-state' import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normalization/normalize-hook-payload' import { parseFormEncodedBody } from '../../../shared/agent-hook-listener/request-body' @@ -160,11 +161,10 @@ export class AgentHookServer extends AgentHookServerLifecycle { return } const identity = this.paneAgentIdentity(resolved) - // Main ends no agent at a launchless mark; only a host that can prove the shell alone (local - // POSIX) may, so SSH, WSL and Windows panes aren't armed here. + // Main retired a local pane's record when its shell came back; a POSIX host now proves that, + // and Windows and WSL, which give no proof, let the mark stand. SSH retires it in the window. const unseen = - row?.connectionId === null && - process.platform !== 'win32' && + isLocalHookConnectionId(row?.connectionId) && identity?.ended === false && identity.processTopology !== 'shared' && !this.hasVerifiableAgentProcess(resolved) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index 219ed324a4b8..e15dae95d1cd 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -249,8 +249,10 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini ['quit with a stop-like exit status', ['exit146'], false], ['quit, then sleep while its exit proof still runs', ['quit-then-sleep'], false], ['quit where the host gives no shell proof (remote, Windows)', ['unproven'], false], - ['quit of an agent no Orca launch held (typed at the prompt)', ['typed'], false] + ['quit of an agent no Orca launch held (typed at the prompt)', ['typed'], false], + ['quit of a typed agent on Windows, whose host gives no shell proof', ['typed-windows'], false] ] as const)('%s', async (_, finishes, keepsRecovery) => { + const platform = process.platform vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(1_000) const tick = () => vi.setSystemTime(Date.now() + 1_000) @@ -346,6 +348,12 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini tick() if (status === 'unmarked') { await server.reconcilePaneProcessExit(PANE_KEY) + } else if (status === 'typed-windows') { + Object.defineProperty(process, 'platform', { value: 'win32' }) + shellAlone = null + server.retireProcessAuthority(PANE_KEY, { confirmedExit: true, launchRetired: true }) + await new Promise((resolve) => setImmediate(resolve)) + Object.defineProperty(process, 'platform', { value: platform }) } else if (status === 'typed') { // The runtime's notice for a mark that finds no launch held. server.retireProcessAuthority(PANE_KEY, { confirmedExit: true, launchRetired: true }) From 491d98cffddf3d2919a6feb7a759945133eb006b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:58:21 -0800 Subject: [PATCH 106/125] perf(sleep): a tracked pane whose agent became shared or ended drops its shell-proof retry --- .../agent-hooks/server/agent-hook-server.ts | 37 +++++++++++-------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index 5d2b0a8bf324..d7682e546918 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -107,26 +107,36 @@ export class AgentHookServer extends AgentHookServerLifecycle { } } - /** Include retained exits proven at or after `exitedSince`. */ /** A sleep settles every pane's exit proofs together, so their fresh process-table reads * coalesce into one; the capture's own presence reads then find them answered. */ async settleExitProofForSleep(paneKey: string): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) - if (!this.forgetUnprovenExitOfVerifiableOwner(resolved)) { + if (!this.forgetUnowedExitProof(resolved)) { await this.unprovenExits.settled(resolved, true) } return null } - /** An agent that now reports a process its presence probe can check needs no shell proof. */ - private forgetUnprovenExitOfVerifiableOwner(resolved: string): boolean { - if (!this.unprovenExits.has(resolved) || !this.hasVerifiableAgentProcess(resolved)) { + /** A pane's agent that now reports a process its presence probe can check, became a shared + * host's, or already ended is owed no shell proof. */ + private exitProofOwed(resolved: string): boolean { + const identity = this.paneAgentIdentity(resolved) + return ( + identity?.ended === false && + identity.processTopology !== 'shared' && + !this.hasVerifiableAgentProcess(resolved) + ) + } + + private forgetUnowedExitProof(resolved: string): boolean { + if (!this.unprovenExits.has(resolved) || this.exitProofOwed(resolved)) { return false } this.unprovenExits.forget(resolved) return true } + /** Include retained exits proven at or after `exitedSince`. */ async checkAgentPresenceSince( paneKey: string, exitedSince: number @@ -154,21 +164,16 @@ export class AgentHookServer extends AgentHookServerLifecycle { * plain shell, which lands on every prompt, skips the saved-record read. */ protected noticeLaunchlessCommandMark(resolved: string): void { const row = this.state.lastStatusByPaneKey.get(resolved) - if ( - (!this.unprovenExits.has(resolved) && !row) || - this.forgetUnprovenExitOfVerifiableOwner(resolved) - ) { + if (!this.unprovenExits.has(resolved) && !row) { + return + } + if (!this.exitProofOwed(resolved)) { + this.unprovenExits.forget(resolved) return } - const identity = this.paneAgentIdentity(resolved) // Main retired a local pane's record when its shell came back; a POSIX host now proves that, // and Windows and WSL, which give no proof, let the mark stand. SSH retires it in the window. - const unseen = - isLocalHookConnectionId(row?.connectionId) && - identity?.ended === false && - identity.processTopology !== 'shared' && - !this.hasVerifiableAgentProcess(resolved) - this.unprovenExits.onCommandFinished(resolved, unseen) + this.unprovenExits.onCommandFinished(resolved, isLocalHookConnectionId(row?.connectionId)) } checkAgentPresence(paneKey: string): Promise { From a9aab5e16c30d6aa75877a92c45b5a44468309a6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:27:14 -0800 Subject: [PATCH 107/125] fix(sleep): a quiet shell's return proves a typed agent's exit without a held launch --- .../ipc/pty/pane/terminal-pane-status-lifecycle.test.ts | 4 ++-- src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts | 8 +++----- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index 7ebabe5e0476..22de3f35e1cf 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -52,14 +52,14 @@ it.each([ false ], [ - 'intervening command retired the launch', + 'a typed agent with no launch held, its shell alone', 'darwin', true, 'zsh', undefined, 'gone', false, - false + true ], ['successor launch during inspection', 'darwin', true, 'zsh', undefined, 'held', true, false], [ diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 8c19551ebaa8..11bb73433282 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -32,12 +32,10 @@ export function bindTerminalPaneStatusLifecycle( const { ptyId } = resolvePanePty(runtime, paneKey) return ptyId ? runtime.getLaunchStatementForPty(ptyId, agent) : null } + // A typed agent holds no launch, and a shell without command marks (cmd.exe) says nothing + // when it quits, so the proof stands on its own; a launch replaced meanwhile voids it. const launch = launchOf() - // A finished command already retired a gone launch; an unknown one (reattach) needs the proof. - return ( - launch !== null && - (await paneShellAlone(runtime, paneKey, agent, () => launchOf() === launch)) === true - ) + return (await paneShellAlone(runtime, paneKey, agent, () => launchOf() === launch)) === true } catch { return false } From d81eaa8a66a06828f6e8e4c207fb17bd7d00604b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:34:25 -0800 Subject: [PATCH 108/125] perf(sleep): a quiet shell's return skips the proof for an ended agent or one a command mark is already proving --- src/main/agent-hooks/server/server-tab-cleanup.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index ee5f52b69c1e..cb86eab17713 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -99,11 +99,12 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { const row = this.state.lastStatusByPaneKey.get(resolved) const identity = this.paneAgentIdentity(resolved) const agent = identity?.status.agentType - const shared = identity?.processTopology === 'shared' + // An ended agent needs no proof, and a command mark's proof already owns a tracked pane. const confirmedExit = - identity && + identity?.ended === false && + identity.processTopology !== 'shared' && agent && - !shared && + !this.unprovenExits.has(resolved) && (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, agent)) if (this.state.lastStatusByPaneKey.get(resolved) !== row) { return From 9604c0058da3874be44108a17d945a6afd843698 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:37:30 -0800 Subject: [PATCH 109/125] perf(sleep): one quiet exit reported by both renderer callbacks runs one proof --- .../agent-hooks/agent-status-row-teardown-ipc.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts b/src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts index bacb443c3771..055b2ad84399 100644 --- a/src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts +++ b/src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts @@ -66,15 +66,21 @@ export function registerAgentStatusRowTeardownIpcHandlers(): void { } }) + const reconcilingPaneKeys = new Set() ipcMain.on('agentStatus:reconcileEndedProcess', (_event, paneKey: unknown) => { if (typeof paneKey !== 'string' || !isValidPaneKey(paneKey)) { return } try { - // Confirmed process exit must clear latches with the row (STA-4612). - void agentHookServer - .reconcilePaneProcessExit(paneKey) - .catch((err) => console.warn('[agent-hooks] reconcilePaneProcessExit failed:', err)) + // Confirmed process exit must clear latches with the row (STA-4612). The shell-settle and + // row-retire callbacks both report one exit; one proof answers both. + if (!reconcilingPaneKeys.has(paneKey)) { + reconcilingPaneKeys.add(paneKey) + void agentHookServer + .reconcilePaneProcessExit(paneKey) + .catch((err) => console.warn('[agent-hooks] reconcilePaneProcessExit failed:', err)) + .finally(() => reconcilingPaneKeys.delete(paneKey)) + } clearMigrationUnsupportedPtysForPaneKey(paneKey) } catch (err) { console.warn('[agent-hooks] reconcileEndedProcessForPaneKeys failed:', err) From 8e291717bae675b45e1073226f45c1304b5f9437 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:40:52 -0800 Subject: [PATCH 110/125] fix(sleep): a live process whose argv the host couldn't read keeps an agent's exit unproven --- .../lifecycle/run-terminal-shell-alone.test.ts | 12 ++++++++++++ .../terminal/lifecycle/run-terminal-shell-alone.ts | 12 +++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts index 0b4ae347ee69..2f407b5e15a7 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts @@ -39,6 +39,18 @@ it.skipIf(process.platform === 'win32').each([ [LOGIN, LOGIN_SHELL, { pid: 101, ppid: 100, stat: 'S', command: 'codex exec task' }], false ], + [ + 'a login root, a stopped process whose argv was unreadable', + 90, + [LOGIN, LOGIN_SHELL, { pid: 101, ppid: 100, stat: 'T', command: '(codex)' }], + false + ], + [ + 'a login root, an exited agent not yet reaped', + 90, + [LOGIN, LOGIN_SHELL, { pid: 101, ppid: 100, stat: 'Z', command: '(codex)' }], + true + ], ['no shell under the root', 90, [LOGIN], false], [ 'a login root, an editor stopped before the agent ran', diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts index c8f9daa0d659..3b6314363ee6 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts @@ -13,9 +13,15 @@ import { isShellProcess } from '../../../../shared/agent-status/process/shell-pr import type { TerminalProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' /** The pane's agent (any agent when unknown) still alive under the shell, stopped or in the - * background, keeps its exit unproven; a stopped editor or another agent suspended before it does not. */ -export function paneAgentProcess(agent?: string): (row: { command: string }) => boolean { + * background, keeps its exit unproven; a stopped editor or another agent suspended before it does + * not. A live process whose argv the host couldn't read (`(comm)`) may be the agent, so it does. */ +export function paneAgentProcess( + agent?: string +): (row: { command: string; stat?: string }) => boolean { return (row) => { + if (/^\(.*\)$/.test(row.command.trim())) { + return row.stat?.includes('Z') !== true + } const recognized = recognizeAgentProcessFromCommandLine(row.command) return recognized !== null && (!agent || recognized.agent === agent) } @@ -25,7 +31,7 @@ export function paneAgentProcess(agent?: string): (row: { command: string }) => * (or, given `paneAgent`, no process under it runs the pane's agent, in any state). */ export async function confirmRootShellAloneFromProcessTable( rootPid: number, - options?: { paneAgent?: (row: { command: string }) => boolean } + options?: { paneAgent?: (row: { command: string; stat?: string }) => boolean } ): Promise { try { const processIndex = getProcessTableIndex(await getFreshShellForegroundSnapshot()) From 9a6496033e4966cd45e56b9b48abc4c248a08c59 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:48:34 -0800 Subject: [PATCH 111/125] perf(sleep): cold root-PID lookups started together share one owner inventory --- .../pane/terminal-pane-status-lifecycle.ts | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 11bb73433282..b758a2edfee2 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -170,6 +170,28 @@ async function paneShellAlone( * name, which a live unrecognized agent shares. */ // Spawn and adoption publish the shell PID; a host that published none pays one targeted // inventory per PTY incarnation, whose answer (a root or none) lasts until the PTY's teardown. +type PtyProvider = ReturnType +const pendingRootLookups = new Map< + PtyProvider, + { ptyIds: Set; result: ReturnType | Promise } +>() + +/** Cold lookups started together (a sleep's proofs) share one owner inventory. */ +function lookupRootPids(provider: PtyProvider, ptyId: string) { + let batch = pendingRootLookups.get(provider) + if (!batch) { + const ptyIds = new Set() + const result = Promise.resolve().then(() => { + pendingRootLookups.delete(provider) + return provider.listProcesses({ ptyIds: [...ptyIds], targetOwnerOnly: true }) + }) + batch = { ptyIds, result: result.catch(() => null) } + pendingRootLookups.set(provider, batch) + } + batch.ptyIds.add(ptyId) + return batch.result +} + async function readPtyRootPid( provider: ReturnType, ptyId: string, @@ -183,9 +205,7 @@ async function readPtyRootPid( if (known && known.incarnationId === incarnationId) { return known.rootPid ?? undefined } - const processes = await provider - .listProcesses({ ptyIds: [ptyId], targetOwnerOnly: true }) - .catch(() => null) + const processes = await lookupRootPids(provider, ptyId) const rootPid = processes?.find((entry) => entry.id === ptyId)?.rootProcessId if (processes && incarnationId && ptyIncarnationById.get(ptyId) === incarnationId) { ptyFallbackRootPidById.set(ptyId, { incarnationId, rootPid: rootPid ?? null }) From 0af573d8270c3fec2fdc75622ccb5a64cbf6f8f5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:57:29 -0800 Subject: [PATCH 112/125] perf(sleep): a batch of cold root-PID lookups indexes its shared reply once --- .../ipc/pty/pane/terminal-pane-status-lifecycle.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index b758a2edfee2..56bb73e91e9d 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -173,7 +173,7 @@ async function paneShellAlone( type PtyProvider = ReturnType const pendingRootLookups = new Map< PtyProvider, - { ptyIds: Set; result: ReturnType | Promise } + { ptyIds: Set; result: Promise | null> } >() /** Cold lookups started together (a sleep's proofs) share one owner inventory. */ @@ -185,7 +185,11 @@ function lookupRootPids(provider: PtyProvider, ptyId: string) { pendingRootLookups.delete(provider) return provider.listProcesses({ ptyIds: [...ptyIds], targetOwnerOnly: true }) }) - batch = { ptyIds, result: result.catch(() => null) } + // One index of the shared reply serves every caller in the batch. + const rootPids = result.then( + (rows) => new Map(rows.map((row) => [row.id, row.rootProcessId] as const)) + ) + batch = { ptyIds, result: rootPids.catch(() => null) } pendingRootLookups.set(provider, batch) } batch.ptyIds.add(ptyId) @@ -205,9 +209,9 @@ async function readPtyRootPid( if (known && known.incarnationId === incarnationId) { return known.rootPid ?? undefined } - const processes = await lookupRootPids(provider, ptyId) - const rootPid = processes?.find((entry) => entry.id === ptyId)?.rootProcessId - if (processes && incarnationId && ptyIncarnationById.get(ptyId) === incarnationId) { + const rootPids = await lookupRootPids(provider, ptyId) + const rootPid = rootPids?.get(ptyId) + if (rootPids && incarnationId && ptyIncarnationById.get(ptyId) === incarnationId) { ptyFallbackRootPidById.set(ptyId, { incarnationId, rootPid: rootPid ?? null }) } return rootPid From 7f4387e17ca5928d82290cae05a5b92ea5867ba9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:08:57 -0800 Subject: [PATCH 113/125] fix(sleep): a quiet return defers to a running mark proof, a second exit report reruns once, and an unreadable argv blocks only as the agent --- .../agent-hooks/server/server-tab-cleanup.ts | 11 ++++--- .../agent-status-row-teardown-ipc.ts | 32 +++++++++++++------ .../run-terminal-shell-alone.test.ts | 6 ++++ .../lifecycle/run-terminal-shell-alone.ts | 10 +++--- 4 files changed, 40 insertions(+), 19 deletions(-) diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index cb86eab17713..0548fe5ef8a5 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -91,20 +91,21 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { /** Shells without command marks need the owning host's process-tree proof. */ async reconcilePaneProcessExit(paneKey: string): Promise { const resolved = this.resolvePaneKeyAlias(paneKey) - // A verifiable process answers for itself (exited, stopped or live); the quiet shell proves nothing. - if (this.hasVerifiableAgentProcess(resolved)) { - await this.checkAgentPresence(resolved) + // A verifiable process answers for itself (exited, stopped or live); the quiet shell proves + // nothing. A command mark's proof owns a tracked pane; reconciling here would forget it. + const tracked = this.unprovenExits.has(resolved) + if (tracked || this.hasVerifiableAgentProcess(resolved)) { + await (tracked ? this.unprovenExits.settled(resolved) : this.checkAgentPresence(resolved)) return } const row = this.state.lastStatusByPaneKey.get(resolved) const identity = this.paneAgentIdentity(resolved) const agent = identity?.status.agentType - // An ended agent needs no proof, and a command mark's proof already owns a tracked pane. + // An ended agent needs no proof. const confirmedExit = identity?.ended === false && identity.processTopology !== 'shared' && agent && - !this.unprovenExits.has(resolved) && (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, agent)) if (this.state.lastStatusByPaneKey.get(resolved) !== row) { return diff --git a/src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts b/src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts index 055b2ad84399..aa954ccaae91 100644 --- a/src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts +++ b/src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts @@ -66,21 +66,33 @@ export function registerAgentStatusRowTeardownIpcHandlers(): void { } }) - const reconcilingPaneKeys = new Set() + // The shell-settle and row-retire callbacks both report one exit: a report during a running + // reconcile runs once after it (which skips the proof if the first one ended the agent). + const rerunByPaneKey = new Map() + const reconcilePaneExit = (paneKey: string): void => { + if (rerunByPaneKey.has(paneKey)) { + rerunByPaneKey.set(paneKey, true) + return + } + rerunByPaneKey.set(paneKey, false) + void agentHookServer + .reconcilePaneProcessExit(paneKey) + .catch((err) => console.warn('[agent-hooks] reconcilePaneProcessExit failed:', err)) + .finally(() => { + const rerun = rerunByPaneKey.get(paneKey) + rerunByPaneKey.delete(paneKey) + if (rerun) { + reconcilePaneExit(paneKey) + } + }) + } ipcMain.on('agentStatus:reconcileEndedProcess', (_event, paneKey: unknown) => { if (typeof paneKey !== 'string' || !isValidPaneKey(paneKey)) { return } try { - // Confirmed process exit must clear latches with the row (STA-4612). The shell-settle and - // row-retire callbacks both report one exit; one proof answers both. - if (!reconcilingPaneKeys.has(paneKey)) { - reconcilingPaneKeys.add(paneKey) - void agentHookServer - .reconcilePaneProcessExit(paneKey) - .catch((err) => console.warn('[agent-hooks] reconcilePaneProcessExit failed:', err)) - .finally(() => reconcilingPaneKeys.delete(paneKey)) - } + // Confirmed process exit must clear latches with the row (STA-4612). + reconcilePaneExit(paneKey) clearMigrationUnsupportedPtysForPaneKey(paneKey) } catch (err) { console.warn('[agent-hooks] reconcileEndedProcessForPaneKeys failed:', err) diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts index 2f407b5e15a7..ccb86ae610a4 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts @@ -45,6 +45,12 @@ it.skipIf(process.platform === 'win32').each([ [LOGIN, LOGIN_SHELL, { pid: 101, ppid: 100, stat: 'T', command: '(codex)' }], false ], + [ + 'a login root, a stopped sudo whose argv was unreadable', + 90, + [LOGIN, LOGIN_SHELL, { pid: 101, ppid: 100, stat: 'T', command: '(sudo)' }], + true + ], [ 'a login root, an exited agent not yet reaped', 90, diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts index 3b6314363ee6..69751a1c03c6 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts @@ -14,15 +14,17 @@ import type { TerminalProcessInspection } from '../../../../shared/terminal/pty/ /** The pane's agent (any agent when unknown) still alive under the shell, stopped or in the * background, keeps its exit unproven; a stopped editor or another agent suspended before it does - * not. A live process whose argv the host couldn't read (`(comm)`) may be the agent, so it does. */ + * not. */ export function paneAgentProcess( agent?: string ): (row: { command: string; stat?: string }) => boolean { return (row) => { - if (/^\(.*\)$/.test(row.command.trim())) { - return row.stat?.includes('Z') !== true + // A live process whose argv the host couldn't read shows as `(comm)`; its name still tells. + const unreadable = /^\((.*)\)$/.exec(row.command.trim()) + if (unreadable && row.stat?.includes('Z')) { + return false } - const recognized = recognizeAgentProcessFromCommandLine(row.command) + const recognized = recognizeAgentProcessFromCommandLine(unreadable?.[1] ?? row.command) return recognized !== null && (!agent || recognized.agent === agent) } } From 91b13545024bb31bc47cc1882525d196a857715f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:08:58 -0800 Subject: [PATCH 114/125] perf(sleep): a host that published no shell PID gives no proof, so no exit proof inventories a daemon --- .../terminal-pane-status-lifecycle.test.ts | 8 +-- .../pane/terminal-pane-status-lifecycle.ts | 67 +++---------------- src/main/ipc/pty/provider/ownership-state.ts | 6 -- src/main/ipc/pty/provider/state-cleanup.ts | 8 +-- 4 files changed, 15 insertions(+), 74 deletions(-) diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts index 22de3f35e1cf..1c13231485bc 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts @@ -12,6 +12,9 @@ vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { setTerminalPaneLifecycle, pruneUnplacedSleepingPanes: () => {} } })) vi.mock('../provider/registry', () => ({ getProviderForPty })) +vi.mock('../../../memory/pty-registry', () => ({ + getRegisteredPtyPid: (ptyId: string) => (ptyId === 'pty-1' ? 4242 : null) +})) vi.mock('../../../runtime/terminal/lifecycle/run-terminal-shell-alone', () => ({ confirmRootShellAloneFromProcessTable: confirmRootShellAlone, paneAgentProcess: () => () => true @@ -109,7 +112,6 @@ it.each([ rootPid === 4242 ? proveShellAlone() : false ) getProviderForPty.mockReturnValue({ - listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }], confirmShellForeground: os === 'win32' ? proveShellAlone : async () => true, // Windows answers from its job census; a foreground name alone is not that census. inspectProcess: async () => ({ @@ -144,9 +146,7 @@ it('does not count a shell-alone proof once input reached the PTY while it ran', } return true }) - getProviderForPty.mockReturnValue({ - listProcesses: async () => [{ id: 'pty-1', rootProcessId: 4242 }] - }) + getProviderForPty.mockReturnValue({}) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the proof only resolves the pane and reads its input facts. const runtime = { resolveTerminalPane: () => ({ ptyId: 'pty-1', incarnationId: 'birth-1' }), diff --git a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts index 56bb73e91e9d..d05a6e51b770 100644 --- a/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts +++ b/src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts @@ -5,7 +5,7 @@ import { toSshExecutionHostId } from '../../../../shared/execution-host/executio import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import { paneKeyPtyId } from './key-state' -import { ptyFallbackRootPidById, ptyIncarnationById } from '../provider/ownership-state' +import { ptyIncarnationById } from '../provider/ownership-state' import { getRegisteredPtyPid } from '../../../memory/pty-registry' import { isLocalHookConnectionId } from '../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' import { getProviderForPty } from '../provider/registry' @@ -35,7 +35,9 @@ export function bindTerminalPaneStatusLifecycle( // A typed agent holds no launch, and a shell without command marks (cmd.exe) says nothing // when it quits, so the proof stands on its own; a launch replaced meanwhile voids it. const launch = launchOf() - return (await paneShellAlone(runtime, paneKey, agent, () => launchOf() === launch)) === true + return ( + (await paneShellAlone(runtime, paneKey, agent, () => launchOf() === launch)) !== false + ) } catch { return false } @@ -168,68 +170,19 @@ async function paneShellAlone( * table instead, local or daemon alike. Windows shells stop no jobs, so the host's job census * finding no child beside a shell foreground suffices there. Never fall back to a foreground * name, which a live unrecognized agent shares. */ -// Spawn and adoption publish the shell PID; a host that published none pays one targeted -// inventory per PTY incarnation, whose answer (a root or none) lasts until the PTY's teardown. -type PtyProvider = ReturnType -const pendingRootLookups = new Map< - PtyProvider, - { ptyIds: Set; result: Promise | null> } ->() - -/** Cold lookups started together (a sleep's proofs) share one owner inventory. */ -function lookupRootPids(provider: PtyProvider, ptyId: string) { - let batch = pendingRootLookups.get(provider) - if (!batch) { - const ptyIds = new Set() - const result = Promise.resolve().then(() => { - pendingRootLookups.delete(provider) - return provider.listProcesses({ ptyIds: [...ptyIds], targetOwnerOnly: true }) - }) - // One index of the shared reply serves every caller in the batch. - const rootPids = result.then( - (rows) => new Map(rows.map((row) => [row.id, row.rootProcessId] as const)) - ) - batch = { ptyIds, result: rootPids.catch(() => null) } - pendingRootLookups.set(provider, batch) - } - batch.ptyIds.add(ptyId) - return batch.result -} - -async function readPtyRootPid( - provider: ReturnType, - ptyId: string, - incarnationId: string | undefined -): Promise { - const registered = getRegisteredPtyPid(ptyId) - if (registered) { - return registered - } - const known = ptyFallbackRootPidById.get(ptyId) - if (known && known.incarnationId === incarnationId) { - return known.rootPid ?? undefined - } - const rootPids = await lookupRootPids(provider, ptyId) - const rootPid = rootPids?.get(ptyId) - if (rootPids && incarnationId && ptyIncarnationById.get(ptyId) === incarnationId) { - ptyFallbackRootPidById.set(ptyId, { incarnationId, rootPid: rootPid ?? null }) - } - return rootPid -} - async function confirmShellAlone( ptyId: string, incarnationId?: string, agent?: string -): Promise { +): Promise { const provider = getProviderForPty(ptyId) if (process.platform !== 'win32') { - const rootPid = await readPtyRootPid(provider, ptyId, incarnationId) + // Spawn and adoption publish the shell's PID; a host that published none (an older daemon) + // gives no proof, so the mark stands there, as on main. + const rootPid = getRegisteredPtyPid(ptyId) return rootPid - ? confirmRootShellAloneFromProcessTable(rootPid, { - paneAgent: paneAgentProcess(agent) - }) - : false + ? confirmRootShellAloneFromProcessTable(rootPid, { paneAgent: paneAgentProcess(agent) }) + : null } if ((await provider.confirmShellForeground?.(ptyId)) === true) { return true diff --git a/src/main/ipc/pty/provider/ownership-state.ts b/src/main/ipc/pty/provider/ownership-state.ts index 505c1270bb16..f2cd9fcdb350 100644 --- a/src/main/ipc/pty/provider/ownership-state.ts +++ b/src/main/ipc/pty/provider/ownership-state.ts @@ -8,12 +8,6 @@ import { // Later write/resize/kill requests carry only PTY ID; preserve its execution host for routing. export const ptyOwnership = new Map() export const ptyIncarnationById = new Map() -/** Exit proofs' root process for a live PTY incarnation whose host published no PID; null when - * its inventory had none. Teardown drops it with the PTY. */ -export const ptyFallbackRootPidById = new Map< - string, - { incarnationId: string; rootPid: number | null } ->() export function isCurrentPtyExit(payload: { id: string; incarnationId?: string }): boolean { const current = ptyIncarnationById.get(payload.id) diff --git a/src/main/ipc/pty/provider/state-cleanup.ts b/src/main/ipc/pty/provider/state-cleanup.ts index 89e2348d87ed..71374e4e2bbb 100644 --- a/src/main/ipc/pty/provider/state-cleanup.ts +++ b/src/main/ipc/pty/provider/state-cleanup.ts @@ -12,12 +12,7 @@ import { } from '../delivery/pty-hidden-delivery-gate' import { agentSessionOwners } from '../pane/agent-session-owners' import { paneKeyPtyId, paneKeyTeardownListeners, ptyPaneKey } from '../pane/key-state' -import { - getPtyIdsForConnection, - ptyFallbackRootPidById, - ptyIncarnationById, - ptyOwnership -} from './ownership-state' +import { getPtyIdsForConnection, ptyIncarnationById, ptyOwnership } from './ownership-state' import { clearBackgroundedDeliverySyncForPty } from './listener-lifecycle' import { activeRendererPtys, @@ -61,7 +56,6 @@ export function clearProviderPtyState( piTitlebarExtensionService.clearPty(id) ptySizes.delete(id) ptyIncarnationById.delete(id) - ptyFallbackRootPidById.delete(id) lastInputAtByPty.delete(id) interactiveOutputCharsByPty.delete(id) const activeChanged = activeRendererPtys.delete(id) From 0655561ce2510a72681c532611adc0bcee7472a8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:17:56 -0800 Subject: [PATCH 115/125] fix(sleep): the window learns a tmux-hosted conversation is shared, so it writes no checkpoint for it --- .../stop/hook-status-resume-records.ts | 14 +- .../main-window-agent-status.test.ts | 39 ++++++ .../main-window/main-window-agent-status.ts | 125 +++++++++--------- .../agent-status-live-entry-builder.ts | 6 +- 4 files changed, 118 insertions(+), 66 deletions(-) create mode 100644 src/main/startup/main-window/main-window-agent-status.test.ts diff --git a/src/main/runtime/terminal/stop/hook-status-resume-records.ts b/src/main/runtime/terminal/stop/hook-status-resume-records.ts index 423fcff4cf17..6944668ad96d 100644 --- a/src/main/runtime/terminal/stop/hook-status-resume-records.ts +++ b/src/main/runtime/terminal/stop/hook-status-resume-records.ts @@ -21,7 +21,10 @@ import type { CommandOf } from '../../../../shared/workspace-layout/workspace-la import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' /** The part of a pane's previous status the next one may inherit its provider session from. */ -export type PreviousHookStatus = Pick +export type PreviousHookStatus = Pick< + ResumeRecordStatus, + 'agentType' | 'state' | 'providerSession' | 'sharedHost' +> /** Main's word on a pane's launch as `agent`: its note, null for none, undefined when main can't tell. */ export type PaneLaunchConfigOf = ( @@ -64,9 +67,9 @@ export function resumeStatusFromHookRow( if (row.providerSessionOnly || row.structuredHost) { return null } - const providerSession = - normalizeAgentProviderSession(row.providerSession) ?? - (canReuseStatusProviderSession(previous, row) ? previous.providerSession : undefined) + const own = normalizeAgentProviderSession(row.providerSession) + const reused = !own && canReuseStatusProviderSession(previous, row) + const providerSession = own ?? (reused ? previous.providerSession : undefined) return { paneKey: row.paneKey, agentType: row.agentType, @@ -79,7 +82,8 @@ export function resumeStatusFromHookRow( lastAssistantMessage: row.lastAssistantMessage, interrupted: row.interrupted, ...(row.mainAgent ? { mainAgent: row.mainAgent } : {}), - ...(row.sharedHost ? { sharedHost: true as const } : {}), + // A status that reuses the pane's session keeps that session's tmux host. + ...(row.sharedHost || (reused && previous.sharedHost) ? { sharedHost: true as const } : {}), ...(row.worktreeId ? { worktreeId: row.worktreeId } : {}) } } diff --git a/src/main/startup/main-window/main-window-agent-status.test.ts b/src/main/startup/main-window/main-window-agent-status.test.ts new file mode 100644 index 000000000000..0706939f30b8 --- /dev/null +++ b/src/main/startup/main-window/main-window-agent-status.test.ts @@ -0,0 +1,39 @@ +import { expect, it, vi } from 'vitest' +import type { BrowserWindow } from 'electron' +import { retainTmuxWriterTopology } from '../../agent-hooks/server/cli-writer-observation' + +const { setListener, send } = vi.hoisted(() => ({ setListener: vi.fn(), send: vi.fn() })) +vi.mock('../../agent-hooks/server/agent-hook-server', () => ({ + agentHookServer: { setListener, setPaneStatusClearListener: () => {} } +})) +vi.mock('../../window/dashboard-popout-window', () => ({ getDashboardPopoutWindow: () => null })) +vi.mock('./synthetic-title-runtime', () => ({ stopSyntheticTitleSpinnerTimer: () => {} })) +vi.mock('../main-process-state', () => ({ + mainProcessState: { mainWindow: { isDestroyed: () => false, webContents: { send } } } +})) + +const { installMainWindowAgentStatusListeners } = await import('./main-window-agent-status') + +it('tells the window that a tmux-hosted conversation is shared, so it writes no checkpoint', () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the listener only forwards status to this window. + installMainWindowAgentStatusListeners({ + window: {} as BrowserWindow, + onRecordAgentState: () => {} + }) + const providerSession = { key: 'session_id' as const, id: 'codex-in-tmux' } + retainTmuxWriterTopology(providerSession) + setListener.mock.lastCall![0]({ + paneKey: 'tab-1:pane-1', + tabId: 'tab-1', + worktreeId: 'wt-1', + connectionId: null, + receivedAt: 1, + stateStartedAt: 1, + payload: { state: 'done', prompt: '', agentType: 'codex' }, + providerSession + }) + expect(send).toHaveBeenCalledWith( + 'agentStatus:set', + expect.objectContaining({ paneKey: 'tab-1:pane-1', sharedHost: true }) + ) +}) diff --git a/src/main/startup/main-window/main-window-agent-status.ts b/src/main/startup/main-window/main-window-agent-status.ts index bfcc028a8e84..7c5a25dd8013 100644 --- a/src/main/startup/main-window/main-window-agent-status.ts +++ b/src/main/startup/main-window/main-window-agent-status.ts @@ -6,6 +6,7 @@ import { getDashboardPopoutWindow } from '../../window/dashboard-popout-window' import { stopSyntheticTitleSpinnerTimer } from './synthetic-title-runtime' import { mainProcessState as state } from '../main-process-state' import { pickHostTurnEnd } from '../../../shared/agent-status/contracts/agent-status-types' +import { cliWriterTopology } from '../../agent-hooks/server/cli-writer-topology' export type MainWindowAgentStatusOptions = { window: BrowserWindow @@ -13,8 +14,8 @@ export type MainWindowAgentStatusOptions = { } export function installMainWindowAgentStatusListeners(options: MainWindowAgentStatusOptions): void { - agentHookServer.setListener( - ({ + agentHookServer.setListener((row) => { + const { paneKey, tabId, worktreeId, @@ -41,77 +42,81 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt agentIdentity, identityOnly, agentPresence - }) => { - if (state.mainWindow?.isDestroyed()) { - return - } - // Renderer still owns structured rows; forwarding would give each pane key two writers until that bridge retires. - if (structuredHost) { - return - } - const launchConfig = state.runtime?.getLaunchStatementForPaneKey(paneKey, payload.agentType) - if (providerSessionOnly) { - // Idle Pi session_start only refreshes resume identity; skip titles, telemetry and status UI. - state.mainWindow?.webContents.send('agentStatus:set', { - ...payload, - paneKey, - ...(launchToken ? { launchToken } : {}), - ...(launchConfig !== undefined ? { launchConfig } : {}), - tabId, - worktreeId, - connectionId, - receivedAt, - ...(evidenceObservedAt !== undefined ? { evidenceObservedAt } : {}), - stateStartedAt, - ...(providerSession ? { providerSession } : {}), - ...(observation ? { observation } : {}), - providerSessionOnly: true - }) - return - } - const runtime = state.runtime - const orchestration = runtime?.getAgentStatusOrchestrationContextForPaneKey(paneKey) - const terminalHandle = runtime?.getAgentStatusTerminalHandleForPaneKey(paneKey) - const statusEvent = { - ...(authorityRestartId && isReplay !== true ? { authorityRestartId } : {}), + } = row + if (state.mainWindow?.isDestroyed()) { + return + } + // Renderer still owns structured rows; forwarding would give each pane key two writers until that bridge retires. + if (structuredHost) { + return + } + const launchConfig = state.runtime?.getLaunchStatementForPaneKey(paneKey, payload.agentType) + // Topology rides the binding as a symbol the IPC clone drops; a tmux host's conversation must + // reach the window as shared so it leaves no resume checkpoint. + const shared = cliWriterTopology(row) === 'shared' ? { sharedHost: true as const } : {} + if (providerSessionOnly) { + // Idle Pi session_start only refreshes resume identity; skip titles, telemetry and status UI. + state.mainWindow?.webContents.send('agentStatus:set', { ...payload, paneKey, ...(launchToken ? { launchToken } : {}), ...(launchConfig !== undefined ? { launchConfig } : {}), - ...(terminalHandle ? { terminalHandle } : {}), tabId, worktreeId, connectionId, receivedAt, ...(evidenceObservedAt !== undefined ? { evidenceObservedAt } : {}), stateStartedAt, - ...(turnStartedAt !== undefined ? { turnStartedAt } : {}), - ...pickHostTurnEnd({ turnEndedAt, turnEndDisposition }), ...(providerSession ? { providerSession } : {}), - ...(publishedOrcaSessionId(agentIdentity) !== undefined - ? { orcaSessionId: publishedOrcaSessionId(agentIdentity) } - : {}), - ...(promptInteractionKey ? { promptInteractionKey } : {}), - ...(restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), ...(observation ? { observation } : {}), - ...(orchestration ? { orchestration } : {}), - ...(programStatus ? { programStatus } : {}), - ...(programStatusOnly === true ? { programStatusOnly: true } : {}), - ...(paneSleep ? { paneSleep } : {}), - ...(agentPresence?.session && !agentPresence.ended - ? { paneOwner: { agent: agentPresence.agent, session: agentPresence.session } } - : {}), - // Mark reconnect replays so cached completions do not notify again. - ...(isReplay === true ? { isReplay: true } : {}) - } - state.mainWindow?.webContents.send('agentStatus:set', statusEvent) - getDashboardPopoutWindow()?.webContents.send('agentStatus:set', statusEvent) - // A facet-only republish (progress tick) or a settled id is not a state the agent entered. - if (programStatusOnly !== true && identityOnly !== true) { - options.onRecordAgentState(payload.agentType ?? 'unknown', payload.state) - } + ...shared, + providerSessionOnly: true + }) + return + } + const runtime = state.runtime + const orchestration = runtime?.getAgentStatusOrchestrationContextForPaneKey(paneKey) + const terminalHandle = runtime?.getAgentStatusTerminalHandleForPaneKey(paneKey) + const statusEvent = { + ...(authorityRestartId && isReplay !== true ? { authorityRestartId } : {}), + ...payload, + paneKey, + ...(launchToken ? { launchToken } : {}), + ...(launchConfig !== undefined ? { launchConfig } : {}), + ...(terminalHandle ? { terminalHandle } : {}), + tabId, + worktreeId, + connectionId, + receivedAt, + ...(evidenceObservedAt !== undefined ? { evidenceObservedAt } : {}), + stateStartedAt, + ...(turnStartedAt !== undefined ? { turnStartedAt } : {}), + ...pickHostTurnEnd({ turnEndedAt, turnEndDisposition }), + ...(providerSession ? { providerSession } : {}), + ...(publishedOrcaSessionId(agentIdentity) !== undefined + ? { orcaSessionId: publishedOrcaSessionId(agentIdentity) } + : {}), + ...(promptInteractionKey ? { promptInteractionKey } : {}), + ...(restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), + ...(observation ? { observation } : {}), + ...(orchestration ? { orchestration } : {}), + ...(programStatus ? { programStatus } : {}), + ...(programStatusOnly === true ? { programStatusOnly: true } : {}), + ...(paneSleep ? { paneSleep } : {}), + ...shared, + ...(agentPresence?.session && !agentPresence.ended + ? { paneOwner: { agent: agentPresence.agent, session: agentPresence.session } } + : {}), + // Mark reconnect replays so cached completions do not notify again. + ...(isReplay === true ? { isReplay: true } : {}) } - ) + state.mainWindow?.webContents.send('agentStatus:set', statusEvent) + getDashboardPopoutWindow()?.webContents.send('agentStatus:set', statusEvent) + // A facet-only republish (progress tick) or a settled id is not a state the agent entered. + if (programStatusOnly !== true && identityOnly !== true) { + options.onRecordAgentState(payload.agentType ?? 'unknown', payload.state) + } + }) agentHookServer.setPaneStatusClearListener((clear) => { if (state.mainWindow?.isDestroyed()) { return diff --git a/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts b/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts index 75f2e1311522..d9e17ab935e7 100644 --- a/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts +++ b/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts @@ -222,7 +222,11 @@ export function buildAgentStatusLiveEntry( ...(metadata?.terminalResumeEligible === false ? { terminalResumeEligible: false as const } : {}), - ...(metadata?.sharedHost ? { sharedHost: true as const } : {}), + // A status that reuses the pane's session keeps that session's tmux host. + ...(metadata?.sharedHost || + (!metadata?.providerSession && providerSession && existing?.sharedHost) + ? { sharedHost: true as const } + : {}), ...(promptInteractionKey ? { promptInteractionKey } : {}), ...(payload.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), ...(payload.paneSleep ? { paneSleep: payload.paneSleep } : {}), From e9e8bf5183b278ab79b68f07aa16f49fb94ed1a3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:27:00 -0800 Subject: [PATCH 116/125] fix(sleep): an identity-only status of a tmux-hosted conversation leaves no window checkpoint --- .../agent-status-partial-updates.test.ts | 32 +++++++++++++++++++ .../agent-status-partial-updates.ts | 3 +- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.test.ts diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.test.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.test.ts new file mode 100644 index 000000000000..618b78c3fbaf --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.test.ts @@ -0,0 +1,32 @@ +import { expect, it } from 'vitest' +import { createTestStore } from '@/store/testing/app-store-test-fixture' +import { applyProviderSessionOnlyUpdate } from './agent-status-partial-updates' + +it.each([ + ['a pane-owned conversation leaves a checkpoint', false, true], + ['a tmux-hosted conversation leaves none', true, false] +])('identity-only status of %s', (_, sharedHost, recorded) => { + const store = createTestStore() + const paneKey = 'tab-1:11111111-1111-4111-8111-111111111111' + applyProviderSessionOnlyUpdate({ + store: store.getState(), + batch: undefined, + data: { + paneKey, + tabId: 'tab-1', + worktreeId: 'wt-1', + agentType: 'claude', + state: 'done', + prompt: '', + providerSession: { key: 'session_id', id: 'claude-session' }, + connectionId: null, + receivedAt: 200, + stateStartedAt: 150, + providerSessionOnly: true, + ...(sharedHost ? { sharedHost: true as const } : {}) + }, + paneKey, + routing: { tabId: 'tab-1', worktreeId: 'wt-1', connectionId: null } + }) + expect(Boolean(store.getState().sleepingAgentSessionsByPaneKey[paneKey])).toBe(recorded) +}) diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.ts index 309158955935..7f4c857df0ef 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.ts @@ -50,7 +50,8 @@ export function applyProviderSessionOnlyUpdate(args: { }): AgentStatusApplyResult { const { store, batch, data, paneKey, routing } = args const agent = RESUMABLE_TUI_AGENTS.find((candidate) => candidate === data.agentType) - if (!data.providerSession || !agent) { + // A tmux host's conversation outlives the pane, so its identity leaves no pane checkpoint. + if (!data.providerSession || !agent || data.sharedHost) { return 'dropped' } const update: AgentProviderSessionUpdate = { From 6b03f53c61b59614b1143534a4fa4d757f6c711f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:27:56 -0800 Subject: [PATCH 117/125] fix(sleep): an ended agent's retained identity reaches the window no more, so a quit isn't checkpointed again on restart --- .../main-window-agent-status.test.ts | 28 +++++++++++++++---- .../main-window/main-window-agent-status.ts | 4 +++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/main/startup/main-window/main-window-agent-status.test.ts b/src/main/startup/main-window/main-window-agent-status.test.ts index 0706939f30b8..74a3a7abcd5c 100644 --- a/src/main/startup/main-window/main-window-agent-status.test.ts +++ b/src/main/startup/main-window/main-window-agent-status.test.ts @@ -15,11 +15,9 @@ vi.mock('../main-process-state', () => ({ const { installMainWindowAgentStatusListeners } = await import('./main-window-agent-status') it('tells the window that a tmux-hosted conversation is shared, so it writes no checkpoint', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the listener only forwards status to this window. - installMainWindowAgentStatusListeners({ - window: {} as BrowserWindow, - onRecordAgentState: () => {} - }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the listener never reads the window it is given. + const window = {} as BrowserWindow + installMainWindowAgentStatusListeners({ window, onRecordAgentState: () => {} }) const providerSession = { key: 'session_id' as const, id: 'codex-in-tmux' } retainTmuxWriterTopology(providerSession) setListener.mock.lastCall![0]({ @@ -37,3 +35,23 @@ it('tells the window that a tmux-hosted conversation is shared, so it writes no expect.objectContaining({ paneKey: 'tab-1:pane-1', sharedHost: true }) ) }) + +it("sends no identity for an agent that ended, so a quit conversation isn't checkpointed again", () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the listener never reads the window it is given. + const window = {} as BrowserWindow + installMainWindowAgentStatusListeners({ window, onRecordAgentState: () => {} }) + send.mockClear() + setListener.mock.lastCall![0]({ + paneKey: 'tab-1:pane-1', + tabId: 'tab-1', + worktreeId: 'wt-1', + connectionId: null, + receivedAt: 1, + stateStartedAt: 1, + payload: { state: 'done', prompt: '', agentType: 'codex' }, + providerSession: { key: 'session_id', id: 'quit-codex' }, + providerSessionOnly: true, + agentPresence: { agent: 'codex', ended: true } + }) + expect(send).not.toHaveBeenCalled() +}) diff --git a/src/main/startup/main-window/main-window-agent-status.ts b/src/main/startup/main-window/main-window-agent-status.ts index 7c5a25dd8013..36cc88a7ec5b 100644 --- a/src/main/startup/main-window/main-window-agent-status.ts +++ b/src/main/startup/main-window/main-window-agent-status.ts @@ -55,6 +55,10 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt // reach the window as shared so it leaves no resume checkpoint. const shared = cliWriterTopology(row) === 'shared' ? { sharedHost: true as const } : {} if (providerSessionOnly) { + // An ended agent's retained identity is no conversation for the window to checkpoint. + if (agentPresence?.ended) { + return + } // Idle Pi session_start only refreshes resume identity; skip titles, telemetry and status UI. state.mainWindow?.webContents.send('agentStatus:set', { ...payload, From 750c77a9ebb88c87276376c3cf65b66ad7858c10 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:40:53 -0800 Subject: [PATCH 118/125] test(sleep): the woken terminal holds the pane's layout, as the window saves it --- .../stop/worktree-sleep-resume-recording.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts index e15dae95d1cd..b2e183d7931c 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.test.ts @@ -304,6 +304,19 @@ describe('a hookless resumed Codex across wakes and shell-confirmed command fini const wake = async (ptyId: string) => { tick() live.add(ptyId) + // The window saves the woken terminal into the pane's layout; a sleep checkpoints only the + // pane its stopped terminal still holds. + const session = fixture.getSession() + const layout = session.terminalLayoutsByTabId?.['host-tab'] + if (layout) { + fixture.setSession({ + ...session, + terminalLayoutsByTabId: { + ...session.terminalLayoutsByTabId, + 'host-tab': { ...layout, ptyIdsByLeafId: { [HEADLESS_LEAF_ID]: ptyId } } + } + }) + } const binding = { tabId: 'host-tab', leafId: HEADLESS_LEAF_ID, incarnationId: ptyId } await runtime.syncWindowGraph(1, { tabs: [ From f56b20cfd86b811edce3dda7182f659063dedce5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:34:39 -0800 Subject: [PATCH 119/125] fix(sleep): only a slept pane's record lists its agent; a live checkpoint is recovery, not a running agent --- .../runtime-agent-status-sources.ts | 11 ++-- .../worktree-ps-saved-sleep.test.ts | 54 +++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/src/main/runtime/construction/runtime-agent-status-sources.ts b/src/main/runtime/construction/runtime-agent-status-sources.ts index 4ca0035f359b..2526277f88a6 100644 --- a/src/main/runtime/construction/runtime-agent-status-sources.ts +++ b/src/main/runtime/construction/runtime-agent-status-sources.ts @@ -1,7 +1,8 @@ import { paneAgentIdentity } from '../../agent-hooks/server/pane-agent-identity' -import type { - SleepingAgentSessionRecord, - AgentProviderSessionMetadata +import { + isPaneSleepRecord, + type SleepingAgentSessionRecord, + type AgentProviderSessionMetadata } from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { RuntimeConstructionBindings as HostBindings } from './runtime-construction-dependencies' @@ -51,7 +52,9 @@ export abstract class RuntimeAgentStatusSources extends OrcaRuntimeWithTerminalD return identity && !identity.ended ? [identity.status] : [] }) for (const record of savedRecords) { - if (paneKeys.has(record.paneKey)) { + // Only a slept pane's record stands for its agent; a live or quit checkpoint is recovery, + // never proof that an agent runs there now. + if (paneKeys.has(record.paneKey) || !isPaneSleepRecord(record)) { continue } const identity = this.readPaneAgentIdentity(record.paneKey, record) diff --git a/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts b/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts index b62b3e2cb5fb..a364a52f1cb6 100644 --- a/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts +++ b/src/main/runtime/workspaces/process-listing/worktree-ps-saved-sleep.test.ts @@ -136,3 +136,57 @@ it.each(['claude', 'codex'] as const)( await vi.waitFor(async () => expect((await listed())?.agents).toEqual([])) } ) + +it('lists no agent from a live checkpoint alone, which is recovery, not a running agent', async () => { + const session = getDefaultWorkspaceSession() + session.tabsByWorktree[WORKTREE] = [ + { + id: TAB, + worktreeId: WORKTREE, + ptyId: null, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 100 + } + ] + session.sleepingAgentSessionsByPaneKey = { + [PANE]: { + paneKey: PANE, + tabId: TAB, + worktreeId: WORKTREE, + agent: 'codex', + providerSession: { key: 'session_id', id: 'checkpointed-codex' }, + prompt: 'Finish this task', + state: 'working', + capturedAt: 900, + updatedAt: 900, + origin: 'live' + } + } + const server = new AgentHookServer() + servers.push(server) + const runtime = new OrcaRuntimeService( + partialRuntimeStore({ + getWorkspaceSession: () => session, + getFolderWorkspaces: () => [ + storeFolderWorkspace({ + id: 'saved-sleep', + projectGroupId: 'group', + folderPath: '/tmp/saved-sleep' + }) + ], + getProjectGroups: () => [storeProjectGroup({ id: 'group' })] + }), + undefined, + { + getPaneAgentIdentity: (paneKey, saved) => server.paneAgentIdentity(paneKey, saved), + getAgentProviderSessionSnapshot: () => server.getStatusSnapshot() + } + ) + const row = (await runtime.getWorktreePs(100, true, true)).worktrees.find( + (worktree) => worktree.worktreeId === WORKTREE + ) + expect(row?.agents).toEqual([]) +}) From bf91f7f3f84507db9ffd6b2b18c0eca147bcfcd4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:43:33 -0800 Subject: [PATCH 120/125] refactor(sleep): one serialized executionHost field records who runs a conversation, replacing the binding symbol and the persisted sharedHost flag --- .../agent-hooks/server/agent-hook-server.ts | 11 +---- .../server/cli-writer-observation.ts | 47 +++++++++---------- .../server/cli-writer-topology.test.ts | 7 ++- .../agent-hooks/server/cli-writer-topology.ts | 9 +--- .../agent-hooks/server/server-hydration.ts | 9 ++-- .../agent-hooks/server/server-persistence.ts | 5 +- src/main/agent-hooks/server/server-state.ts | 2 +- src/main/agent-hooks/server/server-types.ts | 2 - ...server-opencode-writer-observation.test.ts | 4 -- .../main-window-agent-status.test.ts | 6 +-- .../agent-hook-listener/listener-event.ts | 3 ++ 11 files changed, 41 insertions(+), 64 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index d7682e546918..d7447fc86b22 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -5,11 +5,7 @@ import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normal import { parseFormEncodedBody } from '../../../shared/agent-hook-listener/request-body' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' -import { - cliWriterTopology, - retainTmuxWriterTopology, - type CliWriterObservation -} from './cli-writer-observation' +import { cliWriterTopology, type CliWriterObservation } from './cli-writer-observation' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' import { @@ -249,10 +245,7 @@ export class AgentHookServer extends AgentHookServerLifecycle { paneKey ) if (next) { - // The conversation moved, not its host: a tmux server still runs it. - if (cliWriterTopology(row) === 'shared') { - retainTmuxWriterTopology(next) - } + // The conversation moved, not its host: the row keeps its executionHost. this.applyNormalizedStatus( { ...row, diff --git a/src/main/agent-hooks/server/cli-writer-observation.ts b/src/main/agent-hooks/server/cli-writer-observation.ts index d9d18f8b39eb..b3538283f195 100644 --- a/src/main/agent-hooks/server/cli-writer-observation.ts +++ b/src/main/agent-hooks/server/cli-writer-observation.ts @@ -12,11 +12,7 @@ import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/ import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { agentProviderSessionsEqual } from '../../../shared/agent-session/lifecycle/resume/agent-provider-session-equality' import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status/identity/agent-status-terminal-owner' -import { - cliWriterTopology, - OPEN_CODE_WRITER_TOPOLOGY, - type CliWriterTopology -} from './cli-writer-topology' +import { cliWriterTopology, type CliWriterTopology } from './cli-writer-topology' import { readTmuxHookPane, readTmuxHookPaneHint @@ -49,17 +45,12 @@ export function retainOpenCodeWriterTopology( ('opencodeTui' in body && body.opencodeTui === 1) ? 'shared' : 'unverifiable' - Object.defineProperty(event.providerSession, OPEN_CODE_WRITER_TOPOLOGY, { value: topology }) + event.executionHost = topology } /** A tmux server outlives the pane it was started from, so nothing it publishes is pane-owned. */ export function tmuxCliWriterEvent(row: T): T { - if (!row.providerSession) { - return row - } - const providerSession = { ...row.providerSession } - retainTmuxWriterTopology(providerSession) - return { ...row, providerSession } + return row.providerSession ? { ...row, executionHost: 'shared' } : row } /** A hook that ran inside a tmux pane reaches this pane through a client; its server outlives the @@ -79,17 +70,9 @@ export function retainTmuxHookWriterTopology( const inherited = readTmuxHookPaneHint( env.TMUX_PANE && env.TMUX ? `${env.TMUX_PANE} ${env.TMUX.split(',')[0]}` : undefined ) + // A decided binding keeps its topology. if (tmux && !(inherited?.pane === tmux.pane && inherited.socket === tmux.socket)) { - retainTmuxWriterTopology(event.providerSession) - } -} - -/** A binding the pane reaches through a tmux client; a decided binding keeps its topology. */ -export function retainTmuxWriterTopology( - binding: NonNullable -): void { - if (!(OPEN_CODE_WRITER_TOPOLOGY in binding) && Object.isExtensible(binding)) { - Object.defineProperty(binding, OPEN_CODE_WRITER_TOPOLOGY, { value: 'shared' }) + event.executionHost ??= 'shared' } } @@ -131,7 +114,17 @@ export function deriveCliWriterTopology( sender: AgentProcessIdentity | undefined = row.agentPresence?.process ): T { const binding = row.providerSession - if (!binding || !(OPEN_CODE_WRITER_TOPOLOGY in binding)) { + // The host follows the conversation's binding: a row that carries the baseline's own binding + // carries its host. + if ( + binding && + row.executionHost === undefined && + baseline?.providerSession === binding && + baseline.executionHost !== undefined + ) { + row = { ...row, executionHost: baseline.executionHost } + } + if (!binding || row.executionHost === undefined) { if ( binding && baseline && @@ -166,10 +159,12 @@ export function deriveCliWriterTopology( return row } // A tmux host outlives an unverified writer too; only an unverified pane-owned claim is dropped. - if (binding[OPEN_CODE_WRITER_TOPOLOGY] === 'shared') { + if (row.executionHost === 'shared') { return row } - return { ...row, providerSession: { ...binding } } + const unverified = { ...row, providerSession: { ...binding } } + delete unverified.executionHost + return unverified } -export { cliWriterTopology, OPEN_CODE_WRITER_TOPOLOGY } +export { cliWriterTopology } diff --git a/src/main/agent-hooks/server/cli-writer-topology.test.ts b/src/main/agent-hooks/server/cli-writer-topology.test.ts index 7dec40eacced..2802a8098bd1 100644 --- a/src/main/agent-hooks/server/cli-writer-topology.test.ts +++ b/src/main/agent-hooks/server/cli-writer-topology.test.ts @@ -1,16 +1,15 @@ import { expect, it } from 'vitest' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' -import { deriveCliWriterTopology, retainTmuxWriterTopology } from './cli-writer-observation' +import { deriveCliWriterTopology } from './cli-writer-observation' import { cliWriterTopology } from './cli-writer-topology' it('keeps a tmux-hosted conversation shared when an unverified writer reports it', () => { - const providerSession = { key: 'session_id' as const, id: 'claude-in-tmux' } - retainTmuxWriterTopology(providerSession) const row: AgentHookEventPayload = { paneKey: 'tab-1:pane-1', connectionId: null, + executionHost: 'shared', payload: { state: 'working', prompt: '', agentType: 'claude' }, - providerSession + providerSession: { key: 'session_id', id: 'claude-in-tmux' } } // No execution matcher can vouch for the writer; a pane-owned claim would be dropped here. expect(cliWriterTopology(deriveCliWriterTopology(row, undefined, null))).toBe('shared') diff --git a/src/main/agent-hooks/server/cli-writer-topology.ts b/src/main/agent-hooks/server/cli-writer-topology.ts index 159c61921a6d..8e1b4bcadd20 100644 --- a/src/main/agent-hooks/server/cli-writer-topology.ts +++ b/src/main/agent-hooks/server/cli-writer-topology.ts @@ -1,15 +1,10 @@ import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' -// Execution metadata follows the conversation binding and disappears at serialization. -export const OPEN_CODE_WRITER_TOPOLOGY = Symbol('openCodeWriterTopology') - -export type CliWriterTopology = 'pane-owned' | 'shared' | 'unverifiable' +export type CliWriterTopology = NonNullable /** OpenCode-family servers can outlive their pane; only the binding they posted can prove otherwise. */ export function cliWriterTopology(row: AgentHookEventPayload): CliWriterTopology { - const binding = row.providerSession - const topology = - binding && OPEN_CODE_WRITER_TOPOLOGY in binding ? binding[OPEN_CODE_WRITER_TOPOLOGY] : undefined + const topology = row.executionHost return topology === 'shared' ? 'shared' : row.source !== 'opencode' && diff --git a/src/main/agent-hooks/server/server-hydration.ts b/src/main/agent-hooks/server/server-hydration.ts index f9b2eb6dcba4..cdd18116ca82 100644 --- a/src/main/agent-hooks/server/server-hydration.ts +++ b/src/main/agent-hooks/server/server-hydration.ts @@ -1,4 +1,3 @@ -import { retainTmuxWriterTopology } from './cli-writer-observation' import { admitLegacyAgentStatus, clearLegacyAgentStatuses @@ -99,15 +98,15 @@ export abstract class AgentHookServerHydration extends AgentHookServerTabCleanup : { ...(rawEntry as Record), paneKey: resolvedPaneKey } const entry = sanitizeHydratedEntry(resolvedPaneKey, rawResolvedEntry) if (entry && (entry.paneSleep || entry.receivedAt >= ttlCutoff)) { - // The binding's topology is runtime metadata; a shared host still runs this conversation. + // A shared host still runs this conversation after the restart. if ( entry.providerSession && typeof rawResolvedEntry === 'object' && rawResolvedEntry !== null && - 'sharedHost' in rawResolvedEntry && - rawResolvedEntry.sharedHost === true + 'executionHost' in rawResolvedEntry && + rawResolvedEntry.executionHost === 'shared' ) { - retainTmuxWriterTopology(entry.providerSession) + entry.executionHost = 'shared' } const launchTokenHash = readPersistedLaunchTokenHash(rawResolvedEntry) if (launchTokenHash) { diff --git a/src/main/agent-hooks/server/server-persistence.ts b/src/main/agent-hooks/server/server-persistence.ts index f41354e7c795..ad49eec649b1 100644 --- a/src/main/agent-hooks/server/server-persistence.ts +++ b/src/main/agent-hooks/server/server-persistence.ts @@ -19,7 +19,6 @@ import { pruneAgentExits, serializeAgentExits } from './agent-exit-evidence' import { LastStatusStore } from './last-status-store' import { KeyedDeadlines } from '../../../shared/collections/keyed-deadlines' import { rowsOf, selectedStatusEntries } from './last-status-saved-rows' -import { cliWriterTopology } from './cli-writer-topology' import { nextRetryDelayMs } from '../../sqlite/row-cache/row-cache-failure' export abstract class AgentHookServerPersistence extends AgentHookServerHydration { @@ -90,6 +89,8 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio // Full replies serve this runtime's run records only. acceptedReply: _acceptedReply, launchToken: _launchToken, + // Only a shared host outlives the restart; a pane-owned claim is proven again by its hook. + executionHost: _executionHost, ...persistedPayload } = enrichedPayload const launchTokenHash = this.hydratedLaunchTokenHashByPaneKey.get(paneKey) @@ -99,7 +100,7 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio ...persistedPayload, payload: persistedStatus, ...(launchTokenHash ? { launchTokenHash } : {}), - ...(cliWriterTopology(enrichedPayload) === 'shared' ? { sharedHost: true as const } : {}) + ...(enrichedPayload.executionHost === 'shared' ? { executionHost: 'shared' as const } : {}) } const commitment = this.toAuthorityEvidence(persistedPayload, launchTokenHash) if (commitment && !conflictedCommitments.has(paneKey)) { diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 0f71ebd481c3..56fcbe5ccc11 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -107,7 +107,7 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract !row.agentPresence.ended ? { suspended: true as const } : {}), - // A shared host's conversation never leaves a saved record (sharedHost), so one is the pane's. + // A shared host's conversation never leaves a saved record, so one is the pane's. processTopology: row ? (legacy ? cliWriterTopology(row) : 'shared') : 'pane-owned' } : null diff --git a/src/main/agent-hooks/server/server-types.ts b/src/main/agent-hooks/server/server-types.ts index f53d4c3086aa..bffd9452e7d9 100644 --- a/src/main/agent-hooks/server/server-types.ts +++ b/src/main/agent-hooks/server/server-types.ts @@ -84,8 +84,6 @@ export type PersistedAgentHookEventPayload = Omit< | 'replyCandidate' > & { launchTokenHash?: string - /** A tmux or shared server runs this conversation; restores the binding's topology on hydration. */ - sharedHost?: true } export type PersistedAgentHookAuthorityCommitment = { diff --git a/src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts b/src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts index fdc6f1a20259..0987d385d401 100644 --- a/src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts @@ -2,7 +2,6 @@ import { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture } from '../../../../runtime/terminal/identity/agent-status-observed-pane-identity' -import { OPEN_CODE_WRITER_TOPOLOGY } from '../../cli-writer-observation' import { toAgentStatusIpcPayload } from '../../server-status-identity' import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hooks/publication/agent-hook-envelope-build' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -98,8 +97,6 @@ describe('OpenCode writer observation', () => { }) repaint() expect(observation()?.topology).toBe('pane-owned') - const binding = row().providerSession - expect(binding && OPEN_CODE_WRITER_TOPOLOGY in binding).toBe(true) const snapshot = row() const event = { ...snapshot, @@ -112,7 +109,6 @@ describe('OpenCode writer observation', () => { buildRelayHookEnvelope(event, 'opencode2') ]) { expect(JSON.stringify(value)).not.toContain('pane-owned') - expect(Object.getOwnPropertySymbols(structuredClone(value).providerSession ?? {})).toEqual([]) } for (const extra of [{}, { opencodeSharedServer: 1 }]) { await post(extra) diff --git a/src/main/startup/main-window/main-window-agent-status.test.ts b/src/main/startup/main-window/main-window-agent-status.test.ts index 74a3a7abcd5c..d2d23ab4a951 100644 --- a/src/main/startup/main-window/main-window-agent-status.test.ts +++ b/src/main/startup/main-window/main-window-agent-status.test.ts @@ -1,6 +1,5 @@ import { expect, it, vi } from 'vitest' import type { BrowserWindow } from 'electron' -import { retainTmuxWriterTopology } from '../../agent-hooks/server/cli-writer-observation' const { setListener, send } = vi.hoisted(() => ({ setListener: vi.fn(), send: vi.fn() })) vi.mock('../../agent-hooks/server/agent-hook-server', () => ({ @@ -18,9 +17,8 @@ it('tells the window that a tmux-hosted conversation is shared, so it writes no // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the listener never reads the window it is given. const window = {} as BrowserWindow installMainWindowAgentStatusListeners({ window, onRecordAgentState: () => {} }) - const providerSession = { key: 'session_id' as const, id: 'codex-in-tmux' } - retainTmuxWriterTopology(providerSession) setListener.mock.lastCall![0]({ + executionHost: 'shared', paneKey: 'tab-1:pane-1', tabId: 'tab-1', worktreeId: 'wt-1', @@ -28,7 +26,7 @@ it('tells the window that a tmux-hosted conversation is shared, so it writes no receivedAt: 1, stateStartedAt: 1, payload: { state: 'done', prompt: '', agentType: 'codex' }, - providerSession + providerSession: { key: 'session_id', id: 'codex-in-tmux' } }) expect(send).toHaveBeenCalledWith( 'agentStatus:set', diff --git a/src/shared/agent-hook-listener/listener-event.ts b/src/shared/agent-hook-listener/listener-event.ts index 4d1540fa4c24..d5644ef06626 100644 --- a/src/shared/agent-hook-listener/listener-event.ts +++ b/src/shared/agent-hook-listener/listener-event.ts @@ -20,6 +20,9 @@ export type AgentHookEventPayload = { agentPresence?: AgentProcessPresence /** Authenticated hook route that produced this event. */ source?: AgentHookSource + /** Who runs the conversation: a server that outlives the pane (tmux, an OpenCode attach) is + * shared; it follows the conversation's binding, and only shared survives a restart. */ + executionHost?: 'pane-owned' | 'shared' | 'unverifiable' /** Ephemeral Orca launch identity stamped into the PTY env for this process. */ launchToken?: string /** Host-minted live turn revision for guarded interrupt commands; never persisted. */ From 1b4459f5f40c24bc4aa3a0d6a720df05d93c2f38 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:51:19 -0800 Subject: [PATCH 121/125] fix(sleep): a resumed turn takes its host from the resuming hook, so a tmux row resumed in the pane keeps its checkpoint --- .../agent-hooks/server/pane-agent-turn-continuity.test.ts | 5 +++++ src/main/agent-hooks/server/pane-agent-turn-continuity.ts | 6 +++++- src/main/startup/main-window/main-window-agent-status.ts | 3 +-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts index 13ebc4874b6c..8175acc379ad 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts @@ -41,3 +41,8 @@ it('keeps a restated verdict on the reporting terminal, but not a later stamped }) expect(resumedAcceptedTurn(resumed, { ...restated, turnEndedAt: 3_000 }, 'osc')).toBeNull() }) + +it('takes the host from the resuming hook, so a tmux row resumed in the pane is pane-owned', () => { + const tmuxRow = { ...resumed, executionHost: 'shared' as const } + expect(resumedAcceptedTurn(tmuxRow, restated, 'osc')?.executionHost).toBeUndefined() +}) diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index d64cce7af9b4..f220a43faec9 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -36,14 +36,18 @@ export function resumedAcceptedTurn( agentPresence: _sleptOwner, restoredUnconfirmed: _restored, paneSleep: _sleep, + executionHost: previousHost, ...accepted } = previous + // The host follows the binding: a resuming hook's binding brings its own. + const executionHost = incoming.providerSession ? incoming.executionHost : previousHost return { ...accepted, connectionId: incoming.connectionId, ...(incoming.providerSession ? { providerSession: incoming.providerSession } : {}), ...(incoming.agentPresence ? { agentPresence: incoming.agentPresence } : {}), - ...(incoming.terminalHandle ? { terminalHandle: incoming.terminalHandle } : {}) + ...(incoming.terminalHandle ? { terminalHandle: incoming.terminalHandle } : {}), + ...(executionHost ? { executionHost } : {}) } } diff --git a/src/main/startup/main-window/main-window-agent-status.ts b/src/main/startup/main-window/main-window-agent-status.ts index 36cc88a7ec5b..becd424bff8f 100644 --- a/src/main/startup/main-window/main-window-agent-status.ts +++ b/src/main/startup/main-window/main-window-agent-status.ts @@ -51,8 +51,7 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt return } const launchConfig = state.runtime?.getLaunchStatementForPaneKey(paneKey, payload.agentType) - // Topology rides the binding as a symbol the IPC clone drops; a tmux host's conversation must - // reach the window as shared so it leaves no resume checkpoint. + // A tmux host's conversation reaches the window as shared so it leaves no resume checkpoint. const shared = cliWriterTopology(row) === 'shared' ? { sharedHost: true as const } : {} if (providerSessionOnly) { // An ended agent's retained identity is no conversation for the window to checkpoint. From a19560651d82a344fb6477658da16caa9bb4d044 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:56:23 -0800 Subject: [PATCH 122/125] fix(sleep): a resumed turn keeps the host when the hook reuses the row's own binding --- .../agent-hooks/server/pane-agent-turn-continuity.test.ts | 4 +++- src/main/agent-hooks/server/pane-agent-turn-continuity.ts | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts index 8175acc379ad..6ed5cac14727 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.test.ts @@ -44,5 +44,7 @@ it('keeps a restated verdict on the reporting terminal, but not a later stamped it('takes the host from the resuming hook, so a tmux row resumed in the pane is pane-owned', () => { const tmuxRow = { ...resumed, executionHost: 'shared' as const } - expect(resumedAcceptedTurn(tmuxRow, restated, 'osc')?.executionHost).toBeUndefined() + const paneHook = { ...restated, providerSession: { ...SESSION } } + expect(resumedAcceptedTurn(tmuxRow, paneHook, 'osc')?.executionHost).toBeUndefined() + expect(resumedAcceptedTurn(tmuxRow, restated, 'osc')?.executionHost).toBe('shared') }) diff --git a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts index f220a43faec9..d9a58d693fd9 100644 --- a/src/main/agent-hooks/server/pane-agent-turn-continuity.ts +++ b/src/main/agent-hooks/server/pane-agent-turn-continuity.ts @@ -39,8 +39,12 @@ export function resumedAcceptedTurn( executionHost: previousHost, ...accepted } = previous - // The host follows the binding: a resuming hook's binding brings its own. - const executionHost = incoming.providerSession ? incoming.executionHost : previousHost + // The host follows the binding: a resuming hook's own binding brings its own host. + const executionHost = + incoming.executionHost ?? + (!incoming.providerSession || incoming.providerSession === previous.providerSession + ? previousHost + : undefined) return { ...accepted, connectionId: incoming.connectionId, From bac860d0c9bff3153eb245ac6fff95b37af723f1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:17:47 -0800 Subject: [PATCH 123/125] refactor(sleep): one name for who runs a conversation; the window and pane identity read executionHost --- src/main/agent-hooks/server/agent-hook-server.ts | 2 +- src/main/agent-hooks/server/pane-agent-identity.ts | 2 +- src/main/agent-hooks/server/server-cleanup.ts | 2 +- src/main/agent-hooks/server/server-pane-sleep.ts | 4 ++-- src/main/agent-hooks/server/server-state.ts | 2 +- src/main/agent-hooks/server/server-status-identity.ts | 2 +- src/main/agent-hooks/server/server-tab-cleanup.ts | 4 ++-- .../projection/agent-session-resume-ownership.ts | 2 +- .../recovery/restored-pane-hook-store-resume.test.ts | 2 +- .../runtime/terminal/stop/hook-status-resume-records.ts | 6 ++++-- .../terminal/stop/worktree-sleep-resume-recording.ts | 2 +- .../runtime/terminal/stop/worktree-sleep-resume-records.ts | 2 +- .../startup/main-window/main-window-agent-status.test.ts | 2 +- src/main/startup/main-window/main-window-agent-status.ts | 2 +- .../agent-status/agent-status-partial-updates.test.ts | 4 ++-- .../ipc-events/agent-status/agent-status-partial-updates.ts | 2 +- .../ipc-events/agent-status/normalize-agent-status-event.ts | 4 ++-- .../slices/agent-status/contracts/agent-status-contract.ts | 2 +- .../live-status/agent-status-live-entry-builder.ts | 6 +++--- .../lifecycle/resume/agent-resume-record-from-status.ts | 4 ++-- .../agent-status/contracts/agent-status-ipc-payload.ts | 2 +- src/shared/agent-status/contracts/agent-status-types.ts | 2 +- 22 files changed, 32 insertions(+), 30 deletions(-) diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index d7447fc86b22..c3e0f68e4382 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -119,7 +119,7 @@ export class AgentHookServer extends AgentHookServerLifecycle { const identity = this.paneAgentIdentity(resolved) return ( identity?.ended === false && - identity.processTopology !== 'shared' && + identity.executionHost !== 'shared' && !this.hasVerifiableAgentProcess(resolved) ) } diff --git a/src/main/agent-hooks/server/pane-agent-identity.ts b/src/main/agent-hooks/server/pane-agent-identity.ts index 09a0dd85efdb..69af56de4c46 100644 --- a/src/main/agent-hooks/server/pane-agent-identity.ts +++ b/src/main/agent-hooks/server/pane-agent-identity.ts @@ -10,7 +10,7 @@ export type PaneAgentIdentity = { /** Positive local process observation; shell foreground does not end a stopped job. */ suspended?: true /** Shared servers survive the pane; their conversation must not be launched again on wake. */ - processTopology?: 'pane-owned' | 'shared' | 'unverifiable' + executionHost?: 'pane-owned' | 'shared' | 'unverifiable' } /** The one rule for which agent conversation a pane holds: its hook row in any at-rest shape, diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index 9a90794d333c..ee6333f3ee37 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -142,7 +142,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerPaneSleep { // outlives the command that finished at the pane's shell. (options?.confirmedExit && (!previous?.agentPresence?.process || previous.connectionId !== null) && - identityOf()?.processTopology !== 'shared' + identityOf()?.executionHost !== 'shared' ? previous ? endedPresenceOf(previous) : { agent: identityOf()?.status.agentType ?? 'unknown', ended: true } diff --git a/src/main/agent-hooks/server/server-pane-sleep.ts b/src/main/agent-hooks/server/server-pane-sleep.ts index 7722b5a475af..b66f5320acff 100644 --- a/src/main/agent-hooks/server/server-pane-sleep.ts +++ b/src/main/agent-hooks/server/server-pane-sleep.ts @@ -36,7 +36,7 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF | EnrichedAgentHookEventPayload | undefined // Only a live or tmux row can be shared; a saved record never is, so a plain spawn reads none. - if (this.paneAgentIdentity(resolved, null)?.processTopology === 'shared') { + if (this.paneAgentIdentity(resolved, null)?.executionHost === 'shared') { this.dropStatusEntry(resolved, { preserveResumeIdentity: false }) this.emitPaneStatusCleared({ paneKey: resolved }) return @@ -127,7 +127,7 @@ export abstract class AgentHookServerPaneSleep extends AgentHookServerAuthorityF } // Keep shared ownership through provider cleanup, so later exit reconciliation cannot recover // the stale saved record as a pane-owned agent and falsely interrupt its surviving process. - if (identity.processTopology === 'shared') { + if (identity.executionHost === 'shared') { return true } const { diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 56fcbe5ccc11..b66773fb6a8c 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -108,7 +108,7 @@ export abstract class AgentHookServerState extends AgentHookServerStateContract ? { suspended: true as const } : {}), // A shared host's conversation never leaves a saved record, so one is the pane's. - processTopology: row ? (legacy ? cliWriterTopology(row) : 'shared') : 'pane-owned' + executionHost: row ? (legacy ? cliWriterTopology(row) : 'shared') : 'pane-owned' } : null } diff --git a/src/main/agent-hooks/server/server-status-identity.ts b/src/main/agent-hooks/server/server-status-identity.ts index 1220738d3f87..e36d06c1c3c9 100644 --- a/src/main/agent-hooks/server/server-status-identity.ts +++ b/src/main/agent-hooks/server/server-status-identity.ts @@ -71,7 +71,7 @@ export function toAgentStatusIpcPayload( ...(entry.turnStartedAt !== undefined ? { turnStartedAt: entry.turnStartedAt } : {}), ...pickHostTurnEnd(entry), ...(entry.providerSession ? { providerSession: entry.providerSession } : {}), - ...(cliWriterTopology(entry) === 'shared' ? { sharedHost: true as const } : {}), + ...(cliWriterTopology(entry) === 'shared' ? { executionHost: 'shared' as const } : {}), ...(entry.providerSessionOnly ? { providerSessionOnly: true } : {}), ...(entry.promptInteractionKey ? { promptInteractionKey: entry.promptInteractionKey } : {}), ...(entry.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 0548fe5ef8a5..96d741792bd0 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -32,7 +32,7 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { return } const identity = this.paneAgentIdentity(paneKey) - const shared = identity?.processTopology === 'shared' + const shared = identity?.executionHost === 'shared' // A command mark can come from a shell nested in a live agent; one with no process to probe // ends only on the host's word that the pane's shell is alone. const verifiable = this.hasVerifiableAgentProcess(paneKey) @@ -104,7 +104,7 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { // An ended agent needs no proof. const confirmedExit = identity?.ended === false && - identity.processTopology !== 'shared' && + identity.executionHost !== 'shared' && agent && (await this.terminalPaneLifecycle?.confirmProcessExit?.(resolved, agent)) if (this.state.lastStatusByPaneKey.get(resolved) !== row) { diff --git a/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts b/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts index 72de9e564f69..b0fa41d2f6cb 100644 --- a/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts +++ b/src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts @@ -71,7 +71,7 @@ export abstract class OrcaRuntimeWithAgentSessionResumeOwnership extends OrcaRun ): Promise | undefined> { const stored = this.getPaneSleepingAgentRecord(worktreeId, tab) const identity = this.readPaneAgentIdentity(makePaneKey(tab.parentTabId, tab.leafId), stored) - if (identity?.ended || identity?.processTopology === 'shared') { + if (identity?.ended || identity?.executionHost === 'shared') { return {} } const record = stored diff --git a/src/main/runtime/terminal/recovery/restored-pane-hook-store-resume.test.ts b/src/main/runtime/terminal/recovery/restored-pane-hook-store-resume.test.ts index 22fcdb6077be..4ebcf6f51b76 100644 --- a/src/main/runtime/terminal/recovery/restored-pane-hook-store-resume.test.ts +++ b/src/main/runtime/terminal/recovery/restored-pane-hook-store-resume.test.ts @@ -99,7 +99,7 @@ describe('restoring a pane its host recorded an agent in', () => { identity: { status: codexRow(), ended: ownership === 'ended', - processTopology: ownership === 'shared' ? 'shared' : 'pane-owned' + executionHost: ownership === 'shared' ? 'shared' : 'pane-owned' } }) await restore(runtime) diff --git a/src/main/runtime/terminal/stop/hook-status-resume-records.ts b/src/main/runtime/terminal/stop/hook-status-resume-records.ts index 6944668ad96d..9ca79ca0137e 100644 --- a/src/main/runtime/terminal/stop/hook-status-resume-records.ts +++ b/src/main/runtime/terminal/stop/hook-status-resume-records.ts @@ -23,7 +23,7 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session /** The part of a pane's previous status the next one may inherit its provider session from. */ export type PreviousHookStatus = Pick< ResumeRecordStatus, - 'agentType' | 'state' | 'providerSession' | 'sharedHost' + 'agentType' | 'state' | 'providerSession' | 'executionHost' > /** Main's word on a pane's launch as `agent`: its note, null for none, undefined when main can't tell. */ @@ -83,7 +83,9 @@ export function resumeStatusFromHookRow( interrupted: row.interrupted, ...(row.mainAgent ? { mainAgent: row.mainAgent } : {}), // A status that reuses the pane's session keeps that session's tmux host. - ...(row.sharedHost || (reused && previous.sharedHost) ? { sharedHost: true as const } : {}), + ...(row.executionHost === 'shared' || (reused && previous.executionHost === 'shared') + ? { executionHost: 'shared' as const } + : {}), ...(row.worktreeId ? { worktreeId: row.worktreeId } : {}) } } diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts index 7fcf47057d18..53e238a9f181 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts @@ -277,7 +277,7 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu paneKey, session.sleepingAgentSessionsByPaneKey?.[paneKey] ) - if (!identity || identity.ended || identity.processTopology === 'shared') { + if (!identity || identity.ended || identity.executionHost === 'shared') { return [] } const status = resumeStatusFromHookRow( diff --git a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts index 70c05a942e70..b874092c52dc 100644 --- a/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts +++ b/src/main/runtime/terminal/stop/worktree-sleep-resume-records.ts @@ -82,7 +82,7 @@ export async function captureWorktreeSleepResumeRecords(args: { }) if ( identity?.ended || - identity?.processTopology === 'shared' || + identity?.executionHost === 'shared' || (presence === 'exited' && !identity?.status.paneSleep) ) { retiredPaneKeys.push(paneKey) diff --git a/src/main/startup/main-window/main-window-agent-status.test.ts b/src/main/startup/main-window/main-window-agent-status.test.ts index d2d23ab4a951..d87861a91ab6 100644 --- a/src/main/startup/main-window/main-window-agent-status.test.ts +++ b/src/main/startup/main-window/main-window-agent-status.test.ts @@ -30,7 +30,7 @@ it('tells the window that a tmux-hosted conversation is shared, so it writes no }) expect(send).toHaveBeenCalledWith( 'agentStatus:set', - expect.objectContaining({ paneKey: 'tab-1:pane-1', sharedHost: true }) + expect.objectContaining({ paneKey: 'tab-1:pane-1', executionHost: 'shared' }) ) }) diff --git a/src/main/startup/main-window/main-window-agent-status.ts b/src/main/startup/main-window/main-window-agent-status.ts index becd424bff8f..dce23a5591db 100644 --- a/src/main/startup/main-window/main-window-agent-status.ts +++ b/src/main/startup/main-window/main-window-agent-status.ts @@ -52,7 +52,7 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt } const launchConfig = state.runtime?.getLaunchStatementForPaneKey(paneKey, payload.agentType) // A tmux host's conversation reaches the window as shared so it leaves no resume checkpoint. - const shared = cliWriterTopology(row) === 'shared' ? { sharedHost: true as const } : {} + const shared = cliWriterTopology(row) === 'shared' ? { executionHost: 'shared' as const } : {} if (providerSessionOnly) { // An ended agent's retained identity is no conversation for the window to checkpoint. if (agentPresence?.ended) { diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.test.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.test.ts index 618b78c3fbaf..b1d315d10f57 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.test.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.test.ts @@ -5,7 +5,7 @@ import { applyProviderSessionOnlyUpdate } from './agent-status-partial-updates' it.each([ ['a pane-owned conversation leaves a checkpoint', false, true], ['a tmux-hosted conversation leaves none', true, false] -])('identity-only status of %s', (_, sharedHost, recorded) => { +])('identity-only status of %s', (_, shared, recorded) => { const store = createTestStore() const paneKey = 'tab-1:11111111-1111-4111-8111-111111111111' applyProviderSessionOnlyUpdate({ @@ -23,7 +23,7 @@ it.each([ receivedAt: 200, stateStartedAt: 150, providerSessionOnly: true, - ...(sharedHost ? { sharedHost: true as const } : {}) + ...(shared ? { executionHost: 'shared' as const } : {}) }, paneKey, routing: { tabId: 'tab-1', worktreeId: 'wt-1', connectionId: null } diff --git a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.ts b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.ts index 7f4c857df0ef..a6d29c7241aa 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/agent-status-partial-updates.ts @@ -51,7 +51,7 @@ export function applyProviderSessionOnlyUpdate(args: { const { store, batch, data, paneKey, routing } = args const agent = RESUMABLE_TUI_AGENTS.find((candidate) => candidate === data.agentType) // A tmux host's conversation outlives the pane, so its identity leaves no pane checkpoint. - if (!data.providerSession || !agent || data.sharedHost) { + if (!data.providerSession || !agent || data.executionHost === 'shared') { return 'dropped' } const update: AgentProviderSessionUpdate = { diff --git a/src/renderer/src/hooks/ipc-events/agent-status/normalize-agent-status-event.ts b/src/renderer/src/hooks/ipc-events/agent-status/normalize-agent-status-event.ts index c8345f0b812e..ee2cbe7db8e0 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status/normalize-agent-status-event.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status/normalize-agent-status-event.ts @@ -37,7 +37,7 @@ export function normalizeAgentStatusMetadata( data.launchConfig === undefined && !authorityRestartId && !data.paneOwner && - !data.sharedHost && + data.executionHost !== 'shared' && data.orcaSessionId === undefined ) { return undefined @@ -49,6 +49,6 @@ export function normalizeAgentStatusMetadata( ...(data.launchToken ? { launchToken: data.launchToken } : {}), ...(data.launchConfig !== undefined ? { launchConfig: data.launchConfig } : {}), ...(data.paneOwner ? { paneOwner: data.paneOwner } : {}), - ...(data.sharedHost ? { sharedHost: true as const } : {}) + ...(data.executionHost === 'shared' ? { executionHost: 'shared' as const } : {}) } } diff --git a/src/renderer/src/store/slices/agent-status/contracts/agent-status-contract.ts b/src/renderer/src/store/slices/agent-status/contracts/agent-status-contract.ts index 58fbd7379243..01842b0cc753 100644 --- a/src/renderer/src/store/slices/agent-status/contracts/agent-status-contract.ts +++ b/src/renderer/src/store/slices/agent-status/contracts/agent-status-contract.ts @@ -97,7 +97,7 @@ export type AgentStatusMetadata = { launchConfig?: SleepingAgentLaunchConfig | null launchToken?: string terminalResumeEligible?: false - sharedHost?: true + executionHost?: 'shared' paneOwner?: { agent: AgentType; session: string } } diff --git a/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts b/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts index d9e17ab935e7..27ccf5893773 100644 --- a/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts +++ b/src/renderer/src/store/slices/agent-status/live-status/agent-status-live-entry-builder.ts @@ -223,9 +223,9 @@ export function buildAgentStatusLiveEntry( ? { terminalResumeEligible: false as const } : {}), // A status that reuses the pane's session keeps that session's tmux host. - ...(metadata?.sharedHost || - (!metadata?.providerSession && providerSession && existing?.sharedHost) - ? { sharedHost: true as const } + ...(metadata?.executionHost === 'shared' || + (!metadata?.providerSession && providerSession && existing?.executionHost === 'shared') + ? { executionHost: 'shared' as const } : {}), ...(promptInteractionKey ? { promptInteractionKey } : {}), ...(payload.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), diff --git a/src/shared/agent-session/lifecycle/resume/agent-resume-record-from-status.ts b/src/shared/agent-session/lifecycle/resume/agent-resume-record-from-status.ts index c79917991892..fa4b465f52c3 100644 --- a/src/shared/agent-session/lifecycle/resume/agent-resume-record-from-status.ts +++ b/src/shared/agent-session/lifecycle/resume/agent-resume-record-from-status.ts @@ -29,7 +29,7 @@ export type ResumeRecordStatus = Pick< | 'terminalTitle' | 'lastAssistantMessage' | 'terminalResumeEligible' - | 'sharedHost' + | 'executionHost' | 'interrupted' | 'mainAgent' | 'worktreeId' @@ -58,7 +58,7 @@ export function resumeRecordFromStatus(args: { const agent = args.entry.agentType if ( args.entry.terminalResumeEligible === false || - args.entry.sharedHost || + args.entry.executionHost === 'shared' || !isResumableTuiAgent(agent) || !args.entry.providerSession ) { diff --git a/src/shared/agent-status/contracts/agent-status-ipc-payload.ts b/src/shared/agent-status/contracts/agent-status-ipc-payload.ts index 52a64ac631f0..affaf65fe5cf 100644 --- a/src/shared/agent-status/contracts/agent-status-ipc-payload.ts +++ b/src/shared/agent-status/contracts/agent-status-ipc-payload.ts @@ -88,7 +88,7 @@ export type AgentStatusIpcPayload = ParsedAgentStatusPayload & { orchestration?: AgentStatusOrchestrationContext providerSession?: AgentProviderSessionMetadata /** A tmux or shared server, not this pane, runs this conversation: never the pane's resume. */ - sharedHost?: true + executionHost?: 'shared' /** Resume identity update only; the status-shaped fields are transport placeholders. */ providerSessionOnly?: boolean /** Live-only Command Code turn boundary key; not persisted to last-status.json. */ diff --git a/src/shared/agent-status/contracts/agent-status-types.ts b/src/shared/agent-status/contracts/agent-status-types.ts index f28e87775ee1..646584ef3de9 100644 --- a/src/shared/agent-status/contracts/agent-status-types.ts +++ b/src/shared/agent-status/contracts/agent-status-types.ts @@ -134,7 +134,7 @@ export type AgentStatusEntry = { /** False when the status belongs to a non-terminal owner that restores itself. */ terminalResumeEligible?: false /** A tmux or shared server, not this pane, runs this conversation: never the pane's resume. */ - sharedHost?: true + executionHost?: 'shared' /** Live-only Command Code turn boundary key; not persisted to last-status.json. */ promptInteractionKey?: string /** Live OSC 7501 facet never decides state; read through resolveProgramStatusPresentation beside the state owner. */ From efe23d71d770b2256b245fe0bffdd63f982cde15 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:26:57 -0800 Subject: [PATCH 124/125] fix(sleep): a typed WSL agent's mark ends it again; only a process main can probe excuses the shell proof --- .../agent-hooks/server/agent-hook-server.ts | 8 +++- .../server-wsl-launchless-exit.test.ts | 39 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 src/main/agent-hooks/server/testing/presence/server-wsl-launchless-exit.test.ts diff --git a/src/main/agent-hooks/server/agent-hook-server.ts b/src/main/agent-hooks/server/agent-hook-server.ts index c3e0f68e4382..5005420b013f 100644 --- a/src/main/agent-hooks/server/agent-hook-server.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -114,13 +114,17 @@ export class AgentHookServer extends AgentHookServerLifecycle { } /** A pane's agent that now reports a process its presence probe can check, became a shared - * host's, or already ended is owed no shell proof. */ + * host's, or already ended is owed no shell proof. Only a local row's process is probed; a WSL + * guest's PID is not main's to check. */ private exitProofOwed(resolved: string): boolean { const identity = this.paneAgentIdentity(resolved) return ( identity?.ended === false && identity.executionHost !== 'shared' && - !this.hasVerifiableAgentProcess(resolved) + !( + this.state.lastStatusByPaneKey.get(resolved)?.connectionId === null && + this.hasVerifiableAgentProcess(resolved) + ) ) } diff --git a/src/main/agent-hooks/server/testing/presence/server-wsl-launchless-exit.test.ts b/src/main/agent-hooks/server/testing/presence/server-wsl-launchless-exit.test.ts new file mode 100644 index 000000000000..93d6335e372d --- /dev/null +++ b/src/main/agent-hooks/server/testing/presence/server-wsl-launchless-exit.test.ts @@ -0,0 +1,39 @@ +import { expect, it, vi } from 'vitest' +import { AgentHookServer } from '../../agent-hook-server' +import { wslHookRelayConnectionId } from '../../../../../shared/agent-hook-listener/transport/wsl-hook-relay-contract' + +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) + +const PANE = 'tab-wsl:44444444-4444-4444-8444-444444444444' + +it("ends a typed WSL agent at its shell's mark, though it reported a PID main can't probe", async () => { + const server = new AgentHookServer() + const worktreeId = String.raw`repo::\\wsl.localhost\Ubuntu\home\user\repo` + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-wsl', + worktreeId, + providerSession: { key: 'session_id', id: 'wsl-claude' }, + agentPresence: { + agent: 'claude', + sessionOwner: true, + process: { pid: 4001, platform: 'linux', startTime: 'boot:4001' } + }, + payload: { state: 'done', prompt: 'ship it', agentType: 'claude' } + }, + wslHookRelayConnectionId('Ubuntu') + ) + server.setTerminalPaneLifecycle({ + ownsProcess: () => true, + isStopping: () => false, + isReversibleStop: () => false, + isPlaced: () => true, + confirmShellAlone: async () => null + }) + expect(server.paneAgentIdentity(PANE)?.ended).toBe(false) + server.retireProcessAuthority(PANE, { confirmedExit: true, launchRetired: true }) + await new Promise((resolve) => setImmediate(resolve)) + expect(server.paneAgentIdentity(PANE)?.ended ?? true).toBe(true) +}) From 463ed3b044949ea51db8dad1f1c36daee114169c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:36:20 -0800 Subject: [PATCH 125/125] fix(sleep): a slept conversation with no turn yet stays slept across an app restart --- .../agent-hooks/server/server-persistence-validation.ts | 3 ++- .../server/testing/persistence/server-pane-sleep.test.ts | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/agent-hooks/server/server-persistence-validation.ts b/src/main/agent-hooks/server/server-persistence-validation.ts index 764bb1896b5d..f4f237a3223e 100644 --- a/src/main/agent-hooks/server/server-persistence-validation.ts +++ b/src/main/agent-hooks/server/server-persistence-validation.ts @@ -153,7 +153,8 @@ export function sanitizeHydratedEntry( const hostTurn = readHostTurnRecord(record.hostTurn) return { paneKey, - ...(payload.state === 'done' && payload.sessionBoundary !== true && !providerSessionOnly + // A sleep also settles a conversation that had no turn yet (a session boundary). + ...(payload.state === 'done' && !providerSessionOnly ? { paneSleep: readPaneSleep(record.paneSleep) } : {}), agentPresence: readAgentProcessPresence(record.agentPresence), diff --git a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts index aa6962070ac7..676fd24f12f1 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts @@ -289,6 +289,13 @@ it.each(['claude', 'codex'] as const)( }, ended: false }) + // An app restart while asleep keeps it the slept conversation, not one that quit. + server.stop() + await server.start({ env: 'production', userDataPath: home }) + expect(server.paneAgentIdentity(PANE)).toMatchObject({ + status: { paneSleep: { ptyId: 'pty-1' } }, + ended: false + }) } )