diff --git a/src/main/agent-hooks/server-closed-tab-suppression.test.ts b/src/main/agent-hooks/server-closed-tab-suppression.test.ts index 796a9420c71d..2dc470491d16 100644 --- a/src/main/agent-hooks/server-closed-tab-suppression.test.ts +++ b/src/main/agent-hooks/server-closed-tab-suppression.test.ts @@ -81,6 +81,10 @@ describe('AgentHookServer listener replay', () => { state.lastPromptByPaneKey.set(PANE, 'cached prompt') state.lastToolByPaneKey.set(`${sameTabPane}\0tool`, {} as never) state.antigravityCompletedTranscriptByPaneKey.set(`${sameTabPane}\0done`, 'cached') + state.antigravityMainAgentStatusByPaneKey.set(`${sameTabPane}\0lead`, { + state: 'working', + stateStartedAt: 1 + }) state.ampCompletedCacheKeys.add(`${sameTabPane}\0amp`) state.lastPromptByPaneKey.set(siblingPrefixPane, 'sibling prompt') internals.assistantMessageRetryTimers.set(PANE, setTimeout(sameTabRetry, 1_000)) @@ -100,6 +104,7 @@ describe('AgentHookServer listener replay', () => { expect(state.lastPromptByPaneKey.has(PANE)).toBe(false) expect(state.lastToolByPaneKey.has(`${sameTabPane}\0tool`)).toBe(false) expect(state.antigravityCompletedTranscriptByPaneKey.has(`${sameTabPane}\0done`)).toBe(false) + expect(state.antigravityMainAgentStatusByPaneKey.has(`${sameTabPane}\0lead`)).toBe(false) expect(state.ampCompletedCacheKeys.has(`${sameTabPane}\0amp`)).toBe(false) expect(state.lastPromptByPaneKey.get(siblingPrefixPane)).toBe('sibling prompt') expect(internals.assistantMessageRetryTimers.has(PANE)).toBe(false) diff --git a/src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts b/src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts index e57185ddd354..afbbb81ebd5c 100644 --- a/src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts +++ b/src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts @@ -3,6 +3,9 @@ import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { AgentHookServer, _internals } from './server' +import { resolveCancelVerdictLatch } from '../../shared/agent-hook-cancel-verdict-latch' +import { AGENT_TURN_OUTCOMES } from '../../shared/agent-turn-outcome' +import { normalizeAgentStatusPayload } from '../../shared/agent-status-types' import { buildBody, postHookEvent, PANE } from './server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ @@ -45,6 +48,39 @@ describe('main agent turn verdicts and clocks', () => { expect(response.status).toBe(204) } + it('holds only unknown validated outcomes inside the existing cancellation window', () => { + const event = { + paneKey: PANE, + tabId: 'tab-1', + connectionId: null, + source: 'grok' as const, + hookEventName: 'stop', + payload: normalizeAgentStatusPayload({ + state: 'done', + prompt: 'go', + agentType: 'grok', + interrupted: true, + mainAgent: { state: 'done', stateStartedAt: 1, outcome: 'cancellation' } + })! + } + const previous = { ...event, receivedAt: Date.now() } + const unknown = [undefined, 'newer-outcome', 42] + for (const outcome of [...unknown, ...AGENT_TURN_OUTCOMES]) { + const payload = normalizeAgentStatusPayload({ + ...event.payload, + interrupted: undefined, + mainAgent: { state: 'done', stateStartedAt: 1, outcome } + })! + const incoming = { ...event, payload } + expect(resolveCancelVerdictLatch(previous, incoming, previous.receivedAt).hold).toBe( + unknown.includes(outcome) + ) + expect(resolveCancelVerdictLatch(previous, incoming, previous.receivedAt + 15_001).hold).toBe( + false + ) + } + }) + it('starts a new Claude session with its own main agent clock', async () => { await post('/hook/claude', { hook_event_name: 'UserPromptSubmit', prompt: 'first' }) await post('/hook/claude', { hook_event_name: 'Stop' }) diff --git a/src/main/agent-hooks/server-program-status-hook-yield.test.ts b/src/main/agent-hooks/server-program-status-hook-yield.test.ts index e1ba6bfc888a..b46859a43b4d 100644 --- a/src/main/agent-hooks/server-program-status-hook-yield.test.ts +++ b/src/main/agent-hooks/server-program-status-hook-yield.test.ts @@ -7,6 +7,7 @@ import { buildBody, PANE, postHookEvent } from './server.test-fixtures' import type { ParsedAgentStatusPayload } from '../../shared/agent-status-types' import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from './server/program-status/hook-precedence' import { resolveProgramStatusPresentation } from '../../shared/program-status/presentation' +import { createProgramStatusProjector } from '../../shared/program-status/agent-status-projector' let dir: string let server: AgentHookServer @@ -47,6 +48,14 @@ async function openCodeHook(hookEventName: string): Promise { expect(response.status).toBe(204) } +async function antigravityHook( + hookEventName: string, + payload: Record +): Promise { + const body = Object.assign(buildBody(payload), { hook_event_name: hookEventName }) + expect((await postHookEvent(server, body, '/hook/antigravity')).status).toBe(204) +} + function paneRow() { return server.getStatusSnapshotForPane(PANE)[0] } @@ -111,6 +120,91 @@ describe('OSC 7501 status beside hooks', () => { expect(paneRow()?.state).toBe('done') }) + // #33973: agy reports its own turn over OSC 7501 but never the in-process subagents it waits on. + it.each([true, false])( + 'keeps live Antigravity children past root done (mainAgent=%s)', + async (withMainAgent) => { + const parent = { conversationId: 'parent', lastUserInput: 'translate' } + await antigravityHook('PreInvocation', parent) + await antigravityHook('Stop', { ...parent, fullyIdle: false }) + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + programStatus({ + state: 'done', + agentType: 'antigravity', + mainAgent: withMainAgent + ? { state: 'done', outcome: 'success', stateStartedAt: Date.now() } + : undefined + }) + vi.advanceTimersByTime(HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS + 1) + expect(paneRow()).toMatchObject({ state: 'working', mainAgent: { state: 'done' } }) + vi.useRealTimers() + await antigravityHook('PreInvocation', parent) + await antigravityHook('Stop', { ...parent, fullyIdle: true }) + expect(paneRow()?.state).toBe('done') + } + ) + + it('keeps a completed Antigravity transcript settled after a delayed busy Stop', async () => { + const parent = { + conversationId: 'parent', + lastUserInput: 'translate', + transcriptPath: join(dir, 'parent.jsonl') + } + await antigravityHook('PreInvocation', parent) + await antigravityHook('Stop', { ...parent, fullyIdle: true }) + expect(paneRow()?.state).toBe('done') + await antigravityHook('Stop', { ...parent, fullyIdle: false }) + expect(paneRow()?.state).toBe('done') + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + programStatus({ + state: 'done', + agentType: 'antigravity', + mainAgent: { state: 'done', outcome: 'success', stateStartedAt: Date.now() } + }) + vi.advanceTimersByTime(HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS + 1) + expect(paneRow()?.state).toBe('done') + vi.useRealTimers() + await antigravityHook('PreInvocation', parent) + await antigravityHook('Stop', { ...parent, fullyIdle: false }) + expect(paneRow()?.state).toBe('working') + await antigravityHook('PreInvocation', parent) + expect(paneRow()).toMatchObject({ state: 'working', mainAgent: { state: 'working' } }) + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + programStatus({ state: 'done', agentType: 'antigravity' }) + vi.advanceTimersByTime(HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS + 1) + expect(paneRow()?.state).toBe('done') + }) + + it('takes an explicit OSC child question after the hooks fall silent on child work', async () => { + for (const payload of [ + { hook_event_name: 'UserPromptSubmit', session_id: 'parent', prompt: 'delegate' }, + { + hook_event_name: 'PostToolUse', + session_id: 'parent', + tool_name: 'Agent', + tool_response: { isAsync: true, agentId: 'child' } + }, + { + hook_event_name: 'Stop', + session_id: 'parent', + background_tasks: [{ id: 'child', type: 'subagent', status: 'running' }] + } + ]) { + expect((await postHookEvent(server, buildBody(payload))).status).toBe(204) + } + expect(paneRow()).toMatchObject({ state: 'working', mainAgent: { state: 'done' } }) + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + const { payloads } = createProgramStatusProjector().process( + '\x1b]7501;state=done:app=claude-code\x1b\\' + + '\x1b]7501;state=blocked:kind=question:id=child\x1b\\' + ) + for (const { payload } of payloads) { + programStatus(payload) + } + vi.advanceTimersByTime(HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS + 1) + expect(paneRow()).toMatchObject({ state: 'waiting', subagents: [{ state: 'waiting' }] }) + }) + it('never settles a later hook turn with a report that yielded to an earlier one', async () => { await openCodeHook('SessionBusy') vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) diff --git a/src/main/agent-hooks/server-turn-ended-at.test.ts b/src/main/agent-hooks/server-turn-ended-at.test.ts index 535477cfbc0a..cd0877401d4b 100644 --- a/src/main/agent-hooks/server-turn-ended-at.test.ts +++ b/src/main/agent-hooks/server-turn-ended-at.test.ts @@ -3,6 +3,8 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { AgentHookServer, _internals } from './server' +import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' +import { agentVerdictDisplayMark } from '../../shared/agent-main-agent-verdict' import { buildBody, postHookEvent, PANE } from './server.test-fixtures' vi.mock('../telemetry/client', () => ({ track: vi.fn() })) @@ -162,6 +164,98 @@ describe('the host-stamped turn end', () => { expect(row()).toMatchObject({ turnEndedAt: ended, turnEndDisposition: 'identified' }) }) + it.each(['desktop', 'relay'])( + 'recovers final text, supersedes retries and retains inferred cancellation through %s', + async (route) => { + const relay = new RelayAgentHookServer({ + endpointDir: join(directory, 'relay'), + forward: (event) => server.ingestRemote(event, 'connection') + }) + await relay.start() + const transcriptPath = join(directory, 'antigravity-final.jsonl') + const parent = { conversationId: 'parent', transcriptPath, lastUserInput: 'Translate it' } + const hook = async (hook_event_name: string) => { + if (vi.isFakeTimers()) { + vi.advanceTimersByTime(1) + } + const response = await postHookEvent( + route === 'desktop' ? server : relay, + buildBody({ + hook_event_name, + ...parent, + fullyIdle: true, + terminationReason: 'NO_TOOL_CALL' + }), + '/hook/antigravity' + ) + expect(response.status).toBe(204) + } + const request = `${JSON.stringify({ source: 'USER_EXPLICIT', type: 'USER_INPUT', content: parent.lastUserInput })}\n` + const flush = (content: string) => + writeFileSync( + transcriptPath, + `${request}${JSON.stringify({ source: 'MODEL', type: 'PLANNER_RESPONSE', content })}\n` + ) + writeFileSync(transcriptPath, request) + try { + await hook('PreInvocation') + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + await hook('Stop') + const ended = row()! + expect(ended).toMatchObject({ state: 'done', turnEndDisposition: 'identified' }) + expect(ended.lastAssistantMessage).toBeUndefined() + flush('PARENT_FINAL_REPORT') + vi.advanceTimersByTime(300) + expect(row()).toMatchObject({ + turnEndedAt: ended.turnEndedAt, + stateStartedAt: ended.stateStartedAt, + lastAssistantMessage: 'PARENT_FINAL_REPORT' + }) + expect(row()?.mainAgent).toEqual(ended.mainAgent) + writeFileSync(transcriptPath, request) + await hook('PreInvocation') + await hook('Stop') + const supersededEnd = row()?.turnEndedAt + await hook('PreInvocation') + flush('OLD_REPORT') + vi.advanceTimersByTime(300) + expect(row()).toMatchObject({ state: 'working' }) + expect(row()?.lastAssistantMessage).toBeUndefined() + flush('NEW_REPORT') + await hook('Stop') + expect(row()).toMatchObject({ state: 'done', lastAssistantMessage: 'NEW_REPORT' }) + expect(row()?.turnEndedAt).toBeGreaterThan(supersededEnd!) + writeFileSync(transcriptPath, request) + await hook('PreInvocation') + const baseline = row()! + vi.advanceTimersByTime(500) + expect( + server.inferInterrupt({ + paneKey: PANE, + baselineUpdatedAt: baseline.receivedAt, + baselineStateStartedAt: baseline.stateStartedAt, + baselinePrompt: baseline.prompt, + baselineAgentType: 'antigravity', + intent: 'ctrl-c' + }) + ).toBe(true) + expect(agentVerdictDisplayMark(row()!)).toBe('interrupted') + flush('DELAYED_STOP') + await hook('Stop') + expect(agentVerdictDisplayMark(row()!)).toBe('interrupted') + await hook('PreInvocation') + expect(row()).toMatchObject({ state: 'working' }) + flush('NEXT_RESULT') + await hook('Stop') + expect(row()).toMatchObject({ state: 'done', lastAssistantMessage: 'NEXT_RESULT' }) + expect(agentVerdictDisplayMark(row()!)).toBeNull() + } finally { + vi.useRealTimers() + relay.stop() + } + } + ) + it('reaches the live push and survives a host restart, so a restatement stays the same end', async () => { const pushed: (number | undefined)[] = [] server.setListener((status) => pushed.push(status.turnEndedAt)) diff --git a/src/main/agent-hooks/server.test-fixtures.ts b/src/main/agent-hooks/server.test-fixtures.ts index 2eeffa803488..25afb610feb5 100644 --- a/src/main/agent-hooks/server.test-fixtures.ts +++ b/src/main/agent-hooks/server.test-fixtures.ts @@ -48,7 +48,7 @@ export function recentTs(offsetMs = 0): number { } export async function postHookEvent( - server: AgentHookServer, + server: Pick, body: Body, path: string = '/hook/claude' ): Promise { diff --git a/src/main/agent-hooks/server/program-status/hook-precedence.test.ts b/src/main/agent-hooks/server/program-status/hook-precedence.test.ts index c873db8f785e..d6d59edc10a6 100644 --- a/src/main/agent-hooks/server/program-status/hook-precedence.test.ts +++ b/src/main/agent-hooks/server/program-status/hook-precedence.test.ts @@ -80,6 +80,17 @@ describe('programStatusHookYieldEndsAt', () => { expect(programStatusHookYieldEndsAt(hook, heldOpen, NOW + 1)).toBe(Infinity) }) + it('keeps finite session and other-agent fallback when the lead is done', () => { + const leadDone = { state: 'done' as const, outcome: 'success' as const, stateStartedAt: NOW } + const hook = row({ state: 'working', agentType: 'antigravity', mainAgent: leadDone }) + const done = report({ state: 'done', agentType: 'antigravity', mainAgent: leadDone }) + // A program that ended, or another app's report, keeps the silence fallback. + expect( + programStatusHookYieldEndsAt(hook, { ...done, mainAgent: undefined, sessionBoundary: true }) + ).toBe(NOW + SILENCE) + expect(programStatusHookYieldEndsAt(hook, { ...done, agentType: 'claude' })).toBe(NOW + SILENCE) + }) + it('keeps a question the hooks raised only from a working report that began before it', () => { for (const state of ['waiting', 'blocked'] as const) { const hook = row({ state, agentType: 'pi' }) diff --git a/src/main/agent-hooks/server/program-status/hook-precedence.ts b/src/main/agent-hooks/server/program-status/hook-precedence.ts index df80f7f8bbe0..681ecd1709c7 100644 --- a/src/main/agent-hooks/server/program-status/hook-precedence.ts +++ b/src/main/agent-hooks/server/program-status/hook-precedence.ts @@ -20,10 +20,15 @@ export function programStatusHookYieldEndsAt( if (!sameAgent && previous.payload.state === 'done') { return undefined } - // Why: the hook lane tracks its own children; a program's child roster must not reopen the hook's settled turn. + // Why: the hook lane tracks its own children; a program's child roster must not reopen the hook's settled turn, + // and a program's own done, which may omit children it runs in-process, must not settle a turn they hold open. if ( payload.state === previous.payload.state || - (previous.payload.state === 'done' && isAgentStatusHeldOpenByChildWork(payload)) + (previous.payload.state === 'done' && isAgentStatusHeldOpenByChildWork(payload)) || + (sameAgent && + isAgentStatusHeldOpenByChildWork(previous.payload) && + payload.state === 'done' && + payload.sessionBoundary !== true) ) { return Infinity } diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index d2cfb010354d..71304f383b26 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -65,7 +65,8 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { } for (const key of [ ...this.state.antigravityCompletedTranscriptByPaneKey.keys(), - ...this.state.antigravitySubagentParentByPaneKey.keys() + ...this.state.antigravitySubagentParentByPaneKey.keys(), + ...this.state.antigravityMainAgentStatusByPaneKey.keys() ]) { if (paneCacheKeyMatchesTab(key, tabId)) { paneKeysToClear.add(key.split('\0', 1)[0] ?? key) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-main-agent-fact.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-main-agent-fact.test.ts index ae1d0d176181..9a9083497e7b 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-main-agent-fact.test.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-main-agent-fact.test.ts @@ -1,4 +1,12 @@ import { describe, expect, it } from 'vitest' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener' +import { hookRowAgentPhase } from '../../../../../shared/agent-transitions' +import { resolveTerminalTabActivityStatus } from '../../../components/tab-bar/terminal-tab-activity-status' +import { selectAutomationRunOutputSnapshot } from '../../../components/automations/automation-run-output-snapshot' import { normalizeAgentStatusEvent } from '../../../hooks/ipc-events/normalize-agent-status-event' import { createTestStore } from '../store-test-helpers' @@ -16,6 +24,67 @@ function osc(revision: number) { } describe('the main agent fact on a renderer status entry', () => { + it.each([false, true])('projects the captured parent/child turn (old relay=%s)', (oldRelay) => { + const dir = mkdtempSync(join(tmpdir(), 'agy-consumer-')) + const transcriptPath = join(dir, 'parent.jsonl') + const parent = { conversationId: 'parent', lastUserInput: 'translate', transcriptPath } + const child = { conversationId: 'child', lastUserInput: '' } + const toolCall = { name: 'invoke_subagent', args: { TypeName: 'self', Prompt: 'fr' } } + const tab = { id: 'tab-1', title: '' } + const listener = createHookListenerState() + const store = createTestStore() + writeFileSync( + transcriptPath, + JSON.stringify({ source: 'MODEL', type: 'PLANNER_RESPONSE', content: 'Parent final report' }) + ) + try { + for (const [hook_event_name, payload, expected, lead] of [ + ['PreInvocation', parent, 'working', 'working'], + ['PreToolUse', { ...parent, toolCall }, 'working', 'working'], + ['PostToolUse', { ...parent, toolCall }, 'working', 'working'], + ['PreInvocation', child, null, null], + ['Stop', { ...parent, fullyIdle: false }, 'working', 'done'], + ['PostInvocation', child, null, null], + ['Stop', { ...child, fullyIdle: true }, null, null], + ['PreInvocation', parent, 'working', 'working'], + ['Stop', { ...parent, fullyIdle: true }, 'done', 'done'], + ['PreInvocation', { conversationId: 'next', lastUserInput: 'next' }, 'working', 'working'] + ] as const) { + const event = normalizeHookPayload( + listener, + 'antigravity', + { paneKey: PANE, hook_event_name, payload }, + 'production' + ) + expect(event?.payload.state ?? null).toBe(expected) + if (!event) { + continue + } + const normalized = normalizeAgentStatusEvent({ + ...event.payload, + paneKey: PANE, + connectionId: null, + receivedAt: 1_000_000, + stateStartedAt: 1_000_000, + mainAgent: oldRelay ? undefined : event.payload.mainAgent + })! + store.getState().setAgentStatus(PANE, normalized) + const { agentStatusByPaneKey } = store.getState() + const entry = agentStatusByPaneKey[PANE] + expect(resolveTerminalTabActivityStatus({ tab, agentStatusByPaneKey })).toBe(expected) + expect(hookRowAgentPhase(entry)).toBe(expected) + expect(entry.mainAgent?.state).toBe(oldRelay ? undefined : lead) + if (expected === 'done') { + expect(entry.stateHistory.every((item) => item.state === 'working')).toBe(true) + const output = selectAutomationRunOutputSnapshot(entry.lastAssistantMessage, null) + expect(output?.content).toBe('Parent final report') + } + } + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + it('lands on the entry from the IPC payload and is reused by reference when unchanged', () => { const store = createTestStore() const mainAgent = { state: 'done' as const, outcome: 'failure' as const, stateStartedAt: 5 } diff --git a/src/shared/agent-hook-cancel-verdict-latch.ts b/src/shared/agent-hook-cancel-verdict-latch.ts index 4936f967a837..60c5d51f95ac 100644 --- a/src/shared/agent-hook-cancel-verdict-latch.ts +++ b/src/shared/agent-hook-cancel-verdict-latch.ts @@ -1,5 +1,6 @@ import type { AgentHookEventPayload } from './agent-hook-listener/listener-event' import type { AgentMainAgentStatus } from './agent-status-types' +import { isAgentTurnOutcome } from './agent-turn-outcome' import { foldMainAgentWithRowChildWork } from './agent-hook-row-child-work-fold' const INTERRUPTED_DONE_LATE_WORKING_SUPPRESSION_MS = 15_000 @@ -105,7 +106,8 @@ export function resolveCancelVerdictLatch( !isCancelVerdictLatched(previous) || previous.payload.agentType !== incoming.payload.agentType || restatesAnotherPrompt(previous, incoming) || - incoming.payload.mainAgent?.state === 'done' || + (incoming.payload.mainAgent?.state === 'done' && + isAgentTurnOutcome(incoming.payload.mainAgent.outcome)) || opensNewTurn(incoming) ) { return apply diff --git a/src/shared/agent-hook-listener-extraction-characterization.test.ts b/src/shared/agent-hook-listener-extraction-characterization.test.ts index aada0f643d16..5716736a30ae 100644 --- a/src/shared/agent-hook-listener-extraction-characterization.test.ts +++ b/src/shared/agent-hook-listener-extraction-characterization.test.ts @@ -16,6 +16,14 @@ import { makePaneKey } from './stable-pane-id' const PANE = makePaneKey('tab-hooks', '11111111-1111-4111-8112-111111111111') const MOVED_PANE = makePaneKey('tab-hooks', '22222222-2222-4222-8222-222222222222') +function agyLead(state: ReturnType, paneKey = PANE) { + return normalizeHookPayload( + state, + 'antigravity', + { paneKey, hook_event_name: 'PostInvocation', payload: {} }, + 'production' + )?.payload.mainAgent +} function normalizeProviderState( source: AgentHookSource, eventName: string, @@ -181,6 +189,7 @@ describe('agent hook extraction boundaries', () => { set.add(sibling) } + state.antigravityMainAgentStatusByPaneKey.set(PANE, { state: 'working', stateStartedAt: 1 }) movePaneCacheState(state, PANE, MOVED_PANE) for (const map of paneMaps) { @@ -206,6 +215,8 @@ describe('agent hook extraction boundaries', () => { movePaneCacheState(state, MOVED_PANE, MOVED_PANE) expect((state.lastPromptByPaneKey as Map).get(MOVED_PANE)).toBe('exact') + expect(agyLead(state, MOVED_PANE)).toEqual({ state: 'working', stateStartedAt: 1 }) + expect(agyLead(state)?.stateStartedAt).not.toBe(1) }) it('preserves bound OpenCode session ownership and launch identity after a pane move', () => { @@ -275,6 +286,7 @@ describe('agent hook extraction boundaries', () => { state.codexLeadStateByPaneKey.set(PANE, { state: 'working', stateStartedAt: 1 }) state.grokActiveTurnByPaneKey.set(PANE, { promptId: 'prompt-1' }) + state.antigravityMainAgentStatusByPaneKey.set(PANE, { state: 'working', stateStartedAt: 1 }) clearPaneCacheState(state, PANE) for (const map of paneMaps) { @@ -292,6 +304,7 @@ describe('agent hook extraction boundaries', () => { expect(state.claudeLeadStateByPaneKey.has(PANE)).toBe(false) expect(state.codexLeadStateByPaneKey.has(PANE)).toBe(false) expect(state.grokActiveTurnByPaneKey.has(PANE)).toBe(false) + expect(agyLead(state)?.stateStartedAt).not.toBe(1) }) it('preserves cache mutation from a provider reset that emits no row', () => { @@ -304,6 +317,7 @@ describe('agent hook extraction boundaries', () => { payload: { state: 'working', prompt: 'old status' } }) + state.antigravityMainAgentStatusByPaneKey.set(PANE, { state: 'working', stateStartedAt: 1 }) const event = normalizeHookPayload( state, 'droid', @@ -315,6 +329,7 @@ describe('agent hook extraction boundaries', () => { expect(state.lastPromptByPaneKey.has(PANE)).toBe(false) expect(state.lastToolByPaneKey.has(PANE)).toBe(false) expect(state.lastStatusByPaneKey.has(PANE)).toBe(true) + expect(agyLead(state)?.stateStartedAt).not.toBe(1) }) it('clears warning, provider, and lifecycle caches together', () => { @@ -348,6 +363,7 @@ describe('agent hook extraction boundaries', () => { toolName: 'stale-tool' }) + state.antigravityMainAgentStatusByPaneKey.set(PANE, { state: 'working', stateStartedAt: 1 }) clearAllListenerCaches(state) expect(state.warnedVersions.size).toBe(0) @@ -359,5 +375,6 @@ describe('agent hook extraction boundaries', () => { const afterReset = normalizeHookPayload(state, 'muse', notification, 'production') expect(afterReset?.payload).toMatchObject({ state: 'waiting', agentType: 'muse' }) expect(afterReset?.payload.toolName).toBeUndefined() + expect(agyLead(state)?.stateStartedAt).not.toBe(1) }) }) diff --git a/src/shared/agent-hook-listener/listener-state.ts b/src/shared/agent-hook-listener/listener-state.ts index 6a56bbae1ab3..bef0422af0b2 100644 --- a/src/shared/agent-hook-listener/listener-state.ts +++ b/src/shared/agent-hook-listener/listener-state.ts @@ -40,6 +40,8 @@ export type HookListenerState = { antigravityCompletedTranscriptByPaneKey: Map /** Conversation that spawned in-process subagents; kept until its fully idle Stop because children outlive its turns. */ antigravitySubagentParentByPaneKey: Map + /** The Antigravity main agent's own state as last published, so its clock keeps continuity across events. */ + antigravityMainAgentStatusByPaneKey: Map /** Journal-backed prompt for each jcode pane's current turn; see readJcodeTurnPrompt. */ jcodeTurnPromptByPaneKey: Map ampCompletedCacheKeys: Set @@ -126,6 +128,7 @@ export function createHookListenerState( lastStatusByPaneKey: adapter.view, antigravityCompletedTranscriptByPaneKey: new Map(), antigravitySubagentParentByPaneKey: new Map(), + antigravityMainAgentStatusByPaneKey: new Map(), jcodeTurnPromptByPaneKey: new Map(), ampCompletedCacheKeys: new Set(), claudeSubagentRosterByPaneKey: new Map(), @@ -223,6 +226,7 @@ export function clearPaneCacheState(state: HookListenerState, paneKey: string): } deletePaneScopedCacheEntry(state.antigravityCompletedTranscriptByPaneKey, paneKey) deletePaneScopedCacheEntry(state.antigravitySubagentParentByPaneKey, paneKey) + deletePaneScopedCacheEntry(state.antigravityMainAgentStatusByPaneKey, paneKey) deletePaneScopedSetEntry(state.ampCompletedCacheKeys, paneKey) deletePaneScopedCacheEntry(state.claudeConsumedCompactPromptIdByPaneKey, paneKey) state.claudeSubagentRosterByPaneKey.delete(paneKey) @@ -273,6 +277,7 @@ export function movePaneCacheState( moveLegacyAgentStatuses(state, fromPaneKey, toPaneKey) movePaneScopedMapEntries(state.antigravityCompletedTranscriptByPaneKey, fromPaneKey, toPaneKey) movePaneScopedMapEntries(state.antigravitySubagentParentByPaneKey, fromPaneKey, toPaneKey) + movePaneScopedMapEntries(state.antigravityMainAgentStatusByPaneKey, fromPaneKey, toPaneKey) movePaneScopedMapEntries(state.jcodeTurnPromptByPaneKey, fromPaneKey, toPaneKey) movePaneScopedSetEntries(state.ampCompletedCacheKeys, fromPaneKey, toPaneKey) movePaneScopedMapEntries(state.claudeConsumedCompactPromptIdByPaneKey, fromPaneKey, toPaneKey) @@ -301,6 +306,7 @@ export function clearPaneTurnCacheState(state: HookListenerState, paneKey: strin state.lastToolByPaneKey.delete(paneKey) state.antigravityCompletedTranscriptByPaneKey.delete(paneKey) state.antigravitySubagentParentByPaneKey.delete(paneKey) + state.antigravityMainAgentStatusByPaneKey.delete(paneKey) state.jcodeTurnPromptByPaneKey.delete(paneKey) state.ampCompletedCacheKeys.delete(paneKey) state.grokActiveTurnByPaneKey.delete(paneKey) @@ -313,6 +319,7 @@ export function clearAllListenerCaches(state: HookListenerState): void { clearLegacyAgentStatuses(state) state.antigravityCompletedTranscriptByPaneKey.clear() state.antigravitySubagentParentByPaneKey.clear() + state.antigravityMainAgentStatusByPaneKey.clear() state.jcodeTurnPromptByPaneKey.clear() state.ampCompletedCacheKeys.clear() state.claudeConsumedCompactPromptIdByPaneKey.clear() diff --git a/src/shared/agent-hook-listener/providers/antigravity-events.ts b/src/shared/agent-hook-listener/providers/antigravity-events.ts index f30e6c555d56..2331ad4c8129 100644 --- a/src/shared/agent-hook-listener/providers/antigravity-events.ts +++ b/src/shared/agent-hook-listener/providers/antigravity-events.ts @@ -1,3 +1,4 @@ +import { continueMainAgentStatus, foldAgentLeadStatus } from '../../agent-lead-status-fold' import { normalizeAgentStatusPayload, type ParsedAgentStatusPayload @@ -43,25 +44,23 @@ export function normalizeAntigravityEvent( ) { state.antigravitySubagentParentByPaneKey.set(paneKey, conversationId) } + const stopStillBusy = eventName === 'Stop' && isAntigravityStopStillBusy(hookPayload) if (eventName === 'PreInvocation') { state.antigravityCompletedTranscriptByPaneKey.delete(paneKey) } else if ( transcriptPath && - eventName !== 'Stop' && - state.antigravityCompletedTranscriptByPaneKey.get(paneKey) === transcriptPath + state.antigravityCompletedTranscriptByPaneKey.get(paneKey) === transcriptPath && + (eventName !== 'Stop' || stopStillBusy) ) { - // Ignore bookkeeping PostToolUse after Stop so finished rows do not resurrect. + // Completed turns admit idle Stop text enrichment but cannot reopen from delayed hooks. return null } - const stopStillBusy = eventName === 'Stop' && isAntigravityStopStillBusy(hookPayload) - const stateName = + const leadState = eventName === 'PreToolUse' && isAntigravityFeedbackTool(toolName) ? 'waiting' : eventName === 'Stop' - ? stopStillBusy - ? 'working' - : 'done' + ? 'done' : eventName === 'PreInvocation' || eventName === 'PostInvocation' || eventName === 'PreToolUse' || @@ -69,9 +68,20 @@ export function normalizeAntigravityEvent( ? 'working' : null - if (!stateName) { + if (!leadState) { return null } + // fullyIdle=false is agy's own word that background work, such as its subagents, outlives the lead's turn. + const { stateName } = foldAgentLeadStatus({ + leadState, + childWorkLiveness: stopStillBusy ? 'working' : null + }) + const mainAgent = continueMainAgentStatus( + state.antigravityMainAgentStatusByPaneKey.get(paneKey), + { state: leadState }, + Date.now() + ) + state.antigravityMainAgentStatusByPaneKey.set(paneKey, mainAgent) const resetsTurn = isNewTurnEvent('antigravity', eventName) // Cache prompts per turn instead of rescanning large transcripts per hook. @@ -95,7 +105,8 @@ export function normalizeAntigravityEvent( toolInput: snapshot.toolInput, interactivePrompt: snapshot.interactivePrompt, lastAssistantMessage: snapshot.lastAssistantMessage, - lastAssistantMessageIsToolOutput: snapshot.lastAssistantMessageIsToolOutput + lastAssistantMessageIsToolOutput: snapshot.lastAssistantMessageIsToolOutput, + mainAgent }) // Stop between tools can report fullyIdle=false; only an idle Stop is terminal. if (eventName === 'Stop' && !stopStillBusy) {