diff --git a/src/main/native-chat/agent-session-journal/journal-observer-read.ts b/src/main/native-chat/agent-session-journal/journal-observer-read.ts index 169c5d645b0..88c5e7dde64 100644 --- a/src/main/native-chat/agent-session-journal/journal-observer-read.ts +++ b/src/main/native-chat/agent-session-journal/journal-observer-read.ts @@ -45,7 +45,8 @@ export type JournalObserverResult = { physicalCursor: AgentJournalCursor lastActivityAt: number authority: JournalWorkAuthority - state: JournalStatusState + /** goalContinues: the live provider starts the next turn itself, so a settled success is not the end. */ + state: JournalStatusState & { goalContinues?: true } indicators: JournalStatusIndicators usageLimitCut: HostUsageLimitCut | null orcaStopCut: NativeChatOrcaStopCut | null diff --git a/src/main/native-chat/agent-session-journal/journal-sql-item-reads.ts b/src/main/native-chat/agent-session-journal/journal-sql-item-reads.ts index b0c50ac8364..d163fb32092 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-item-reads.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-item-reads.ts @@ -302,13 +302,17 @@ function readContextUsage(db: Database.Database, prefix: Prefix): AgentSessionCo } /** The newest transition wins; on equal sequence the earlier-admitted row, as a fold scan keeps it. */ -function readThreadGoal(db: Database.Database, prefix: Prefix): JournalThreadGoalSource { +export function readJournalSqlGoalRows(db: Database.Database, prefix: Prefix) { const row = db .prepare(`SELECT payload_json FROM journal_items INDEXED BY journal_items_goal_transition WHERE session_id=? AND epoch=? AND hidden=0 AND goal_transition=1 ORDER BY sequence DESC, ordinal ASC LIMIT 1`) .get(...prefix) - return journalThreadGoalSource(row ? [parseItem(row)] : []) + return row ? [parseItem(row)] : [] +} + +function readThreadGoal(db: Database.Database, prefix: Prefix): JournalThreadGoalSource { + return journalThreadGoalSource(readJournalSqlGoalRows(db, prefix)) } function parseItem(row: Record): AgentJournalRenderItem { diff --git a/src/main/native-chat/agent-session-journal/journal-sql-observer-read.ts b/src/main/native-chat/agent-session-journal/journal-sql-observer-read.ts index ee171eb82f9..3442bcdb43f 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-observer-read.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-observer-read.ts @@ -5,6 +5,8 @@ import type { JournalObserverRead, JournalObserverResult } from './journal-obser import { readJournalSqlStatusState } from './journal-sql-status-state' import { readJournalSqlStatusIndicators } from './journal-sql-status-indicators' import { readJournalSqlUsageLimitCut, readJournalSqlOrcaStopCut } from './journal-sql-status-cuts' +import { readJournalSqlGoalRows } from './journal-sql-item-reads' +import { agentSessionThreadGoalStartsTurns } from '../../../shared/agent-session/agent-session-thread-goal' /** Status, cuts and current work share one ready snapshot and one captured live authority. */ export function readJournalSqlObserver( @@ -13,15 +15,22 @@ export function readJournalSqlObserver( ): JournalObserverResult { const { authority } = input const work = readJournalSqlCurrentWork(context, authority) + const state = withStructuredAgentSessionDiedTurnVerdict( + readJournalSqlStatusState(context, authority.record?.currentFence, work.scope), + work.diedTurn() + ) + // A dead generation starts no next turn, so its active goal cannot hold completion. + const goalContinues = + work.liveFence !== null && + agentSessionThreadGoalStartsTurns( + readJournalSqlGoalRows(context.scope.db, context.scope.prefix)[0] + ) return { cursor: { epoch: context.epoch, sequence: context.sequence }, physicalCursor: { epoch: context.scope.epoch, sequence: context.sequence }, lastActivityAt: context.lastActivityAt, authority, - state: withStructuredAgentSessionDiedTurnVerdict( - readJournalSqlStatusState(context, authority.record?.currentFence, work.scope), - work.diedTurn() - ), + state: goalContinues ? { ...state, goalContinues } : state, indicators: readJournalSqlStatusIndicators( context, { diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-completion.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-completion.test.ts new file mode 100644 index 00000000000..4566bbbe062 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-completion.test.ts @@ -0,0 +1,96 @@ +import { expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalThreadGoalStatus +} from '../../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionTurnCompletionEvent } from '../../../../../shared/agent-session/view/agent-session-turn-completion-wire' +import { unhandledProviderFrameJournalItem } from '../../providers/unhandled-provider-frame' +import { agentJournalSubmissionKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' +import { + HOST_TEST_SESSION, + hostTestAttachParams +} from './structured-agent-session-host-test-data.test-fixture' +import { + createRestTestRig, + REST_TEST_CALLER, + restTestSend +} from './structured-agent-session-rest-test-rig.test-fixture' + +it('announces a Codex goal once, after its automatic turns stop', async () => { + const rig = await createRestTestRig() + try { + const attached = await rig.host.attach(REST_TEST_CALLER, hostTestAttachParams(null)) + if (!attached.ok) { + throw new Error(`attach refused: ${attached.refusal.code}`) + } + const events: AgentSessionTurnCompletionEvent[] = [] + rig.host.subscribeTurnCompletions({ id: 'notifications', emit: (event) => events.push(event) }) + const send = restTestSend('finish the migration', attached.fence) + expect(await rig.host.send(REST_TEST_CALLER, send)).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledOnce()) + const request = rig.adapter.dispatch.mock.calls[0]![0] + const dispatched = await rig.adapter.dispatch.mock.results[0]!.value + if (dispatched.state !== 'accepted' || dispatched.providerIdentity.provider !== 'codex') { + throw new Error('the send was not accepted by Codex') + } + const provider = rig.adapter.acquire.mock.calls.at(-1)![0].events! + const { threadId } = dispatched.providerIdentity + let ordinal = 100 + const append = async (turnId: string, body: Parameters[1]) => { + ordinal += 1 + provider.appendItem({ provider: 'codex', threadId, turnId, ordinal }, body, { + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await rig.host.flushStreamedEvents(HOST_TEST_SESSION) + } + const goal = (turnId: string, status: AgentJournalThreadGoalStatus) => { + const goalRow = unhandledProviderFrameJournalItem( + 'codex', + 'notification:thread/goal/updated', + { + threadId, + turnId, + goal: { + threadId, + objective: 'finish the migration', + status, + tokenBudget: null, + tokensUsed: 10, + timeUsedSeconds: 30, + createdAt: 1789067988, + updatedAt: 1789067988 + } + } + ) + return append(turnId, goalRow!.body) + } + // The completion feed sees each status the host publishes, so this pins every turn edge. + const published = (status: 'working' | 'idle') => + vi.waitFor(() => expect(rig.host.readStatusSummary(HOST_TEST_SESSION)?.status).toBe(status)) + const turn = async (turnId: string, userItemId?: string) => { + const body = { kind: 'turn' as const, turnId, ...(userItemId ? { userItemId } : {}) } + await append(turnId, { ...body, state: 'running' }) + await published('working') + await append(turnId, { ...body, state: 'completed', outcome: 'success' }) + await published('idle') + } + + const first = dispatched.providerIdentity.turnId + await goal(first, 'active') + await turn(first, agentJournalSubmissionKey(request.clientMessageId)) + await turn('continuation') + await goal('continuation', 'complete') + + await vi.waitFor(() => + expect(events.filter((event) => event.type === 'completion')).not.toHaveLength(0) + ) + expect(events).toEqual([ + expect.objectContaining({ + type: 'completion', + completion: expect.objectContaining({ turnId: 'continuation', outcome: 'success' }) + }) + ]) + } finally { + await rig.dispose() + } +}) diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-turn-completion-feed.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-turn-completion-feed.ts index 7aab1f8ab59..f0da99124e8 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-turn-completion-feed.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-turn-completion-feed.ts @@ -238,6 +238,10 @@ export class StructuredAgentSessionTurnCompletionFeed { if (request.outcome !== 'success' || state.summary.status === 'attention') { return false } + // An open async question pauses the goal on the user, so it is news now. + if (state.goalContinues && state.summary.awaitsAnswer !== true) { + return true + } const held = foldAgentLeadStatus({ leadState: 'done', childWorkLiveness: agentChildWorkLiveness(this.deps.readChildWork(sessionId)) diff --git a/src/shared/agent-session/agent-session-thread-goal.ts b/src/shared/agent-session/agent-session-thread-goal.ts index 1bf0cf89848..ab4eb20505d 100644 --- a/src/shared/agent-session/agent-session-thread-goal.ts +++ b/src/shared/agent-session/agent-session-thread-goal.ts @@ -80,6 +80,15 @@ export function currentAgentSessionThreadGoalSourceBySequence