diff --git a/src/providers/codex.ts b/src/providers/codex.ts index b0c8abe7..89ac5f72 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -1012,9 +1012,9 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { // decodes in agreement instead of back-patching already-emitted calls. // Bounded by one task's calls; flushed at the next task_started and at EOF. let pendingTaskCalls: ParsedProviderCall[] = [] - // The last null-info ping estimate. Measured usage later in the same - // turn and task replaces it, so the turn is one measured call. - let pingEstimate: ParsedProviderCall | null = null + // Null-info ping estimates. Measured usage later in the same turn and + // task replaces all of them, so the turn is measured calls only. + let pingEstimates: ParsedProviderCall[] = [] let taskGeneratedTokens = 0 let taskToolIntervals: Array<[number, number]> = [] let taskStartedAt: number | undefined = resume?.state.taskStartedAt @@ -1052,19 +1052,20 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { const totalTokens = inputTokens + cachedInputTokens + outputTokens + reasoningTokens if (totalTokens === 0) return - const est = pingEstimate - pingEstimate = null - const estIndex = est && est.turnId === currentTurnId ? pendingTaskCalls.indexOf(est) : -1 - if (est && estIndex !== -1) { - pendingTaskCalls.splice(estIndex, 1) - taskGeneratedTokens -= est.outputTokens - pendingTools = [...est.tools, ...pendingTools] - pendingToolSequence = [...(est.toolSequence ?? []), ...pendingToolSequence] - pendingSkills = [...(est.skills ?? []), ...pendingSkills] - pendingUserMessage = est.userMessage || pendingUserMessage - pendingLocAdded += est.locAdded ?? 0 - pendingLocRemoved += est.locRemoved ?? 0 - pendingEditFailed += est.editFailed ?? 0 + const ests = pingEstimates.filter(est => est.turnId === currentTurnId && pendingTaskCalls.includes(est)) + pingEstimates = [] + if (ests.length > 0) { + pendingTaskCalls = pendingTaskCalls.filter(call => !ests.includes(call)) + for (const est of ests) taskGeneratedTokens -= est.outputTokens + pendingTools = [...ests.flatMap(est => est.tools), ...pendingTools] + pendingToolSequence = [...ests.flatMap(est => est.toolSequence ?? []), ...pendingToolSequence] + pendingSkills = [...ests.flatMap(est => est.skills ?? []), ...pendingSkills] + pendingUserMessage = ests.find(est => est.userMessage)?.userMessage || pendingUserMessage + for (const est of ests) { + pendingLocAdded += est.locAdded ?? 0 + pendingLocRemoved += est.locRemoved ?? 0 + pendingEditFailed += est.editFailed ?? 0 + } } if (seenKeys.has(dedupKey)) return @@ -1293,6 +1294,7 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { attachPendingNativeToolEvents(pendingTaskCalls.at(-1)) results.push(...pendingTaskCalls) pendingTaskCalls = [] + pingEstimates = [] taskGeneratedTokens = 0 taskToolIntervals = [] const startedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN @@ -1538,7 +1540,7 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { // prompt pending for the measured call that follows. A turn that // ends on such a ping with nothing after it priced nothing: no call. // After output, the ping estimates the turn until measured usage - // for it arrives (pingEstimate). + // for it arrives (pingEstimates). if (pendingOutputChars === 0) continue const estInput = estimateTokensFromChars(pendingUserMessage.length) const estOutput = estimateTokensFromChars(pendingOutputChars) @@ -1584,7 +1586,7 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { ...(pendingLocRemoved ? { locRemoved: pendingLocRemoved } : {}), ...(pendingEditFailed ? { editFailed: pendingEditFailed } : {}), }) - pingEstimate = pendingTaskCalls.at(-1)! + pingEstimates.push(pendingTaskCalls.at(-1)!) taskGeneratedTokens += estOutput pendingTools = [] diff --git a/tests/providers/codex.test.ts b/tests/providers/codex.test.ts index 52203c03..e46fc6f7 100644 --- a/tests/providers/codex.test.ts +++ b/tests/providers/codex.test.ts @@ -920,15 +920,19 @@ describe('codex provider - JSONL parsing', () => { }) describe('a null-info ping after assistant output', () => { - const lines = (measured: boolean) => [ + const textThenPing = (s: string) => [ + JSON.stringify({ type: 'response_item', timestamp: `2026-04-14T10:00:0${s}Z`, payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'looking at the test now' }] } }), + JSON.stringify({ type: 'event_msg', timestamp: `2026-04-14T10:00:0${s}.5Z`, payload: { type: 'token_count', info: null, rate_limits: { primary: { used_percent: 3 } } } }), + ] + const lines = (measured: boolean, pings: number) => [ sessionMeta({ session_id: 'sess-ping-output', model: 'gpt-5.5' }), userMessage('fix the failing test'), - JSON.stringify({ type: 'response_item', timestamp: '2026-04-14T10:00:03Z', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'looking at the test now' }] } }), - JSON.stringify({ type: 'event_msg', timestamp: '2026-04-14T10:00:04Z', payload: { type: 'token_count', info: null, rate_limits: { primary: { used_percent: 3 } } } }), + ...textThenPing('3'), + ...(pings > 1 ? textThenPing('4') : []), ...(measured ? [tokenCount({ timestamp: '2026-04-14T10:00:05Z', last: { input: 5_000, output: 200 }, total: { input: 5_000, output: 200 } })] : []), ] - const parse = async (measured: boolean) => { - const filePath = await writeSession(tmpDir, '2026-04-14', `rollout-ping-output-${measured}.jsonl`, lines(measured)) + const parse = async (measured: boolean, pings = 1) => { + const filePath = await writeSession(tmpDir, '2026-04-14', `rollout-ping-output-${measured}-${pings}.jsonl`, lines(measured, pings)) const calls: ParsedProviderCall[] = [] for await (const call of createCodexProvider(tmpDir).createSessionParser({ path: filePath, project: 'test', provider: 'codex' }, new Set()).parse()) calls.push(call) return calls @@ -941,6 +945,12 @@ describe('codex provider - JSONL parsing', () => { expect(calls[0]!.costIsEstimated).toBeUndefined() }) + it('yields every ping estimate of the turn to the measured usage', async () => { + const calls = await parse(true, 2) + expect(calls).toHaveLength(1) + expect(calls[0]).toMatchObject({ inputTokens: 5_000, outputTokens: 200, userMessage: 'fix the failing test' }) + }) + it('stays an estimated call when the turn ends without measured usage', async () => { const calls = await parse(false) expect(calls).toHaveLength(1)