fix(notifications): hold the finished notification while a Codex goal keeps running (#42838)

* fix(notifications): hold Codex completion while its goal keeps running

Codex starts the next goal turn by itself, so a successful turn that
settles while the thread goal is active is not the end of the work.
The SQL observer now reports when the newest goal row is an active
Codex goal on a live generation, and the completion feed holds success
until that stops. Claude goals finish within one turn and never hold.

Co-authored-by: BingX <22970633+bing-xbx@users.noreply.github.com>

* fix(notifications): announce a goal turn that ends on an open async question

---------

Co-authored-by: BingX <22970633+bing-xbx@users.noreply.github.com>
This commit is contained in:
Kelvin Amoaba
2026-11-15 23:12:37 +00:00
committed by GitHub
co-authored by BingX
parent df15cdfe89
commit 1b82ef66d6
6 changed files with 130 additions and 7 deletions
@@ -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
@@ -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<string, unknown>): AgentJournalRenderItem {
@@ -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,
{
@@ -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<typeof provider.appendItem>[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()
}
})
@@ -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))
@@ -80,6 +80,15 @@ export function currentAgentSessionThreadGoalSourceBySequence<T extends GoalCand
return latest === null ? undefined : { item: latest, goal: goalFromRow(latest.body) }
}
/** Codex starts the next turn itself while its goal is active; Claude pursues a goal within one turn. */
export function agentSessionThreadGoalStartsTurns(item: GoalCandidate | undefined): boolean {
return (
item?.body.kind === 'status' &&
isAgentSessionThreadGoalFrame(item.body.providerFrame) &&
currentAgentSessionThreadGoal([item])?.status === 'active'
)
}
/** Goal statuses that still describe work in progress, so readers keep them in view. */
export function isAgentSessionThreadGoalOpen(goal: AgentJournalThreadGoal | null): boolean {
return goal !== null && goal.status !== 'complete'