Skip to content
5 changes: 5 additions & 0 deletions src/main/agent-hooks/server-closed-tab-suppression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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)
Expand Down
36 changes: 36 additions & 0 deletions src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => ({
Expand Down Expand Up @@ -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' })
Expand Down
94 changes: 94 additions & 0 deletions src/main/agent-hooks/server-program-status-hook-yield.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -47,6 +48,14 @@ async function openCodeHook(hookEventName: string): Promise<void> {
expect(response.status).toBe(204)
}

async function antigravityHook(
hookEventName: string,
payload: Record<string, unknown>
): Promise<void> {
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]
}
Expand Down Expand Up @@ -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'] })
Expand Down
94 changes: 94 additions & 0 deletions src/main/agent-hooks/server-turn-ended-at.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() }))
Expand Down Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion src/main/agent-hooks/server.test-fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export function recentTs(offsetMs = 0): number {
}

export async function postHookEvent(
server: AgentHookServer,
server: Pick<AgentHookServer, 'buildPtyEnv'>,
body: Body,
path: string = '/hook/claude'
): Promise<Response> {
Expand Down
11 changes: 11 additions & 0 deletions src/main/agent-hooks/server/program-status/hook-precedence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' })
Expand Down
9 changes: 7 additions & 2 deletions src/main/agent-hooks/server/program-status/hook-precedence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 2 additions & 1 deletion src/main/agent-hooks/server/server-tab-cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading