From 7527921d0f5fa2ea504380d6849973b6f28b5975 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 3 Aug 2026 13:05:06 -0700 Subject: [PATCH 1/5] fix(agent-status): restore hydrated nonterminal statuses as unconfirmed A hook transition that fires while Electron is down has no receiver and is discarded, so last-status.json can restore a stale 'working' as confirmed truth for up to the 7-day hydrate TTL. Stamp hydrated nonterminal rows with restoredUnconfirmed, carry it through both IPC paths, and treat such rows as never-fresh in the shared and renderer freshness gates so the sidebar, worktree.ps, and the raw snapshot all present the same degraded semantics. Terminal states restore as-is; any accepted live event clears the flag; the flag itself is never persisted. Interrupt/question inference refuses to fabricate transitions onto unconfirmed rows. --- src/main/agent-hooks/server.test.ts | 123 ++++++++++++++++++ src/main/agent-hooks/server.ts | 19 ++- src/main/index.ts | 2 + src/main/runtime/orca-runtime.ts | 7 +- .../sidebar/useWorktreeAgentRows.test.ts | 21 +++ src/renderer/src/hooks/useIpcEvents.ts | 7 +- src/renderer/src/lib/pane-agent-evidence.ts | 5 +- src/renderer/src/store/slices/agent-status.ts | 2 + src/shared/agent-status-types.test.ts | 21 +++ src/shared/agent-status-types.ts | 16 ++- src/shared/runtime-types.ts | 2 + 11 files changed, 217 insertions(+), 8 deletions(-) diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index b3ff89ab3556..b2dcecef33b9 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -7026,6 +7026,129 @@ describe('Last-status persistence', () => { } }) + it('restores hydrated nonterminal statuses as unconfirmed until a live event lands', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'may finish offline', agentType: 'claude' } + }, + 'conn-1' + ) + firstServer.ingestRemote( + { + paneKey: GOOD_PANE, + tabId: 'tab-good', + worktreeId: 'wt-1', + payload: { state: 'done', prompt: 'finished before restart', agentType: 'claude' } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + const listener = vi.fn() + server.setListener(listener) + expect(listener).toHaveBeenCalledWith( + expect.objectContaining({ paneKey: PANE, restoredUnconfirmed: true }) + ) + const byPane = new Map(server.getStatusSnapshot().map((entry) => [entry.paneKey, entry])) + expect(byPane.get(PANE)).toMatchObject({ state: 'working', restoredUnconfirmed: true }) + // Why: `done` is a terminal fact — no later transition can have been missed, so it restores confirmed. + expect(byPane.get(GOOD_PANE)?.restoredUnconfirmed).toBeUndefined() + + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'confirmed live', agentType: 'claude' } + }, + 'conn-1' + ) + const confirmed = server.getStatusSnapshot().find((entry) => entry.paneKey === PANE) + expect(confirmed).toMatchObject({ state: 'working', prompt: 'confirmed live' }) + expect(confirmed?.restoredUnconfirmed).toBeUndefined() + } finally { + server.stop() + } + }) + + it('never persists the unconfirmed flag and re-stamps it on every hydrate', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'still running', agentType: 'claude' } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const secondServer = new AgentHookServer() + await secondServer.start({ env: 'production', userDataPath }) + secondServer.flushStatusPersistSync() + secondServer.stop() + expect(readFileSync(lastStatusPath(), 'utf8')).not.toContain('restoredUnconfirmed') + + const thirdServer = new AgentHookServer() + await thirdServer.start({ env: 'production', userDataPath }) + try { + expect(thirdServer.getStatusSnapshot()).toEqual([ + expect.objectContaining({ paneKey: PANE, state: 'working', restoredUnconfirmed: true }) + ]) + } finally { + thirdServer.stop() + } + }) + + it('refuses interrupt inference on an unconfirmed hydrated row', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'long task', agentType: 'codex' } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + const baseline = server.getStatusSnapshot()[0] + expect(baseline).toMatchObject({ paneKey: PANE, restoredUnconfirmed: true }) + const applied = server.inferInterrupt({ + paneKey: PANE, + baselineUpdatedAt: baseline.receivedAt, + baselineStateStartedAt: baseline.stateStartedAt, + baselinePrompt: 'long task', + baselineAgentType: 'codex', + intent: 'plain-escape' + }) + // Why: synthesizing `done` onto a never-confirmed `working` would fabricate a transition from stale disk state. + expect(applied).toBe(false) + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' }) + expect(server.getStatusSnapshot()[0]?.interrupted).toBeUndefined() + } finally { + server.stop() + } + }) + it('keeps SSH status ordering monotonic across hydration and clock rollback', async () => { const now = 1_700_000_000_000 vi.spyOn(Date, 'now').mockReturnValue(now) diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index 0f99f2cae9d7..94976306755e 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -83,6 +83,8 @@ export type { AgentHookSource } type EnrichedAgentHookEventPayload = AgentHookEventPayload & { receivedAt: number stateStartedAt: number + /** Stamped at hydrate for nonterminal states; never persisted (hydrate re-stamps) and cleared by any accepted live event replacing the entry. */ + restoredUnconfirmed?: true } type NormalizedLocalHook = { @@ -92,7 +94,7 @@ type NormalizedLocalHook = { type PersistedAgentHookEventPayload = Omit< EnrichedAgentHookEventPayload, - 'claudeRunningNonAgentTask' | 'launchToken' | 'promptInteractionKey' + 'claudeRunningNonAgentTask' | 'launchToken' | 'promptInteractionKey' | 'restoredUnconfirmed' > & { launchTokenHash?: string } @@ -378,6 +380,7 @@ function toAgentStatusIpcPayload(entry: EnrichedAgentHookEventPayload): AgentSta ...(entry.providerSession ? { providerSession: entry.providerSession } : {}), ...(entry.providerSessionOnly ? { providerSessionOnly: true } : {}), ...(entry.promptInteractionKey ? { promptInteractionKey: entry.promptInteractionKey } : {}), + ...(entry.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), ...entry.payload } } @@ -728,6 +731,10 @@ export class AgentHookServer { if (existing.providerSessionOnly) { return false } + // Why: inference must not fabricate a `done` onto a row whose `working` was never confirmed this runtime. + if (existing.restoredUnconfirmed) { + return false + } const payload = existing.payload const agentType: AgentType | undefined = payload.agentType // Why: Droid's Ctrl+C exits the CLI (handled by PTY lifecycle) rather than interrupting the current turn. @@ -816,6 +823,10 @@ export class AgentHookServer { if (!existing) { return false } + // Why: inference must not fabricate a transition onto a row whose state was never confirmed this runtime. + if (existing.restoredUnconfirmed) { + return false + } const payload = existing.payload // Why: only Claude's interactive question clears on typed input — tool name (not hook event) discriminates; real permission waits stay sticky. if ( @@ -2505,6 +2516,10 @@ export class AgentHookServer { (entry.payload.subagents?.length ?? 0) - (hydratedPayload.subagents?.length ?? 0) entry.payload = hydratedPayload } + if (entry.payload.state !== 'done') { + // Why: the terminal transition may have fired while no receiver was up; restore as unconfirmed, never as live truth. + entry.restoredUnconfirmed = true + } this.state.lastStatusByPaneKey.set(resolvedPaneKey, entry) if (entry.connectionId) { // Why: a restart can see an earlier wall clock; seed ordering so new events stay after disk state. @@ -2621,6 +2636,8 @@ export class AgentHookServer { const { claudeRunningNonAgentTask: _claudeRunningNonAgentTask, promptInteractionKey: _promptInteractionKey, + // Why: never persisted — hydrate re-stamps it, so a stored copy could only drift. + restoredUnconfirmed: _restoredUnconfirmed, launchToken, ...persistedPayload } = payload as EnrichedAgentHookEventPayload diff --git a/src/main/index.ts b/src/main/index.ts index 2c94c61488ca..c7c5f24c46f8 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1406,6 +1406,7 @@ function openMainWindow(): BrowserWindow { providerSession, providerSessionOnly, promptInteractionKey, + restoredUnconfirmed, isReplay }) => { if (mainWindow?.isDestroyed()) { @@ -1442,6 +1443,7 @@ function openMainWindow(): BrowserWindow { stateStartedAt, ...(providerSession ? { providerSession } : {}), ...(promptInteractionKey ? { promptInteractionKey } : {}), + ...(restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), ...(orchestration ? { orchestration } : {}) }) recordAgentStateCrashBreadcrumb(payload.agentType ?? 'unknown', payload.state) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 26db5a1964c0..372673fb51a8 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -17155,6 +17155,7 @@ export class OrcaRuntimeService { interrupted: boolean stateStartedAt: number updatedAt: number + restoredUnconfirmed?: boolean } >() for (const snapshot of this.latestAgentStatusByPaneKey.values()) { @@ -17199,7 +17200,8 @@ export class OrcaRuntimeService { toolInput: entry.toolInput ?? null, interrupted: entry.interrupted ?? false, stateStartedAt: entry.stateStartedAt, - updatedAt: entry.receivedAt + updatedAt: entry.receivedAt, + ...(entry.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}) }) } if (rowSources.size === 0) { @@ -17263,7 +17265,8 @@ export class OrcaRuntimeService { toolInput: src.toolInput, interrupted: src.interrupted, stateStartedAt: src.stateStartedAt, - updatedAt: src.updatedAt + updatedAt: src.updatedAt, + ...(src.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}) } // Why: SSH/runtime projections can spell an equivalent path differently; // bucket by the canonical summary id so mobile keeps the agent activity. diff --git a/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts b/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts index 4d7ab9e84d61..913e197691a7 100644 --- a/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts +++ b/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts @@ -267,6 +267,27 @@ describe('buildWorktreeAgentRows', () => { expect(done?.state).toBe('done') }) + it('decays a restored-unconfirmed working entry to idle even while recent', () => { + // Why: a hydrated nonterminal row may describe a turn that ended while no + // receiver was up; it must never render as confirmed working, however new. + const updatedAt = 2_000 + const now = updatedAt + 1 + const rows = buildWorktreeAgentRows({ + tabs: [makeTab('tab-1'), makeTab('tab-2')], + entries: [ + makeEntry(PANE_KEY_1, updatedAt, { state: 'working', restoredUnconfirmed: true }), + makeEntry(PANE_KEY_2, updatedAt, { state: 'working' }) + ], + retained: [], + now + }) + + const unconfirmed = rows.find((r) => r.paneKey === PANE_KEY_1) + const confirmed = rows.find((r) => r.paneKey === PANE_KEY_2) + expect(unconfirmed?.state).toBe('idle') + expect(confirmed?.state).toBe('working') + }) + it('renders live worktree-attributed entries even when their tab is absent', () => { const rows = buildWorktreeAgentRows({ tabs: [], diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 3c8b19068c2e..38b7b473ae4a 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -3203,6 +3203,11 @@ export function useIpcEvents(): void { const statusPayloadWithTurnBoundary = data.promptInteractionKey ? { ...statusPayload, promptInteractionKey: data.promptInteractionKey } : statusPayload + // Why: hydrated-unconfirmed provenance is envelope data the payload whitelist above drops; re-thread it or freshness gates confirm restored rows. + const statusPayloadWithProvenance = + data.restoredUnconfirmed === true + ? { ...statusPayloadWithTurnBoundary, restoredUnconfirmed: true } + : statusPayloadWithTurnBoundary const identity = resolveAgentStatusIdentity({ existing: existingStatus ? { @@ -3241,7 +3246,7 @@ export function useIpcEvents(): void { const statusWorktreeId = data.worktreeId ?? owningWorktreeId store.setAgentStatus( paneKey, - statusPayloadWithTurnBoundary, + statusPayloadWithProvenance, terminalTitle, { updatedAt: data.receivedAt, diff --git a/src/renderer/src/lib/pane-agent-evidence.ts b/src/renderer/src/lib/pane-agent-evidence.ts index 4d67758951ad..4c9c49ad9bbe 100644 --- a/src/renderer/src/lib/pane-agent-evidence.ts +++ b/src/renderer/src/lib/pane-agent-evidence.ts @@ -15,11 +15,12 @@ import { // (Moved here from agent-status.ts so the evidence resolvers below and the // aggregate consumers share one gate without an import cycle.) export function isExplicitAgentStatusFresh( - entry: Pick, + entry: Pick, now: number, staleAfterMs: number ): boolean { - return now - entry.updatedAt <= staleAfterMs + // Why: an unconfirmed hydrated row may describe a turn that ended while no receiver was up; never fresh. + return entry.restoredUnconfirmed !== true && now - entry.updatedAt <= staleAfterMs } /** diff --git a/src/renderer/src/store/slices/agent-status.ts b/src/renderer/src/store/slices/agent-status.ts index dc2fde9f6031..3e48e55c41fb 100644 --- a/src/renderer/src/store/slices/agent-status.ts +++ b/src/renderer/src/store/slices/agent-status.ts @@ -156,6 +156,7 @@ export type AgentStatusSlice = { payload: ParsedAgentStatusPayload & { orchestration?: AgentStatusOrchestrationContext promptInteractionKey?: string + restoredUnconfirmed?: boolean }, terminalTitle?: string, timing?: { updatedAt?: number; stateStartedAt?: number }, @@ -1877,6 +1878,7 @@ export const createAgentStatusSlice: StateCreator { vi.restoreAllMocks() }) +describe('isFreshNonDoneAgentStatus', () => { + it('treats a within-TTL working entry as fresh', () => { + expect(isFreshNonDoneAgentStatus({ state: 'working', updatedAt: 1_000 }, 2_000)).toBe(true) + }) + + it('never treats a restored-unconfirmed entry as fresh, regardless of age', () => { + expect( + isFreshNonDoneAgentStatus( + { state: 'working', updatedAt: 1_999, restoredUnconfirmed: true }, + 2_000 + ) + ).toBe(false) + }) + + it('stays false for done and for stale entries', () => { + expect(isFreshNonDoneAgentStatus({ state: 'done', updatedAt: 2_000 }, 2_000)).toBe(false) + expect(isFreshNonDoneAgentStatus({ state: 'working', updatedAt: 0 }, 10_000, 5_000)).toBe(false) + }) +}) + describe('parseAgentStatusPayload', () => { it('parses a valid working payload', () => { const result = parseAgentStatusPayload( diff --git a/src/shared/agent-status-types.ts b/src/shared/agent-status-types.ts index 157fc95a050d..1f2c3680048f 100644 --- a/src/shared/agent-status-types.ts +++ b/src/shared/agent-status-types.ts @@ -137,6 +137,10 @@ export type AgentStatusEntry = { providerSession?: AgentProviderSessionMetadata /** Live-only Command Code turn boundary key; not persisted to last-status.json. */ promptInteractionKey?: string + /** True for a nonterminal state hydrated from last-status.json with no live hook since: + * the transition may have been missed while no receiver was up, so freshness gates + * treat the row as stale immediately. Cleared by any accepted live event. */ + restoredUnconfirmed?: boolean } export type MigrationUnsupportedPtyEntry = { @@ -200,6 +204,8 @@ export type AgentStatusIpcPayload = ParsedAgentStatusPayload & { providerSessionOnly?: boolean /** Live-only Command Code turn boundary key; not persisted to last-status.json. */ promptInteractionKey?: string + /** See AgentStatusEntry.restoredUnconfirmed — hydrated nonterminal provenance. */ + restoredUnconfirmed?: boolean } /** Wire shape for ordinary pane teardown or a stamped SSH disconnect batch. */ @@ -228,11 +234,17 @@ export const AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH = 16000 export const AGENT_STATUS_STALE_AFTER_MS = 30 * 60 * 1000 export function isFreshNonDoneAgentStatus( - entry: Pick | undefined, + entry: Pick | undefined, now = Date.now(), staleAfterMs = AGENT_STATUS_STALE_AFTER_MS ): boolean { - return Boolean(entry && entry.state !== 'done' && now - entry.updatedAt <= staleAfterMs) + // Why: an unconfirmed hydrated row may describe a turn that ended while no receiver was up; never fresh. + return Boolean( + entry && + entry.state !== 'done' && + entry.restoredUnconfirmed !== true && + now - entry.updatedAt <= staleAfterMs + ) } // Why: ReadonlySet so .has() accepts any string without a cast here; the narrowing cast stays on the return line where it's proven safe. diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index c8291e35fb1d..125d0d588ad4 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -740,6 +740,8 @@ export type RuntimeWorktreeAgentRow = { /** When the current `state` was first reported (ms). Drives "Xm ago". */ stateStartedAt: number updatedAt: number + /** See AgentStatusEntry.restoredUnconfirmed — set for hydrated nonterminal rows so clients don't render them as confirmed activity. */ + restoredUnconfirmed?: boolean } export type RuntimeWorktreePsSummary = { From e49432ed656af7da3520ccddf05d0330a4779c10 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 3 Aug 2026 13:51:55 -0700 Subject: [PATCH 2/5] fix(agent-status): shed unconfirmed marker when the liveness sweep verifies done The restored-subagent reaper's reconciled entry spread carried restoredUnconfirmed onto a process-probe-verified 'done', making freshness gates suppress a legitimate completion. Keep the marker only while the reconciled state stays nonterminal. --- .../agent-hooks/restored-subagent-liveness-sweep.test.ts | 7 ++++++- src/main/agent-hooks/server.ts | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts b/src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts index 9caf7966c836..9811773eb073 100644 --- a/src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts +++ b/src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts @@ -119,6 +119,7 @@ describe('restored subagent liveness sweep', () => { try { expect(paneStatus(server)).toEqual({ state: 'working', subagents: [WORKING_CHILD] }) const previous = server.getStatusSnapshotForPane(PANE)[0] + expect(previous?.restoredUnconfirmed).toBe(true) const previousReceivedAt = previous?.receivedAt ?? 0 const reconciledAt = previousReceivedAt + 1 const now = vi.spyOn(Date, 'now').mockReturnValue(previousReceivedAt) @@ -130,6 +131,8 @@ describe('restored subagent liveness sweep', () => { receivedAt: reconciledAt, stateStartedAt: reconciledAt }) + // Why: the reconciled `done` is process-probe-verified, so it must shed the hydrated-unconfirmed marker. + expect(server.getStatusSnapshotForPane(PANE)[0]?.restoredUnconfirmed).toBeUndefined() now.mockRestore() } finally { server.stop() @@ -163,7 +166,9 @@ describe('restored subagent liveness sweep', () => { state: 'waiting', subagents: undefined, receivedAt: previous?.receivedAt, - stateStartedAt: previous?.stateStartedAt + stateStartedAt: previous?.stateStartedAt, + // Why: a still-nonterminal reconciled row remains unconfirmed — only hooks or a terminal fact confirm it. + restoredUnconfirmed: true }) } finally { server.stop() diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index 94976306755e..0b8e2a406cf2 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -2382,8 +2382,12 @@ export class AgentHookServer { const reconciledAt = stateChanged ? Math.max(Date.now(), enriched.receivedAt + 1) : enriched.receivedAt + // Why: a reconciled `done` is process-probe-verified, not hydrated guesswork — carrying + // restoredUnconfirmed onto it would make freshness gates suppress a legitimate completion. + const { restoredUnconfirmed, ...reconciledBase } = enriched const reconciled: EnrichedAgentHookEventPayload = { - ...enriched, + ...reconciledBase, + ...(state !== 'done' && restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), receivedAt: reconciledAt, stateStartedAt: stateChanged ? reconciledAt : enriched.stateStartedAt, payload: { ...enriched.payload, state, subagents } From 3611c27077d91c4fe564ed460ae2e446b03862cb Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 3 Aug 2026 16:47:31 -0700 Subject: [PATCH 3/5] fix(agent-status): let live evidence replace hydrated rows --- src/main/agent-hooks/server.test.ts | 159 +++++++++++++++++- src/main/agent-hooks/server.ts | 8 +- src/main/runtime/orca-runtime.test.ts | 56 ++++++ src/main/runtime/orca-runtime.ts | 7 +- src/renderer/src/hooks/useIpcEvents.ts | 3 +- .../src/runtime/web-session-tabs-sync.test.ts | 55 ++++++ .../src/runtime/web-session-tabs-sync.ts | 11 +- .../src/store/slices/agent-status.test.ts | 32 ++++ src/renderer/src/store/slices/agent-status.ts | 3 +- src/shared/agent-status-identity.ts | 1 + 10 files changed, 325 insertions(+), 10 deletions(-) diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index b2dcecef33b9..184ad8537e86 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -7068,18 +7068,173 @@ describe('Last-status persistence', () => { paneKey: PANE, tabId: 'tab-1', worktreeId: 'wt-1', - payload: { state: 'working', prompt: 'confirmed live', agentType: 'claude' } + payload: { state: 'done', prompt: 'confirmed live', agentType: 'codex' } }, 'conn-1' ) const confirmed = server.getStatusSnapshot().find((entry) => entry.paneKey === PANE) - expect(confirmed).toMatchObject({ state: 'working', prompt: 'confirmed live' }) + expect(confirmed).toMatchObject({ + state: 'done', + prompt: 'confirmed live', + agentType: 'codex' + }) expect(confirmed?.restoredUnconfirmed).toBeUndefined() } finally { server.stop() } }) + it('lets an identical live OSC observation confirm a hydrated row', async () => { + const payload = { + state: 'working' as const, + prompt: 'still running', + agentType: 'claude' as const + } + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { paneKey: PANE, tabId: 'tab-1', worktreeId: 'wt-1', payload }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + expect(server.getStatusSnapshot()[0]?.restoredUnconfirmed).toBe(true) + server.ingestTerminalStatus({ + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + connectionId: 'conn-1', + payload + }) + expect(server.getStatusSnapshot()[0]?.restoredUnconfirmed).toBeUndefined() + } finally { + server.stop() + } + }) + + it('does not let a hydrated Claude permission suppress the first live working event', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PermissionRequest', + payload: { + state: 'waiting', + prompt: 'review command', + agentType: 'claude', + toolName: 'Bash', + toolInput: 'dangerous command' + } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PreToolUse', + payload: { + state: 'working', + prompt: 'review command', + agentType: 'claude', + toolName: 'Read', + toolInput: 'package.json' + } + }, + 'conn-1' + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + toolName: 'Read' + }) + expect(server.getStatusSnapshot()[0]?.restoredUnconfirmed).toBeUndefined() + } finally { + server.stop() + } + }) + + it('does not inherit a stale tool id from hydrated Claude progress', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PreToolUse', + toolUseId: 'tool-old', + toolAgentType: 'main', + payload: { + state: 'working', + prompt: 'run tests', + agentType: 'claude', + toolName: 'Bash', + toolInput: 'pnpm test' + } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PermissionRequest', + toolAgentType: 'main', + payload: { + state: 'waiting', + prompt: 'run tests', + agentType: 'claude', + toolName: 'Bash', + toolInput: 'pnpm test' + } + }, + 'conn-1' + ) + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PostToolUse', + toolUseId: 'tool-new', + toolAgentType: 'main', + payload: { + state: 'working', + prompt: 'run tests', + agentType: 'claude', + toolName: 'Bash', + toolInput: 'pnpm test' + } + }, + 'conn-1' + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' }) + } finally { + server.stop() + } + }) + it('never persists the unconfirmed flag and re-stamps it on every hydrate', async () => { const firstServer = new AgentHookServer() await firstServer.start({ env: 'production', userDataPath }) diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index 0b8e2a406cf2..1ffe08f6f617 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -437,6 +437,9 @@ function shouldKeepClaudePermissionVisible( previous: EnrichedAgentHookEventPayload | undefined, next: AgentHookEventPayload ): boolean { + if (previous?.restoredUnconfirmed) { + return false + } if ( previous?.payload.agentType !== 'claude' || previous.payload.state !== 'waiting' || @@ -510,6 +513,7 @@ function shouldInheritClaudeToolUseIdForPermission( next: AgentHookEventPayload ): boolean { if ( + previous?.restoredUnconfirmed || previous?.payload.agentType !== 'claude' || previous.payload.state !== 'working' || previous.hookEventName !== 'PreToolUse' || @@ -1139,7 +1143,8 @@ export class AgentHookServer { ? { agentType: previous.payload.agentType, state: previous.payload.state, - updatedAt: previous.receivedAt + updatedAt: previous.receivedAt, + restoredUnconfirmed: previous.restoredUnconfirmed } : undefined, incoming: rootContextPreservingPayload.payload.agentType, @@ -1751,6 +1756,7 @@ export class AgentHookServer { | EnrichedAgentHookEventPayload | undefined if ( + !previous?.restoredUnconfirmed && previous?.connectionId === connectionId && previous.tabId === tabId && previous.worktreeId === worktreeId && diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index fab9c65dd22c..97441f8a7694 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -10849,6 +10849,62 @@ describe('OrcaRuntimeService', () => { }) }) + it('does not treat a restored-unconfirmed hook row as live terminal status', async () => { + const leafId = '11111111-1111-4111-8111-111111111111' + const paneKey = makePaneKey('tab-1', leafId) + const runtime = new OrcaRuntimeService(store, undefined, { + getAgentStatusSnapshot: () => [ + { + paneKey, + state: 'waiting', + prompt: '', + agentType: 'codex', + connectionId: null, + receivedAt: Date.now(), + stateStartedAt: Date.now(), + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + restoredUnconfirmed: true + } + ] + }) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }), + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + title: 'repo terminal', + activeLeafId: leafId, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + leafId, + paneRuntimeId: 1, + ptyId: 'pty-1' + } + ] + }) + + const [terminal] = (await runtime.listTerminals()).terminals + + await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({ + handle: terminal.handle, + isRunningAgent: false, + status: null + }) + }) + it('does not let stale wait text override a fresh explicit working state', async () => { const leafId = '11111111-1111-4111-8111-111111111111' const paneKey = makePaneKey('tab-1', leafId) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 372673fb51a8..dbae4df1c3c1 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -16314,9 +16314,10 @@ export class OrcaRuntimeService { const consider = ( state: AgentStatusEntry['state'] | undefined, - updatedAt: number | null | undefined + updatedAt: number | null | undefined, + restoredUnconfirmed = false ): void => { - if (!state) { + if (!state || restoredUnconfirmed) { return } if (typeof updatedAt !== 'number' || now - updatedAt > AGENT_STATUS_STALE_AFTER_MS) { @@ -16340,7 +16341,7 @@ export class OrcaRuntimeService { if (entry.terminalHandle !== handle && (!paneKey || entry.paneKey !== paneKey)) { continue } - consider(entry.state, entry.receivedAt) + consider(entry.state, entry.receivedAt, entry.restoredUnconfirmed) } return bestStatus ? { status: bestStatus, updatedAt: bestUpdatedAt } : null diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 38b7b473ae4a..f7f66f0ceacd 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -3213,7 +3213,8 @@ export function useIpcEvents(): void { ? { agentType: existingStatus.agentType, state: existingStatus.state, - updatedAt: existingStatus.updatedAt + updatedAt: existingStatus.updatedAt, + restoredUnconfirmed: existingStatus.restoredUnconfirmed } : undefined, incoming: statusPayload.agentType, diff --git a/src/renderer/src/runtime/web-session-tabs-sync.test.ts b/src/renderer/src/runtime/web-session-tabs-sync.test.ts index e406d8644f0f..01836b7955a5 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.test.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.test.ts @@ -1896,6 +1896,61 @@ describe('applyWebSessionTabsSnapshot', () => { expect(patch.sortEpoch).toBe(1) }) + it('applies a marker-only host restart degradation to mirrored agent status', () => { + const hostPaneKey = makePaneKey('host-tab-1', LEAF_ID) + const snapshot = makeSnapshot([ + { + type: 'terminal', + id: HOST_SURFACE_ID, + title: 'codex [working]', + parentTabId: 'host-tab-1', + leafId: LEAF_ID, + isActive: true, + status: 'ready', + terminal: 'terminal-1', + agentStatus: { + state: 'working', + prompt: 'fix web parity', + updatedAt: NOW - 100, + stateStartedAt: NOW - 1_000, + agentType: 'codex', + paneKey: hostPaneKey, + tabId: 'host-tab-1', + worktreeId: WT, + stateHistory: [] + } + } + ]) + const initial = applyWebSessionTabsSnapshot( + makeState(), + snapshot, + ENV, + NOW + ) as Partial + const mirroredPaneKey = Object.keys(initial.agentStatusByPaneKey ?? {})[0]! + const degraded = applyWebSessionTabsSnapshot( + makeState({ ...initial }), + { + ...snapshot, + snapshotVersion: 2, + tabs: snapshot.tabs.map((tab) => + tab.type === 'terminal' && tab.agentStatus + ? { + ...tab, + agentStatus: { ...tab.agentStatus, restoredUnconfirmed: true } + } + : tab + ) + }, + ENV, + NOW + ) as Partial + + expect(degraded.agentStatusByPaneKey?.[mirroredPaneKey]?.restoredUnconfirmed).toBe(true) + expect(degraded.agentStatusEpoch).toBe(2) + expect(degraded.sortEpoch).toBe(2) + }) + it('repairs mirrored same-state attribution and retains identity from an older snapshot', () => { const hostPaneKey = makePaneKey('host-tab-1', LEAF_ID) const snapshot = makeSnapshot([ diff --git a/src/renderer/src/runtime/web-session-tabs-sync.ts b/src/renderer/src/runtime/web-session-tabs-sync.ts index 0b8b39086756..d944272accb9 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.ts @@ -801,10 +801,13 @@ function buildMirroredAgentStatusPatch( changed = true const entryAttributionChanged = existing?.worktreeId !== entry.worktreeId || existing?.tabId !== entry.tabId + const entryFreshnessChanged = + !!existing && isAgentStatusFresh(existing, now) !== isAgentStatusFresh(entry, now) const entrySortRelevantChange = !existing || existing.state !== entry.state || !isAgentStatusFresh(existing, now) || + entryFreshnessChanged || entryAttributionChanged || isMirroredCommandCodeTurnBump(existing, entry) aggregateRelevantChange = aggregateRelevantChange || entrySortRelevantChange @@ -1395,13 +1398,17 @@ function agentStatusEntryEqual(a: AgentStatusEntry | undefined, b: AgentStatusEn a.lastAssistantMessage === b.lastAssistantMessage && a.interrupted === b.interrupted && a.promptInteractionKey === b.promptInteractionKey && + a.restoredUnconfirmed === b.restoredUnconfirmed && agentProviderSessionsEqual(a.agentType, a.providerSession, b.providerSession) && sameAgentStateHistory(a.stateHistory, b.stateHistory) ) } -function isAgentStatusFresh(entry: Pick, now: number): boolean { - return now - entry.updatedAt <= AGENT_STATUS_STALE_AFTER_MS +function isAgentStatusFresh( + entry: Pick, + now: number +): boolean { + return entry.restoredUnconfirmed !== true && now - entry.updatedAt <= AGENT_STATUS_STALE_AFTER_MS } function isMirroredCommandCodeTurnBump( diff --git a/src/renderer/src/store/slices/agent-status.test.ts b/src/renderer/src/store/slices/agent-status.test.ts index 6954fcc70346..70c334eae1a8 100644 --- a/src/renderer/src/store/slices/agent-status.test.ts +++ b/src/renderer/src/store/slices/agent-status.test.ts @@ -603,6 +603,38 @@ describe('agent status tool + assistant fields', () => { expect(setGeneratedTabTitleFromAgentPrompt).toHaveBeenLastCalledWith('tab-1:1', 'parent codex') }) + it('does not let restored-unconfirmed identity suppress a live terminal status', () => { + vi.useFakeTimers() + const store = createTestStore() + store.getState().setAgentStatus( + 'tab-1:1', + { + state: 'working', + prompt: 'stale codex turn', + agentType: 'codex', + restoredUnconfirmed: true + }, + 'codex', + { updatedAt: 1_000, stateStartedAt: 1_000 } + ) + + store + .getState() + .setAgentStatus( + 'tab-1:1', + { state: 'done', prompt: 'live claude turn', agentType: 'claude' }, + 'claude', + { updatedAt: 1_100, stateStartedAt: 1_100 } + ) + + expect(store.getState().agentStatusByPaneKey['tab-1:1']).toMatchObject({ + state: 'done', + prompt: 'live claude turn', + agentType: 'claude' + }) + expect(store.getState().agentStatusByPaneKey['tab-1:1'].restoredUnconfirmed).toBeUndefined() + }) + it('allows pane agentType to change after the prior turn is done', () => { vi.useFakeTimers() const store = createTestStore() diff --git a/src/renderer/src/store/slices/agent-status.ts b/src/renderer/src/store/slices/agent-status.ts index 3e48e55c41fb..d8c87362edc1 100644 --- a/src/renderer/src/store/slices/agent-status.ts +++ b/src/renderer/src/store/slices/agent-status.ts @@ -1713,7 +1713,8 @@ export const createAgentStatusSlice: StateCreator Date: Mon, 3 Aug 2026 17:03:17 -0700 Subject: [PATCH 4/5] fix(agent-status): keep restored rows degraded Sort accepted live evidence after hydrated rows even across wall-clock rollback. Let unconfirmed rows own their preserved pane titles without asserting live state, while retaining independently live sibling evidence. --- src/main/agent-hooks/server.test.ts | 24 ++++++++---- src/main/agent-hooks/server.ts | 9 ++++- .../sidebar/smart-attention.test.ts | 31 ++++++++++++++- .../src/components/sidebar/smart-attention.ts | 7 +++- .../worktree-agent-activity-summary.test.ts | 29 ++++++++++++++ .../worktree-agent-activity-summary.ts | 9 ++++- .../terminal-tab-activity-status.test.ts | 33 ++++++++++++++++ .../tab-bar/terminal-tab-activity-status.ts | 38 +++++++++++++------ .../src/lib/running-agent-targets.test.ts | 30 +++++++++++++++ src/renderer/src/lib/running-agent-targets.ts | 4 +- 10 files changed, 189 insertions(+), 25 deletions(-) diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index 184ad8537e86..96bb121c7e74 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -7092,25 +7092,35 @@ describe('Last-status persistence', () => { } const firstServer = new AgentHookServer() await firstServer.start({ env: 'production', userDataPath }) - firstServer.ingestRemote( - { paneKey: PANE, tabId: 'tab-1', worktreeId: 'wt-1', payload }, - 'conn-1' - ) + firstServer.ingestTerminalStatus({ + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + connectionId: null, + payload + }) firstServer.flushStatusPersistSync() firstServer.stop() const server = new AgentHookServer() await server.start({ env: 'production', userDataPath }) try { - expect(server.getStatusSnapshot()[0]?.restoredUnconfirmed).toBe(true) + const restored = server.getStatusSnapshot()[0] + if (!restored) { + throw new Error('expected hydrated status') + } + expect(restored?.restoredUnconfirmed).toBe(true) + vi.spyOn(Date, 'now').mockReturnValue(restored.receivedAt - 1_000) server.ingestTerminalStatus({ paneKey: PANE, tabId: 'tab-1', worktreeId: 'wt-1', - connectionId: 'conn-1', + connectionId: null, payload }) - expect(server.getStatusSnapshot()[0]?.restoredUnconfirmed).toBeUndefined() + const confirmed = server.getStatusSnapshot()[0] + expect(confirmed?.restoredUnconfirmed).toBeUndefined() + expect(confirmed?.receivedAt).toBe(restored.receivedAt + 1) } finally { server.stop() } diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index 1ffe08f6f617..71fa1a6a0fc5 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -1084,8 +1084,13 @@ export class AgentHookServer { const connectionClearWatermark = payload.connectionId ? this.connectionTimestampWatermarkById.get(payload.connectionId) : undefined - // Why: Date.now() can repeat across reconnect; a remote replay must sort strictly after its connection's transient clear. - const now = Math.max(Date.now(), (connectionClearWatermark ?? -1) + 1) + // Why: renderer ordering rejects older rows; live evidence must sort after reconnect clears and restored rows across clock rollback. + const restoredStatusWatermark = previous?.restoredUnconfirmed ? previous.receivedAt : undefined + const now = Math.max( + Date.now(), + (connectionClearWatermark ?? -1) + 1, + (restoredStatusWatermark ?? -1) + 1 + ) if (payload.connectionId) { this.connectionTimestampWatermarkById.set(payload.connectionId, now) } diff --git a/src/renderer/src/components/sidebar/smart-attention.test.ts b/src/renderer/src/components/sidebar/smart-attention.test.ts index 794d7f781176..09f64c758d19 100644 --- a/src/renderer/src/components/sidebar/smart-attention.test.ts +++ b/src/renderer/src/components/sidebar/smart-attention.test.ts @@ -60,7 +60,8 @@ function makeEntry(overrides: Partial & { paneKey: string }): tabId: overrides.tabId, terminalTitle: overrides.terminalTitle, stateHistory: overrides.stateHistory ?? [], - interrupted: overrides.interrupted + interrupted: overrides.interrupted, + restoredUnconfirmed: overrides.restoredUnconfirmed } } @@ -576,6 +577,34 @@ describe('buildAttentionByWorktree', () => { expect(map.get(w.id)).toEqual({ cls: 2, attentionTimestamp: NOW - 30_000 }) }) + it('keeps a restored row idle while allowing an independently live sibling title', () => { + const w = makeWorktree('wt-1') + const tab = makeTab('tab-1', w.id) + const key = paneKey(tab.id, LEAF_1) + const map = buildAttentionByWorktree( + [w], + { [w.id]: [tab] }, + { + [key]: makeEntry({ + paneKey: key, + state: 'working', + restoredUnconfirmed: true + }) + }, + { [tab.id]: { 1: '⠋ Claude', 2: '✋ Gemini CLI' } }, + ptyMap([tab.id]), + NOW, + undefined, + splitLayout(tab.id) + ) + + expect(map.get(w.id)).toEqual({ + cls: 1, + attentionTimestamp: NOW, + cause: 'title-heuristic' + }) + }) + it('per-pane authority across panes: pane A fresh hook=done, pane B no hook + permission title → Class 1', () => { const w = makeWorktree('wt-1') const tab = makeTab('tab-1', w.id) diff --git a/src/renderer/src/components/sidebar/smart-attention.ts b/src/renderer/src/components/sidebar/smart-attention.ts index 01a551428caf..be8920676d1d 100644 --- a/src/renderer/src/components/sidebar/smart-attention.ts +++ b/src/renderer/src/components/sidebar/smart-attention.ts @@ -288,8 +288,11 @@ export function buildAttentionByWorktree( if (hookEntries) { for (const entry of hookEntries) { panes.push({ kind: 'hook', entry }) - // Why: only fresh hook entries suppress the title fallback; a stale one would hide the live title and drop to Class 4. - if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { + // Why: restored rows own their co-restored title without asserting live state. + if ( + !entry.restoredUnconfirmed && + !isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS) + ) { continue } const leafId = leafIdFromPaneKey(entry.paneKey) diff --git a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.test.ts b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.test.ts index 26c5d2828df2..bc1f06cc7b5b 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.test.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.test.ts @@ -15,6 +15,7 @@ function makeAgentStatusEntry(args: { state: AgentStatusEntry['state'] worktreeId?: string parentPaneKey?: string + restoredUnconfirmed?: true }): AgentStatusEntry { return { paneKey: args.paneKey, @@ -24,6 +25,7 @@ function makeAgentStatusEntry(args: { stateStartedAt: 1_000, stateHistory: [], worktreeId: args.worktreeId, + restoredUnconfirmed: args.restoredUnconfirmed, orchestration: args.parentPaneKey ? { taskId: 'task-1', @@ -165,6 +167,33 @@ describe('selectWorktreeAgentActivitySummary', () => { expect(nowSpy).toHaveBeenCalledTimes(2) }) + it('lets an unconfirmed restored row suppress only its pane title', () => { + vi.spyOn(Date, 'now').mockReturnValue(2_000) + const paneKey = makePaneKey('tab-1', LEAF_ID) + const summary = selectWorktreeAgentActivitySummary( + { + tabsByWorktree: { + 'repo::/wt-1': [makeTab('tab-1', 'repo::/wt-1')] + }, + agentStatusEpoch: 0, + agentStatusByPaneKey: { + [paneKey]: makeAgentStatusEntry({ + paneKey, + state: 'working', + restoredUnconfirmed: true + }) + }, + migrationUnsupportedByPtyId: {}, + runtimeAgentOrchestrationByPaneKey: {}, + retainedAgentsByPaneKey: {} + }, + 'repo::/wt-1' + ) + + expect(summary).toMatchObject({ hasLiveWorking: false, hasPermission: false }) + expect(summary.agentStatusPaneIdsByTabId['tab-1']).toEqual(new Set([LEAF_ID])) + }) + it('limits summary-reference churn to the transitioning worktree at scale', () => { vi.spyOn(Date, 'now').mockReturnValue(2_000) const worktreeIds = Array.from({ length: 12 }, (_, index) => `repo::/wt-${index}`) diff --git a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts index 0d3810fe53ff..38e585d39ce0 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts @@ -107,10 +107,17 @@ function getWorktreeAgentActivitySummaries( runtimeAgentOrchestrationByPaneKey?.[paneKey] ) const worktreeId = resolveAgentStatusWorktreeId(entry, tabIdToWorktreeId, orchestration) - if (!worktreeId || !isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { + if (!worktreeId) { continue } const summary = summaryForWorktree(worktreeId) + if (entry.restoredUnconfirmed) { + addAgentStatusPaneId(summary, paneIdentity.tabId, paneIdentity.paneId) + continue + } + if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { + continue + } addAgentStatusPaneId(summary, paneIdentity.tabId, paneIdentity.paneId) if (entry.state === 'done') { addParentPaneId(summary, orchestration, worktreeId, tabIdToWorktreeId) diff --git a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts index 2f6cbcadcd8e..8f1ea50121c4 100644 --- a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts +++ b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.test.ts @@ -108,6 +108,39 @@ describe('resolveTerminalTabActivityStatus', () => { ).toBe('working') }) + it('does not revive an unconfirmed restored row from its preserved title', () => { + const restored = entry(FIRST_LEAF_ID, 'working', { restoredUnconfirmed: true }) + expect( + resolveTerminalTabActivityStatus({ + tab: { id: TAB_ID, title: 'Codex working' }, + agentStatusByPaneKey: { [restored.paneKey]: restored }, + ptyIdsByTabId: LIVE_PTY + }) + ).toBe('active') + }) + + it('keeps an independently live sibling title visible beside an unconfirmed row', () => { + const restored = entry(FIRST_LEAF_ID, 'working', { restoredUnconfirmed: true }) + expect( + resolveTerminalTabActivityStatus({ + tab: TAB, + agentStatusByPaneKey: { [restored.paneKey]: restored }, + runtimePaneTitlesByTabId: { [TAB_ID]: { 1: 'Codex working', 2: 'Claude working' } }, + ptyIdsByTabId: LIVE_PTY, + terminalLayout: { + root: { + type: 'split', + direction: 'vertical', + first: { type: 'leaf', leafId: FIRST_LEAF_ID }, + second: { type: 'leaf', leafId: SECOND_LEAF_ID } + }, + activeLeafId: FIRST_LEAF_ID, + expandedLeafId: null + } + }) + ).toBe('working') + }) + it('de-spins a stale working tab on an epoch bump without a new map reference', () => { // Why: the freshness scheduler bumps agentStatusEpoch (not the map ref) at // the 30m stale boundary. The flag cache must invalidate on that bump, or an diff --git a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts index b64ba41b0f5c..611a6ca86aef 100644 --- a/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts +++ b/src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts @@ -56,22 +56,21 @@ function getTerminalTabActivityFlags( const now = Date.now() for (const [paneKey, entry] of Object.entries(agentStatusByPaneKey ?? {})) { const identity = parseAgentStatusPaneKey(entry.paneKey || paneKey) + if (!identity) { + continue + } + if (entry.restoredUnconfirmed) { + const flags = getOrCreateTerminalTabActivityFlags(flagsByTabId, identity.tabId) + flags.paneIds.add(identity.paneId) + continue + } // Why: stale hook entries (>30m) are not authority; a slept/abandoned pane // must not keep a tab spinning. Same freshness gate as the sidebar. - if (!identity || !isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { + if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { continue } - let flags = flagsByTabId.get(identity.tabId) - if (!flags) { - flags = { - hasPermission: false, - hasLiveWorking: false, - hasLiveDone: false, - paneIds: new Set() - } - flagsByTabId.set(identity.tabId, flags) - } + const flags = getOrCreateTerminalTabActivityFlags(flagsByTabId, identity.tabId) flags.paneIds.add(identity.paneId) if (entry.state === 'blocked' || entry.state === 'waiting') { flags.hasPermission = true @@ -89,6 +88,23 @@ function getTerminalTabActivityFlags( return flagsByTabId } +function getOrCreateTerminalTabActivityFlags( + flagsByTabId: Map, + tabId: string +): TerminalTabActivityFlags { + let flags = flagsByTabId.get(tabId) + if (!flags) { + flags = { + hasPermission: false, + hasLiveWorking: false, + hasLiveDone: false, + paneIds: new Set() + } + flagsByTabId.set(tabId, flags) + } + return flags +} + // Why: mirror the sidebar summary's parse — live entries on restored/imported // sessions can still carry pre-UUID numeric pane keys. Keep the numeric pane id // so the title-heuristic dedup in resolveWorktreeStatus can still match them. diff --git a/src/renderer/src/lib/running-agent-targets.test.ts b/src/renderer/src/lib/running-agent-targets.test.ts index 847052d2e794..addf1741fa81 100644 --- a/src/renderer/src/lib/running-agent-targets.test.ts +++ b/src/renderer/src/lib/running-agent-targets.test.ts @@ -294,6 +294,36 @@ describe('running agent send targets', () => { expect(target).not.toHaveProperty('disabledReason') }) + it('does not promote an unconfirmed restored row from its preserved title', () => { + const paneKey = makePaneKey(TAB_ID, RIGHT_LEAF_ID) + const target = resolveRunningAgentSendTarget( + state({ + agentStatusByPaneKey: { + [paneKey]: { ...entry(paneKey, 'working'), restoredUnconfirmed: true } + }, + terminalLayoutsByTabId: { + [TAB_ID]: { + root: { type: 'leaf', leafId: RIGHT_LEAF_ID }, + activeLeafId: RIGHT_LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId: { [RIGHT_LEAF_ID]: 'pty-right' } + } + }, + runtimePaneTitlesByTabId: { [TAB_ID]: { 1: 'Codex ready' } } + }), + WORKTREE_ID, + paneKey, + NOW + ) + + expect(target).toMatchObject({ + paneKey, + ptyId: 'pty-right', + status: 'disabled', + disabledReason: 'Agent status is stale' + }) + }) + it('treats a missing tab title as absent live title evidence', () => { const paneKey = makePaneKey(TAB_ID, RIGHT_LEAF_ID) const target = resolveRunningAgentSendTarget( diff --git a/src/renderer/src/lib/running-agent-targets.ts b/src/renderer/src/lib/running-agent-targets.ts index eedc06e36bac..e483b04b4a9a 100644 --- a/src/renderer/src/lib/running-agent-targets.ts +++ b/src/renderer/src/lib/running-agent-targets.ts @@ -71,7 +71,9 @@ export function deriveRunningAgentSendTargets( const liveTitleStatus = ptyId ? detectLiveAgentPaneStatus(state, parsed.tabId, parsed.leafId, tab.title) : null - if (decision.hookState === null) { + if (entry.restoredUnconfirmed) { + disabledReason = 'Agent status is stale' + } else if (decision.hookState === null) { if (liveTitleStatus === 'permission') { disabledReason = 'Agent needs permission' } else if (liveTitleStatus === null) { From acc464e7a7c2108965520071f92d4a3a6c92f985 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 3 Aug 2026 17:08:28 -0700 Subject: [PATCH 5/5] fix(agent-status): suppress unmapped restored titles Treat a single runtime title as covered by the single restored hook row while layout identity is unavailable. Preserve ordinary age-stale fallback and mapped sibling-pane evidence. --- .../sidebar/smart-attention.test.ts | 48 +++++++++++++++++++ .../src/components/sidebar/smart-attention.ts | 7 ++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/sidebar/smart-attention.test.ts b/src/renderer/src/components/sidebar/smart-attention.test.ts index 09f64c758d19..d32192d36a58 100644 --- a/src/renderer/src/components/sidebar/smart-attention.test.ts +++ b/src/renderer/src/components/sidebar/smart-attention.test.ts @@ -605,6 +605,54 @@ describe('buildAttentionByWorktree', () => { }) }) + it('does not revive a restored row from one title before layout hydration', () => { + const w = makeWorktree('wt-1') + const tab = makeTab('tab-1', w.id) + const key = paneKey(tab.id, LEAF_1) + const map = buildAttentionByWorktree( + [w], + { [w.id]: [tab] }, + { + [key]: makeEntry({ + paneKey: key, + state: 'working', + restoredUnconfirmed: true + }) + }, + { [tab.id]: { 1: '⠋ Claude' } }, + ptyMap([tab.id]), + NOW + ) + + expect(map.get(w.id)).toEqual(IDLE) + }) + + it('still uses one unmapped title when the hook is only age-stale', () => { + const w = makeWorktree('wt-1') + const tab = makeTab('tab-1', w.id) + const key = paneKey(tab.id, LEAF_1) + const map = buildAttentionByWorktree( + [w], + { [w.id]: [tab] }, + { + [key]: makeEntry({ + paneKey: key, + state: 'working', + updatedAt: NOW - AGENT_STATUS_STALE_AFTER_MS - 1 + }) + }, + { [tab.id]: { 1: '✋ Gemini CLI' } }, + ptyMap([tab.id]), + NOW + ) + + expect(map.get(w.id)).toEqual({ + cls: 1, + attentionTimestamp: NOW, + cause: 'title-heuristic' + }) + }) + it('per-pane authority across panes: pane A fresh hook=done, pane B no hook + permission title → Class 1', () => { const w = makeWorktree('wt-1') const tab = makeTab('tab-1', w.id) diff --git a/src/renderer/src/components/sidebar/smart-attention.ts b/src/renderer/src/components/sidebar/smart-attention.ts index be8920676d1d..6c102a414058 100644 --- a/src/renderer/src/components/sidebar/smart-attention.ts +++ b/src/renderer/src/components/sidebar/smart-attention.ts @@ -311,9 +311,12 @@ export function buildAttentionByWorktree( if (paneTitles && Object.keys(paneTitles).length > 0) { // Why: split-pane tabs host multiple agents, one title each; mirrors getWorkingAgentsPerWorktree precedence. const tabLayout = terminalLayoutsByTabId?.[tab.id] - for (const [runtimePaneId, title] of Object.entries(paneTitles)) { + const paneTitleEntries = Object.entries(paneTitles) + for (const [runtimePaneId, title] of paneTitleEntries) { const leafId = resolveRuntimePaneTitleLeafId(tabLayout, runtimePaneId) - if (leafId !== null && hookLeafIds.has(leafId)) { + const hasSingleUnmappedHook = + leafId === null && hookLeafIds.size === 1 && paneTitleEntries.length === 1 + if ((leafId !== null && hookLeafIds.has(leafId)) || hasSingleUnmappedHook) { continue } panes.push({