From 7ac33a70c3e9858c142f4f2fac00e6d826c068f0 Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Wed, 11 Nov 2026 21:32:54 +0900 Subject: [PATCH] feat: show generation rate (tok/s) for Codex rounds (#2379) * feat(codex): fill the round footer tok/s from app-server timing Measure each Codex round's generation window the way agy rounds do: the live turn span minus tool-execution and wait-for-the-user windows, over the thread-cumulative output-token delta, emitted on the turn's turn_duration so the round footer shows tok/s. Tool windows prefer the app-server's own item timing (startedAtMs/completedAtMs/durationMs). The token baseline is the last reported cumulative total: the CLI seeds a thread it created in this process (thread/start) to zero, while resumed and forked threads receive the app-server's attach-time usage replay and stay unseeded, so inherited history is never counted as a turn's output. Only the live root-turn feed reaches the ledger: history replays re-project old items and must not settle a round. Permission hooks keep timing waits for the user. * fix(codex): seed gateway-created threads for the first-turn tok/s baseline Native /new and /clear create threads through the gateway before/after hooks, whose after() binds the fresh root without the zero usage seed the runtime create path applies - so the new thread's first turn captured a null baseline and never showed tok/s. Seed it there too, same as create(): thread/start only, since forked threads receive the app-server's attach-time usage replay instead (tiann/hapi#2379). * fix(codex): keep the active generation ledger across a hub-only reconnect SharedCodexRoot's session.onReconnect reset the whole projection, but a hub reconnect only replays final history: the native turn keeps running without a new turn/started, so dropping the ledger identity, baseline and windows made generation.settle() return null at completion and the round permanently lost its tok/s. Add projection.resetAfterHubReconnect which replays without touching the ledger; the app-server reconnect path keeps the full reset, because the resumed turn re-announces itself and must re-measure from its own start (tiann/hapi#2379). * fix(codex): seed fresh usage before session-ready releases queued input The gateway thread/start seed ran in the after() hook, after the bind wrapper had already activated the root: registerControls and emitSessionReady open the input gates, so a queued Web prompt (or one submitted on session-ready while the runner notification is delayed) could start the thread's first turn before the zero baseline existed, and seeding afterward could not repair that captured-null turn. Move the seed into the bind wrapper right after root.bind, guarded by a freshThread flag the create and gateway paths set for thread/start only - forks keep their app-server attach-time replay baseline (tiann/hapi#2379). --- cli/src/codex/shared/permissions.test.ts | 43 ++++ cli/src/codex/shared/permissions.ts | 12 +- cli/src/codex/shared/projection.test.ts | 222 ++++++++++++++++++ cli/src/codex/shared/projection.ts | 85 ++++++- cli/src/codex/shared/root.test.ts | 74 +++++- cli/src/codex/shared/root.ts | 23 +- .../codex/shared/runtime.integration.test.ts | 81 +++++++ cli/src/codex/shared/runtime.ts | 14 +- .../utils/appServerEventConverter.test.ts | 54 +++++ .../codex/utils/appServerEventConverter.ts | 20 +- .../codex/utils/codexGenerationLedger.test.ts | 164 +++++++++++++ cli/src/codex/utils/codexGenerationLedger.ts | 121 ++++++++++ web/src/chat/normalize.test.ts | 21 ++ web/src/chat/normalizeAgent.ts | 7 +- web/src/chat/reducerTimeline.test.ts | 30 +++ web/src/chat/reducerTimeline.ts | 10 +- web/src/chat/types.ts | 2 +- 17 files changed, 963 insertions(+), 20 deletions(-) create mode 100644 cli/src/codex/utils/codexGenerationLedger.test.ts create mode 100644 cli/src/codex/utils/codexGenerationLedger.ts diff --git a/cli/src/codex/shared/permissions.test.ts b/cli/src/codex/shared/permissions.test.ts index 69e93e33..4edfd4f7 100644 --- a/cli/src/codex/shared/permissions.test.ts +++ b/cli/src/codex/shared/permissions.test.ts @@ -83,4 +83,47 @@ describe('shared request arbitration', () => { f.permissions.receive({ id: 2, method: 'future/request', params: { threadId: 'thread' } }); await Promise.resolve(); expect(f.respond).not.toHaveBeenCalled(); }); + + it('times the wait for the user from receive to the answer reaching Codex', async () => { + let waitOpens = 0; + let waitCloses = 0; + const handlers = new Map Promise>(); + const respond = vi.fn(); + const session = { getMetadata: () => ({ codexSessionId: 'thread' }), sendAgentMessage: vi.fn(), + updateAgentState: vi.fn(), + rpcHandlerManager: { registerHandler: (key: string, fn: (raw: unknown) => Promise) => { handlers.set(key, fn); } } + } as unknown as ApiSessionClient; + const permissions = new SharedCodexPermissions(session, { respond } as unknown as CodexAppServerClient, 'generation', + undefined, threadId => { + expect(threadId).toBe('thread'); + waitOpens += 1; + return () => { waitCloses += 1; }; + }); + const request = { id: 1, method: 'item/tool/requestUserInput', params: { threadId: 'thread', turnId: 'turn', itemId: 'call', + questions: [{ id: 'choice', header: 'Choose', question: 'Which?', options: [{ label: 'A', description: 'A' }] }] } }; + permissions.receive(request); + expect(waitOpens).toBe(1); + expect(waitCloses).toBe(0); + const id = Object.keys((session.updateAgentState as ReturnType).mock.calls + .at(-1)![0]({}).requests ?? {})[0]; + await handlers.get('permission')!({ id, approved: true, answers: { choice: ['A'] } }); + await vi.waitFor(() => expect(respond).toHaveBeenCalled()); + expect(waitCloses).toBe(1); + }); + + it('closes the wait when the request is withdrawn without an answer', async () => { + let waitCloses = 0; + const handlers = new Map Promise>(); + const session = { getMetadata: () => ({ codexSessionId: 'thread' }), sendAgentMessage: vi.fn(), + updateAgentState: vi.fn(), + rpcHandlerManager: { registerHandler: (key: string, fn: (raw: unknown) => Promise) => { handlers.set(key, fn); } } + } as unknown as ApiSessionClient; + const permissions = new SharedCodexPermissions(session, { respond: vi.fn() } as unknown as CodexAppServerClient, 'generation', + undefined, () => () => { waitCloses += 1; }); + const request = { id: 1, method: 'item/tool/requestUserInput', params: { threadId: 'thread', turnId: 'turn', itemId: 'call', + questions: [{ id: 'choice', header: 'Choose', question: 'Which?', options: [{ label: 'A', description: 'A' }] }] } }; + permissions.receive(request); + permissions.resolved('thread', request.id); + await vi.waitFor(() => expect(waitCloses).toBe(1)); + }); }); diff --git a/cli/src/codex/shared/permissions.ts b/cli/src/codex/shared/permissions.ts index 2f4cdcf5..9523b99b 100644 --- a/cli/src/codex/shared/permissions.ts +++ b/cli/src/codex/shared/permissions.ts @@ -32,7 +32,8 @@ export class SharedCodexPermissions { } : message, id); } constructor(private readonly session: ApiSessionClient, private readonly client: CodexAppServerClient, private readonly generation: string, - answerAsyncQuestion?: (reply: Reply) => Promise) { + answerAsyncQuestion?: (reply: Reply) => Promise, + private readonly onUserWait?: (threadId: string) => ((endedAt: number) => void) | undefined) { session.rpcHandlerManager.registerHandler(RPC_METHODS.Permission, async (raw: unknown) => { const reply = ReplySchema.parse(raw); if (await answerAsyncQuestion?.(reply)) return; @@ -89,9 +90,14 @@ export class SharedCodexPermissions { }); const handler = handlers.get(request.method); if (!handler) return; + // The wait for the user starts here and ends when the answer reached + // Codex (or the request was withdrawn); hosts time it for the round + // footer's tok/s, which must not count user waits as generation. + const endWait = this.onUserWait?.(threadId) ?? null; let response: unknown; - try { response = handler(request.params); } catch { return; } + try { response = handler(request.params); } catch { endWait?.(Date.now()); return; } void Promise.resolve(response).then(result => { + endWait?.(Date.now()); if (result === IGNORE_SHARED_REQUEST) return; if (this.closed || this.retired.has(key)) return; // No pending entry means a native client already resolved the displayed request. @@ -105,7 +111,7 @@ export class SharedCodexPermissions { this.client.respond(request.id, { answers }); } else this.client.respond(request.id, result); } - }).catch(() => { /* Native resolution/disconnection withdraws, never responds with an error. */ }); + }).catch(() => { endWait?.(Date.now()); /* Native resolution/disconnection withdraws, never responds with an error. */ }); } resolved(threadId: string, nativeId: unknown, status: 'resolved' | 'canceled' = 'resolved'): void { diff --git a/cli/src/codex/shared/projection.test.ts b/cli/src/codex/shared/projection.test.ts index 13b4024c..9540f0fb 100644 --- a/cli/src/codex/shared/projection.test.ts +++ b/cli/src/codex/shared/projection.test.ts @@ -228,6 +228,228 @@ describe('shared history projection', () => { ]); }); + it('fills the live turn duration with generation time and round output tokens', async () => { + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + // Pre-round cumulative usage: the token baseline for the round. + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 1_000 } } + }, undefined, 500); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'turn' } }, undefined, 1_000); + await projection.notification('item/started', { + threadId: 'thread', turnId: 'turn', item: { id: 'cmd', type: 'commandExecution', command: 'ls', startedAtMs: 2_000 } + }, undefined, 2_050); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 1_050 } } + }, undefined, 3_000); + await projection.notification('item/completed', { + threadId: 'thread', turnId: 'turn', item: { id: 'cmd', type: 'commandExecution', status: 'completed', durationMs: 1_800, completedAtMs: 4_000 } + }, undefined, 4_050); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }, undefined, 5_000); + + const durations = send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration'); + // 4 s round, Codex-measured 1.8 s command: 2.2 s of generation for 50 tokens. + expect(durations).toEqual([expect.objectContaining({ + turn_id: 'turn', durationMs: 4_000, generationMs: 2_200, generationOutputTokens: 50 + })]); + }); + + it('omits the generation pair without a pre-turn usage baseline', async () => { + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'turn' } }, undefined, 1_000); + await projection.notification('item/started', { + threadId: 'thread', turnId: 'turn', item: { id: 'cmd', type: 'commandExecution', command: 'ls' } + }, undefined, 1_100); + await projection.notification('item/completed', { + threadId: 'thread', turnId: 'turn', item: { id: 'cmd', type: 'commandExecution', status: 'completed' } + }, undefined, 2_000); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }, undefined, 3_000); + + const durations = send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration'); + expect(durations).toEqual([expect.objectContaining({ turn_id: 'turn', durationMs: 2_000 })]); + expect(durations[0]).not.toHaveProperty('generationMs'); + expect(durations[0]).not.toHaveProperty('generationOutputTokens'); + }); + + it('fills the generation pair for a fresh thread whose usage arrives mid-turn', async () => { + // Mirrors the captured 2026-11-11 16:40 E2E rollout: a new thread's + // first tokenUsage notifications land between turn/started and + // turn/completed (wire shape per codex rust-v0.167.0 + // ThreadTokenUsageUpdatedNotification: camelCase breakdowns). The + // CLI seeds a thread it created in this process to zero right after + // thread/start; resumed or forked threads instead receive the + // app-server's attach-time usage replay. + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + projection.seedFreshUsage(); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'turn' } }, undefined, 1_000); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { outputTokens: 50 } } + }, undefined, 2_000); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { outputTokens: 63 } } + }, undefined, 4_000); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }, undefined, 5_000); + + const durations = send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration'); + expect(durations).toEqual([expect.objectContaining({ + turn_id: 'turn', durationMs: 4_000, generationMs: 4_000, generationOutputTokens: 63 + })]); + }); + + it('preserves the active generation ledger across a hub-only reconnect reset', async () => { + // The hub reconnect replays history with stable IDs, but the native + // turn keeps running without a new turn/started: the active round's + // identity, baseline and windows must survive the reset. + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 100 } } + }, undefined, 500); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'turn' } }, undefined, 1_000); + projection.resetAfterHubReconnect(); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 160 } } + }, undefined, 3_000); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }, undefined, 4_000); + expect(send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration')).toEqual([ + expect.objectContaining({ durationMs: 3_000, generationMs: 3_000, generationOutputTokens: 60 }) + ]); + }); + + it('does not let mid-turn usage stand in for a baseline on a resumed thread', async () => { + // Cold reopen path: a new app-server process resumes with + // excludeTurns, so no usage replay arrives (codex rust-v0.167.0 + // thread_processor.rs skips the replay for excludeTurns resumes). + // The session's token state is still seeded from the rollout, so the + // first mid-turn cumulative total already includes inherited + // history: counting it as this turn's output would overstate tok/s. + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'turn' } }, undefined, 1_000); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { outputTokens: 47_000 } } + }, undefined, 2_000); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { outputTokens: 47_060 } } + }, undefined, 4_000); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }, undefined, 5_000); + + const durations = send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration'); + expect(durations).toEqual([expect.objectContaining({ turn_id: 'turn', durationMs: 4_000 })]); + expect(durations[0]).not.toHaveProperty('generationMs'); + expect(durations[0]).not.toHaveProperty('generationOutputTokens'); + }); + + it('does not let history replay feed the generation ledger', async () => { + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + await projection.history({ + turns: [{ id: 'old', status: 'completed', items: [{ + id: 'cmd', type: 'commandExecution', command: 'long', startedAtMs: 100, completedAtMs: 900, durationMs: 800 + }] }] + }); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 100 } } + }, undefined, 2_000); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'live' } }, undefined, 3_000); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 160 } } + }, undefined, 3_500); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'live', status: 'completed' } }, undefined, 4_000); + + // Replayed tool windows must not shrink the live round's generation time. + expect(send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration')).toEqual([ + expect.objectContaining({ durationMs: 1_000, generationMs: 1_000, generationOutputTokens: 60 }) + ]); + }); + + it('resets the generation ledger when a turn fails and measures the next one', async () => { + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 100 } } + }, undefined, 500); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'a' } }, undefined, 1_000); + await projection.notification('item/started', { + threadId: 'thread', turnId: 'a', item: { id: 'cmd', type: 'commandExecution', command: 'ls' } + }, undefined, 1_100); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'a', status: 'failed' } }, undefined, 2_000); + expect(send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration')).toEqual([]); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 160 } } + }, undefined, 2_500); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'b' } }, undefined, 3_000); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 260 } } + }, undefined, 3_500); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'b', status: 'completed' } }, undefined, 4_000); + + // The failed turn's open tool window must not exclude time from turn b. + expect(send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration')).toEqual([ + expect.objectContaining({ turn_id: 'b', durationMs: 1_000, generationMs: 1_000, generationOutputTokens: 100 }) + ]); + }); + + it('resets the generation ledger when the projection resets on reconnect', async () => { + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 100 } } + }, undefined, 500); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'turn' } }, undefined, 1_000); + await projection.notification('item/started', { + threadId: 'thread', turnId: 'turn', item: { id: 'cmd', type: 'commandExecution', command: 'ls', startedAtMs: 2_000 } + }, undefined, 2_050); + await projection.notification('item/completed', { + threadId: 'thread', turnId: 'turn', item: { id: 'cmd', type: 'commandExecution', status: 'completed', completedAtMs: 3_000 } + }, undefined, 3_050); + // App-server reconnect: the root resets the projection; the ledger must + // drop the pre-disconnect round so the resumed turn re-measures itself. + projection.reset(); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'turn' } }, undefined, 20_000); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 160 } } + }, undefined, 20_500); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }, undefined, 21_000); + + // The round wall clock keeps the upstream stale-start behavior (20000), + // but generation time must be measured from the resume, not the + // pre-disconnect start, and the stale tool window must not subtract. + expect(send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration')).toEqual([ + expect.objectContaining({ durationMs: 20_000, generationMs: 1_000, generationOutputTokens: 60 }) + ]); + }); + + it('times an approval wait into the live round through the host hook', async () => { + const send = vi.fn(); + const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; + const projection = new SharedCodexProjection(session, 'thread', async () => {}); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 0 } } + }, undefined, 500); + await projection.notification('turn/started', { threadId: 'thread', turn: { id: 'turn' } }, undefined, 1_000); + const answered = projection.beginUserWait(2_000); + answered(3_500); + await projection.notification('thread/tokenUsage/updated', { + threadId: 'thread', tokenUsage: { total: { output_tokens: 10 } } + }, undefined, 4_000); + await projection.notification('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }, undefined, 5_000); + + expect(send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration')).toEqual([ + expect.objectContaining({ durationMs: 4_000, generationMs: 2_500, generationOutputTokens: 10 }) + ]); + }); + it('keeps each turn model through settings changes, reconnect replay and rerouting', async () => { const send = vi.fn(); const session = { getMetadata: () => ({}), sendAgentMessage: send } as unknown as ApiSessionClient; diff --git a/cli/src/codex/shared/projection.ts b/cli/src/codex/shared/projection.ts index 5eb38133..d92e9cd1 100644 --- a/cli/src/codex/shared/projection.ts +++ b/cli/src/codex/shared/projection.ts @@ -1,4 +1,5 @@ import { CodexRoundDuration } from '../utils/roundDuration'; +import { CodexGenerationLedger } from '../utils/codexGenerationLedger'; import { createHash } from 'node:crypto'; import type { ApiSessionClient } from '@/api/apiSession'; import { normalizeSessionDisplayTitle } from '@/agent/sessionDisplayRename'; @@ -39,6 +40,7 @@ function metadataHasDisplayTitle(metadata: { name?: string; summary?: { text: st export class SharedCodexProjection { private converter = new AppServerEventConverter(); private readonly roundDuration = new CodexRoundDuration(); + private readonly generation = new CodexGenerationLedger(); private readonly emitted = new Set(); private readonly turns = new Map(); private readonly turnModels = new Map(); @@ -57,7 +59,16 @@ export class SharedCodexProjection { } turnFor(id: string): string | undefined { return this.turns.get(id); } - reset(): void { this.converter = new AppServerEventConverter(); this.emitted.clear(); } + reset(): void { this.converter = new AppServerEventConverter(); this.emitted.clear(); this.generation.reset(); } + + /** + * Hub-only reconnect variant: replay final history with stable IDs, but + * the native turn keeps running without a new turn/started, so the + * active round's ledger identity, baseline and windows must survive. + * Only an app-server reconnect may drop the ledger (reset), because the + * resumed turn re-announces itself and re-measures from its own start. + */ + resetAfterHubReconnect(): void { this.converter = new AppServerEventConverter(); this.emitted.clear(); } private send(body: Record, key: string): void { if (this.emitted.has(key)) return; this.emitted.add(key); @@ -96,19 +107,24 @@ export class SharedCodexProjection { } } } - await this.project(method, params, modelAtReceipt); + await this.project(method, params, modelAtReceipt, false, receivedAt); if (p.threadId === this.threadId && !this.parentThreadId) { const turn = record(p.turn); const turnId = string(turn.id); - if (method === 'turn/started') this.roundDuration.start(turnId, receivedAt); + if (method === 'turn/started') { + this.roundDuration.start(turnId, receivedAt); + this.generation.startTurn(turnId, receivedAt); + } if (method === 'turn/completed') { - const duration = this.roundDuration.finish(turnId, receivedAt, turn.status === 'completed'); - if (duration) this.send(duration, `duration:${turnId}`); + const completed = turn.status === 'completed'; + const duration = this.roundDuration.finish(turnId, receivedAt, completed); + const generation = this.generation.settle(turnId, receivedAt, completed); + if (duration) this.send({ ...duration, ...(generation ?? {}) }, `duration:${turnId}`); } } } - private async project(method: string, params: unknown, modelAtReceipt?: string, fromHistory = false): Promise { + private async project(method: string, params: unknown, modelAtReceipt?: string, fromHistory = false, receivedAt = Date.now()): Promise { if (method.startsWith('codex/event/')) return; const p = record(params); const item = record(p.item); @@ -157,7 +173,11 @@ export class SharedCodexProjection { }, `lifecycle:${turnId}:${method}`); } const events = this.converter.handleNotification(method, params); + // Only a live root-turn feed reaches the generation ledger: history + // replays re-project old items, and child threads summarize nowhere. + const liveRound = !fromHistory && !this.parentThreadId; for (const event of events) { + if (liveRound) this.observeGenerationEvent(event, receivedAt); const callId = string(event.call_id); const key = `${turnId ?? 'thread'}:${itemId ?? callId ?? createHash('sha256').update(JSON.stringify(event)).digest('hex')}:${event.type}`; if (event.type === 'agent_message') send({ type: 'message', message: event.message }, key); @@ -246,6 +266,59 @@ export class SharedCodexProjection { } } + /** + * Feeds one converted live event into the generation ledger: tool item + * lifecycles become excluded windows (Codex's own durations win), and + * token usage updates the thread-cumulative output total. + */ + private observeGenerationEvent(event: Record, receivedAt: number): void { + const callId = string(event.call_id); + const positiveInt = (value: unknown): number | null => { + const parsed = typeof value === 'number' && Number.isSafeInteger(value) ? value : null; + return parsed !== null && parsed > 0 ? parsed : null; + }; + switch (event.type) { + case 'exec_command_begin': + case 'mcp_tool_call_begin': + case 'patch_apply_begin': + case 'codex_tool_call_begin': + if (callId) this.generation.beginTool(callId, positiveInt(event.started_at_ms) ?? receivedAt); + return; + case 'exec_command_end': + case 'mcp_tool_call_end': + case 'patch_apply_end': + case 'codex_tool_call_end': + if (callId) this.generation.endTool(callId, positiveInt(event.completed_at_ms) ?? receivedAt, + typeof event.duration_ms === 'number' ? event.duration_ms : undefined); + return; + case 'token_count': { + const info = record(event.info); + const total = record(info.total ?? info.totalTokenUsage ?? info.total_token_usage); + const raw: unknown = total.outputTokens ?? total.output_tokens; + const output = typeof raw === 'number' && Number.isSafeInteger(raw) && raw >= 0 ? raw : null; + if (output !== null) this.generation.noteTokenUsage(output); + return; + } + } + } + + /** The host's approval hooks: a wait for the user is not generation time. */ + beginUserWait(startedAt: number): (endedAt: number) => void { + return this.generation.beginUserWait(startedAt); + } + + /** + * Seeds a thread this process created (thread/start) to zero cumulative + * usage, making its first turn measurable. Call exactly once right + * after the thread is created and before any turn: resumed and forked + * threads must not be seeded, because their totals arrive through the + * app-server's attach-time usage replay and already include inherited + * history. + */ + seedFreshUsage(): void { + this.generation.noteTokenUsage(0); + } + async history(thread: unknown): Promise { if (record(thread).id === this.threadId) this.summaryThread = thread; const turns = record(thread).turns; diff --git a/cli/src/codex/shared/root.test.ts b/cli/src/codex/shared/root.test.ts index dbc5ee3a..664e9862 100644 --- a/cli/src/codex/shared/root.test.ts +++ b/cli/src/codex/shared/root.test.ts @@ -421,7 +421,79 @@ async function completePlan(f: Awaited>, status = 'co return codexPlanProposalId('thread', turn.id, 'plan-item'); } -describe('shared permission modes', () => { +it('keeps the active round measurable when only the hub reconnects', async () => { + vi.useFakeTimers(); + try { + vi.setSystemTime(1_000_000); + const f = await fixture(); + await f.root.activate(); + const settled = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); await f.drain(); }; + f.native.notify('thread/tokenUsage/updated', { threadId: 'thread', tokenUsage: { total: { output_tokens: 100 } } }); + vi.setSystemTime(1_001_000); + await f.drain(); + f.native.notify('turn/started', { threadId: 'thread', turn: { id: 'turn' } }); + vi.setSystemTime(1_002_000); + await f.drain(); + // Hub-only reconnect: the native turn keeps running without a new + // turn/started, so the active round's ledger identity, baseline + // and windows must survive the replay. + f.reconnect(); + await settled(); + f.native.notify('thread/tokenUsage/updated', { threadId: 'thread', tokenUsage: { total: { output_tokens: 160 } } }); + vi.setSystemTime(1_003_000); + await f.drain(); + f.native.notify('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }); + vi.setSystemTime(1_004_000); + await f.drain(); + expect(f.send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration')).toEqual([ + expect.objectContaining({ durationMs: 2_000, generationMs: 2_000, generationOutputTokens: 60 }) + ]); + } finally { vi.useRealTimers(); } + }); + + it('keeps timing approval waits out of generation after a reconnect', async () => { + vi.useFakeTimers(); + try { + vi.setSystemTime(1_000_000); + const f = await fixture(); + await f.root.activate(); + const settled = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); await f.drain(); }; + f.native.notify('thread/tokenUsage/updated', { threadId: 'thread', tokenUsage: { total: { output_tokens: 100 } } }); + vi.setSystemTime(1_001_000); + await f.drain(); + // App-server reconnect: the re-armed permissions must keep the + // host's user-wait hook, or approval waits count as generation. + await (f.root as unknown as { reconnect(): Promise }).reconnect(); + f.native.notify('turn/started', { threadId: 'thread', turn: { id: 'turn' } }); + vi.setSystemTime(1_002_000); + await f.drain(); + const question: NativeRequest = { id: 'native-question', method: 'item/tool/requestUserInput', params: { + threadId: 'thread', turnId: 'turn', itemId: 'question', + questions: [{ id: 'choice', header: 'Choose', question: 'Which?', options: [{ label: 'A', description: 'A' }] }] + } }; + vi.setSystemTime(1_003_000); + f.native.serverRequest(question); + for (let i = 0; i < 200 && Object.keys(f.state().requests ?? {}).length === 0; i++) await Promise.resolve(); + await f.drain(); + const key = Object.keys(f.state().requests!)[0]; + expect(key, 'approval surfaced after reconnect').toBeTruthy(); + vi.setSystemTime(1_003_500); + await f.rpc.get(RPC_METHODS.Permission)!({ id: key, approved: true, answers: { choice: ['A'] } }); + await settled(); + f.native.notify('thread/tokenUsage/updated', { threadId: 'thread', tokenUsage: { total: { output_tokens: 160 } } }); + vi.setSystemTime(1_004_000); + await f.drain(); + f.native.notify('turn/completed', { threadId: 'thread', turn: { id: 'turn', status: 'completed' } }); + vi.setSystemTime(1_005_000); + await f.drain(); + // 3 s round with a 0.5 s wait for the user: 2.5 s of generation. + expect(f.send.mock.calls.map(([body]) => body).filter(body => body.type === 'turn_duration')).toEqual([ + expect.objectContaining({ durationMs: 3_000, generationMs: 2_500, generationOutputTokens: 60 }) + ]); + } finally { vi.useRealTimers(); } + }); + + describe('shared permission modes', () => { it('switches native auto-review on and back to the human reviewer', async () => { const f = await fixture(); expect((await f.root.applySettings({ permissionMode: 'autoReview' })).applied.permissionMode).toBe('autoReview'); diff --git a/cli/src/codex/shared/root.ts b/cli/src/codex/shared/root.ts index a2e9d80d..6dcd6213 100644 --- a/cli/src/codex/shared/root.ts +++ b/cli/src/codex/shared/root.ts @@ -146,7 +146,9 @@ export class SharedCodexRoot { const wasActivated = Boolean(this.heartbeat); // An emitted socket packet is not a durable hub acknowledgement. // Replay final native history with stable IDs after every reconnect. - this.projection?.reset(); + // The native turn keeps running across a hub-only reconnect, so the + // active generation ledger must survive it. + this.projection?.resetAfterHubReconnect(); this.steeringActive = undefined; this.publishedPlanId = undefined; this.publishedCompactionIds = undefined; @@ -160,6 +162,21 @@ export class SharedCodexRoot { }); } + /** The host's approval hooks: a wait for the user is not generation time. */ + private readonly userWaitFor = (threadId: string): ((endedAt: number) => void) | undefined => + threadId === this.threadId ? this.projection?.beginUserWait(Date.now()) : undefined; + + /** + * Seeds a thread this runtime just created (thread/start) to zero + * cumulative usage so its first round's tok/s is measurable. Never call + * for resumed or forked threads: their totals arrive through the + * app-server's attach-time usage replay and already include inherited + * history. + */ + seedFreshUsage(): void { + this.projection.seedFreshUsage(); + } + async prepare(): Promise { // Descendants share this bridge. The projection applies successful // root title calls so a child cannot rename the parent session. @@ -167,7 +184,7 @@ export class SharedCodexRoot { skillLookup: { workingDirectory: this.bootstrap.workingDirectory, flavor: 'codex' } }); await initializeSharedClient(this.client); this.asyncQuestions = new SharedCodexAsyncQuestions(this.session, (threadId, text, id) => this.submitQuestionAnswer(threadId, text, id)); - this.permissions = new SharedCodexPermissions(this.session, this.client, this.host.generation, reply => this.asyncQuestions.answer(reply)); + this.permissions = new SharedCodexPermissions(this.session, this.client, this.host.generation, reply => this.asyncQuestions.answer(reply), this.userWaitFor); this.client.setServerRequestHandler(request => { void this.receiveRequest(request); }); } private async submitQuestionAnswer(threadId: string, text: string, clientUserMessageId: string): Promise { @@ -446,7 +463,7 @@ export class SharedCodexRoot { try { await initializeSharedClient(this.client); if (this.stopping) return; - this.permissions = new SharedCodexPermissions(this.session, this.client, `${this.host.generation}:${randomUUID()}`, reply => this.asyncQuestions.answer(reply)); + this.permissions = new SharedCodexPermissions(this.session, this.client, `${this.host.generation}:${randomUUID()}`, reply => this.asyncQuestions.answer(reply), this.userWaitFor); this.client.setServerRequestHandler(request => { void this.receiveRequest(request); }); const settingsRevision = this.settingsRevision; const response = record(await this.client.request('thread/resume', { threadId: this.threadId, excludeTurns: true })); diff --git a/cli/src/codex/shared/runtime.integration.test.ts b/cli/src/codex/shared/runtime.integration.test.ts index c1978c3b..c4f61db6 100644 --- a/cli/src/codex/shared/runtime.integration.test.ts +++ b/cli/src/codex/shared/runtime.integration.test.ts @@ -285,6 +285,12 @@ describe.skipIf(process.env.HAPI_RUN_SHARED_CODEX_TESTS !== '1')('installed Code const nextSession = [...state.sessions.values()].find(session => session.metadata.codexSessionId === next)!; expect(web.metadata.codexSessionId).toBe(initial); expect(process.env.HAPI_SESSION_ID).toBe('parent-must-not-leak'); + // A thread created through the gateway (native /new) is fresh: the + // first turn must measure from the zero seed, not a null baseline. + await first.request('turn/start', { threadId: next, input: [{ type: 'text', text: 'HELLO NEW THREAD', text_elements: [] }] }); + await vi.waitFor(() => expect(nextSession.messages).toContainEqual(expect.objectContaining({ + type: 'turn_duration', generationMs: expect.any(Number), generationOutputTokens: 3 + })), { timeout: 15_000 }); await first.request('thread/archive', { threadId: next }); roots = [initial]; await vi.waitFor(() => expect(nextSession.dead).toBe(true)); expect(web.dead).toBe(false); await second.request('turn/start', { threadId: initial, model: 'second-mock', input: [{ type: 'text', text: 'HELLO FROM TERMINAL', text_elements: [] }], clientUserMessageId: 'native-1' }); @@ -307,4 +313,79 @@ describe.skipIf(process.env.HAPI_RUN_SHARED_CODEX_TESTS !== '1')('installed Code await rm(home, { recursive: true, force: true, maxRetries: 3 }); } }, 60_000); + it('seeds a gateway-created thread before session-ready releases queued input', async () => { + const home = await mkdtemp('/tmp/hapi-shared-gateway-seed-'); state.home = home; + const ch = join(home, 'codex'); const cwd = join(home, 'work'); await mkdir(ch); await mkdir(cwd); + const modelRequests: unknown[] = []; + const http = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on('data', chunk => chunks.push(Buffer.from(chunk))); + request.on('end', () => { + if (!request.url?.endsWith('/responses')) { response.writeHead(404).end(); return; } + modelRequests.push(JSON.parse(Buffer.concat(chunks).toString())); + const id = randomUUID(); + const events = [{ type: 'response.created', response: { id } }, + { type: 'response.output_item.done', item: { type: 'message', role: 'assistant', id: `msg_${id}`, content: [{ type: 'output_text', text: 'MOCK ANSWER' }] } }, + { type: 'response.completed', response: { id, usage: { input_tokens: 12, output_tokens: 3, total_tokens: 15 } } }]; + response.writeHead(200, { 'Content-Type': 'text/event-stream' }); + response.end(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join('')); + }); + }); + await new Promise(resolve => http.listen(0, '127.0.0.1', resolve)); + const port = (http.address() as { port: number }).port; + await writeFile(join(ch, 'config.toml'), `model = "mock-model"\nmodel_provider = "mock_provider"\napproval_policy = "never"\nsandbox_mode = "read-only"\ncheck_for_update_on_startup = false\n[model_providers.mock_provider]\nname = "Isolated mock"\nbase_url = "http://127.0.0.1:${port}/v1"\nwire_api = "responses"\nrequires_openai_auth = false\nsupports_websockets = false\nrequest_max_retries = 0\nstream_max_retries = 0\n[analytics]\nenabled = false\n[feedback]\nenabled = false\n[projects."${cwd}"]\ntrust_level = "trusted"\n`); + vi.stubEnv('CODEX_HOME', ch); vi.stubEnv('HOME', home); + const { runSharedRuntime } = await import('./runtime'); + let ready!: (value: import('./runtime').RuntimeReady) => void; + const readiness = new Promise(resolve => { ready = resolve; }); + const abort = new AbortController(); + const running = runSharedRuntime({ workingDirectory: cwd }, ready, abort.signal); + const clients: CodexAppServerClient[] = []; + // Hold the runner notification for the gateway-created session: the + // zero seed used to wait behind it while session-ready had already + // released input, and a later seed cannot repair that first turn. + let releaseRunner!: () => void; + const runnerGate = new Promise(resolve => { releaseRunner = resolve; }); + let released = false; + const release = () => { if (!released) { released = true; releaseRunner(); } }; + const originalReady = MockSession.prototype.emitSessionReady; + try { + const { runtime, sessionId } = await Promise.race([readiness, running.then(() => { throw new Error('Runtime stopped before ready'); })]); + const firstWeb = state.sessions.get(sessionId)!; + vi.mocked(notifyRunnerSessionStarted).mockImplementation(async (id: string) => { + if (id !== sessionId) await runnerGate; + return {}; + }); + // The hub releases a queued prompt the moment session-ready fires. + MockSession.prototype.emitSessionReady = function (this: MockSession) { + this.user?.({ content: { text: 'QUEUED AT READY' } }, 'queued-at-ready'); + originalReady.call(this); + }; + const first = new CodexAppServerClient({ endpoint: runtime.endpoint, token: runtime.token }); + clients.push(first); first.setServerRequestHandler(() => {}); await initializeSharedClient(first); + const started = first.request('thread/start', { cwd }); + const nextSession = await vi.waitFor(() => { + const session = [...state.sessions.values()].find(candidate => candidate !== firstWeb); + expect(session, 'gateway session created').toBeDefined(); + return session!; + }, { timeout: 15_000 }); + // The queued turn runs to completion while the runner notification + // is still gated: its first turn must already measure from the + // zero seed. + await vi.waitFor(() => expect(nextSession.messages).toContainEqual(expect.objectContaining({ + type: 'turn_duration', generationMs: expect.any(Number), generationOutputTokens: 3 + })), { timeout: 15_000 }); + expect(JSON.stringify(modelRequests)).toContain('QUEUED AT READY'); + release(); + await started; + } finally { + MockSession.prototype.emitSessionReady = originalReady; + release(); + vi.mocked(notifyRunnerSessionStarted).mockImplementation(async () => ({})); + abort.abort(); await running.catch(() => {}); + await Promise.all(clients.map(client => client.disconnect())); + await new Promise(resolve => http.close(() => resolve())); + await rm(home, { recursive: true, force: true, maxRetries: 3 }); + } + }, 60_000); }); diff --git a/cli/src/codex/shared/runtime.ts b/cli/src/codex/shared/runtime.ts index e436ad95..bde583a4 100644 --- a/cli/src/codex/shared/runtime.ts +++ b/cli/src/codex/shared/runtime.ts @@ -213,7 +213,7 @@ export async function runSharedRuntime(options: SharedLaunchOptions, onReady?: ( runtime.pendingCreations = runtime.pendingCreations?.filter(sid => sid !== root.session.sessionId); await persist(); }; const reserve = async (root: SharedCodexRoot, threadId: string) => withThreadOwnership(home, threadId, id, () => reserveRecord(root, threadId)); - const bind = async (root: SharedCodexRoot, response: Record, subscribe: boolean, initialOptions?: SharedLaunchOptions) => { + const bind = async (root: SharedCodexRoot, response: Record, subscribe: boolean, initialOptions?: SharedLaunchOptions, freshThread = false) => { assertRunning(); const threadId = string(record(response.thread).id); if (!threadId) throw new Error('Codex lifecycle response has no thread ID'); @@ -225,6 +225,13 @@ export async function runSharedRuntime(options: SharedLaunchOptions, onReady?: ( assertRunning(); roots.set(threadId, root); await root.bind(threadId, response, subscribe); + // A thread this runtime created (thread/start) starts from zero + // cumulative usage: seed before activate() opens the input gates, or + // a prompt released at session-ready starts the first turn with a + // null baseline that later seeding cannot repair. Forks are + // excluded: their totals arrive through the app-server's attach-time + // usage replay. + if (freshThread) root.seedFreshUsage(); assertRunning(); // Cold-resumed threads predate the control connection's automatic // new-thread subscription. Subscribe once without changing settings. @@ -245,7 +252,8 @@ export async function runSharedRuntime(options: SharedLaunchOptions, onReady?: ( runtime.pendingCreations = [...runtime.pendingCreations ?? [], root.session.sessionId]; await persist(); const response = record(await root.client.request(method, root.config({ ...params, ...(method === 'thread/fork' ? { deferGoalContinuation: true } : {}) }))); nativeSucceeded = true; - await bind(root, response, true, initialOptions); return root; + await bind(root, response, true, initialOptions, method === 'thread/start'); + return root; } catch (error) { // A timed-out native mutation may have succeeded. Never replay it or kill unrelated roots. if (!nativeSucceeded && !isIndeterminateError(error)) { @@ -305,7 +313,7 @@ export async function runSharedRuntime(options: SharedLaunchOptions, onReady?: ( runtime.pendingCreations = runtime.pendingCreations?.filter(sid => sid !== reservation.root.session.sessionId); await persist(); prepared.delete(reservation.root); await reservation.root.close(true); return; } - await bind(reservation.root, record(response.result), true); + await bind(reservation.root, record(response.result), true, undefined, request.method === 'thread/start'); } else if (request.method === 'thread/archive' && !response.error) { const root = roots.get(string(record(request.params).threadId) ?? ''); if (root) await end(root, false); } else if (request.method === 'thread/queue/delete' && !response.error && record(response.result).deleted === true) { diff --git a/cli/src/codex/utils/appServerEventConverter.test.ts b/cli/src/codex/utils/appServerEventConverter.test.ts index ee600d67..44307079 100644 --- a/cli/src/codex/utils/appServerEventConverter.test.ts +++ b/cli/src/codex/utils/appServerEventConverter.test.ts @@ -225,6 +225,60 @@ describe('AppServerEventConverter', () => { command: 'node server.js', cwd: '/repo', status: 'failed', exit_code: -1, duration_ms: 16_636_720 })]); }); + it('carries item timing on tool events for the generation ledger', () => { + const converter = new AppServerEventConverter(); + + const command = converter.handleNotification('item/started', { + item: { id: 'cmd-1', type: 'commandExecution', command: 'ls', startedAtMs: 1_000 } + }); + expect(command).toEqual([expect.objectContaining({ type: 'exec_command_begin', call_id: 'cmd-1', started_at_ms: 1_000 })]); + const commandEnd = converter.handleNotification('item/completed', { + item: { id: 'cmd-1', type: 'commandExecution', status: 'completed', durationMs: 500, completedAtMs: 1_500 } + }); + expect(commandEnd).toEqual([expect.objectContaining({ + type: 'exec_command_end', call_id: 'cmd-1', duration_ms: 500, completed_at_ms: 1_500 + })]); + + const mcp = converter.handleNotification('item/started', { + item: { id: 'mcp-1', type: 'mcpToolCall', server: 's', tool: 't', arguments: {}, startedAtMs: 2_000 } + }); + expect(mcp).toEqual([expect.objectContaining({ type: 'mcp_tool_call_begin', call_id: 'mcp-1', started_at_ms: 2_000 })]); + const mcpEnd = converter.handleNotification('item/completed', { + item: { id: 'mcp-1', type: 'mcpToolCall', server: 's', tool: 't', result: { Ok: 'done' }, durationMs: 250, completedAtMs: 2_250 } + }); + expect(mcpEnd).toEqual([expect.objectContaining({ + type: 'mcp_tool_call_end', call_id: 'mcp-1', duration_ms: 250, completed_at_ms: 2_250 + })]); + + const patch = converter.handleNotification('item/started', { + item: { id: 'patch-1', type: 'fileChange', changes: {}, startedAtMs: 3_000 } + }); + expect(patch).toEqual([expect.objectContaining({ type: 'patch_apply_begin', call_id: 'patch-1', started_at_ms: 3_000 })]); + const patchEnd = converter.handleNotification('item/completed', { + item: { id: 'patch-1', type: 'fileChange', success: true, completedAtMs: 3_400 } + }); + expect(patchEnd).toEqual([expect.objectContaining({ type: 'patch_apply_end', call_id: 'patch-1', completed_at_ms: 3_400 })]); + + const collab = converter.handleNotification('item/started', { + item: { id: 'agent-1', type: 'collabAgentToolCall', tool: 'spawn_agent', startedAtMs: 4_000 } + }); + expect(collab).toEqual([expect.objectContaining({ type: 'codex_tool_call_begin', call_id: 'agent-1', started_at_ms: 4_000 })]); + const collabEnd = converter.handleNotification('item/completed', { + item: { id: 'agent-1', type: 'collabAgentToolCall', tool: 'spawn_agent', status: 'completed', completedAtMs: 5_000 } + }); + expect(collabEnd).toEqual([expect.objectContaining({ type: 'codex_tool_call_end', call_id: 'agent-1', completed_at_ms: 5_000 })]); + }); + + it('omits item timing keys the agent did not send', () => { + const converter = new AppServerEventConverter(); + const started = converter.handleNotification('item/started', { + item: { id: 'cmd-1', type: 'commandExecution', command: 'ls' } + }); + expect(started).toEqual([{ + type: 'exec_command_begin', call_id: 'cmd-1', command: 'ls' + }]); + }); + it('maps MCP tool call items', () => { const converter = new AppServerEventConverter(); diff --git a/cli/src/codex/utils/appServerEventConverter.ts b/cli/src/codex/utils/appServerEventConverter.ts index 580068ed..a64f450a 100644 --- a/cli/src/codex/utils/appServerEventConverter.ts +++ b/cli/src/codex/utils/appServerEventConverter.ts @@ -1052,6 +1052,8 @@ export class AppServerEventConverter { } if (itemType === 'commandexecution') { + const startedAtMs = asNumber(item.startedAtMs ?? item.started_at_ms); + const completedAtMs = asNumber(item.completedAtMs ?? item.completed_at_ms); if (method === 'item/started') { const command = extractCommand(item.command ?? item.cmd ?? item.args); const cwd = asString(item.cwd ?? item.workingDirectory ?? item.working_directory); @@ -1068,6 +1070,7 @@ export class AppServerEventConverter { if (autoApproved !== null) meta.auto_approved = autoApproved; if (commandActions) meta.command_actions = commandActions; if (source) meta.command_source = source; + if (startedAtMs !== null) meta.started_at_ms = startedAtMs; this.commandMeta.set(itemId, meta); events.push(scoped({ @@ -1101,6 +1104,7 @@ export class AppServerEventConverter { ...(error ? { error } : {}), ...(exitCode !== null ? { exit_code: exitCode } : {}), ...(durationMs !== null ? { duration_ms: durationMs } : {}), + ...(completedAtMs !== null ? { completed_at_ms: completedAtMs } : {}), ...(status ? { status } : {}) })); @@ -1113,6 +1117,9 @@ export class AppServerEventConverter { } if (itemType === 'mcptoolcall') { + const startedAtMs = asNumber(item.startedAtMs ?? item.started_at_ms); + const completedAtMs = asNumber(item.completedAtMs ?? item.completed_at_ms); + const durationMs = asNumber(item.durationMs ?? item.duration_ms); const server = asString(item.server ?? item.serverName ?? item.server_name); const tool = asString(item.tool ?? item.toolName ?? item.tool_name ?? item.name); const input = item.arguments ?? item.input ?? {}; @@ -1123,6 +1130,7 @@ export class AppServerEventConverter { call_id: itemId, server, tool, + ...(startedAtMs !== null ? { started_at_ms: startedAtMs } : {}), invocation: { server, tool, @@ -1138,7 +1146,9 @@ export class AppServerEventConverter { call_id: itemId, server, tool, - result: error ? { Err: error } : item.result + result: error ? { Err: error } : item.result, + ...(durationMs !== null ? { duration_ms: durationMs } : {}), + ...(completedAtMs !== null ? { completed_at_ms: completedAtMs } : {}) })); } @@ -1174,6 +1184,8 @@ export class AppServerEventConverter { } if (itemType === 'collabagenttoolcall') { + const startedAtMs = asNumber(item.startedAtMs ?? item.started_at_ms); + const completedAtMs = asNumber(item.completedAtMs ?? item.completed_at_ms); if (this.rawAgentToolCallIds.has(itemId)) return events; const toolName = normalizeCollabAgentToolName(item.tool ?? item.name); if (!toolName) return events; @@ -1183,6 +1195,7 @@ export class AppServerEventConverter { type: 'codex_tool_call_begin', call_id: itemId, name: toolName, + ...(startedAtMs !== null ? { started_at_ms: startedAtMs } : {}), input: buildCollabAgentInput(item, toolName) })); } @@ -1193,6 +1206,7 @@ export class AppServerEventConverter { type: 'codex_tool_call_end', call_id: itemId, name: toolName, + ...(completedAtMs !== null ? { completed_at_ms: completedAtMs } : {}), output: buildCollabAgentOutput(item, toolName), is_error: status === 'failed' || status === 'error' })); @@ -1202,12 +1216,15 @@ export class AppServerEventConverter { } if (itemType === 'filechange') { + const startedAtMs = asNumber(item.startedAtMs ?? item.started_at_ms); + const completedAtMs = asNumber(item.completedAtMs ?? item.completed_at_ms); if (method === 'item/started') { const changes = extractChanges(item.changes ?? item.change ?? item.diff); const autoApproved = asBoolean(item.autoApproved ?? item.auto_approved); const meta: Record = {}; if (changes) meta.changes = changes; if (autoApproved !== null) meta.auto_approved = autoApproved; + if (startedAtMs !== null) meta.started_at_ms = startedAtMs; this.fileChangeMeta.set(itemId, meta); events.push(scoped({ @@ -1229,6 +1246,7 @@ export class AppServerEventConverter { ...meta, ...(stdout ? { stdout } : {}), ...(stderr ? { stderr } : {}), + ...(completedAtMs !== null ? { completed_at_ms: completedAtMs } : {}), success: success ?? false })); diff --git a/cli/src/codex/utils/codexGenerationLedger.test.ts b/cli/src/codex/utils/codexGenerationLedger.test.ts new file mode 100644 index 00000000..43177642 --- /dev/null +++ b/cli/src/codex/utils/codexGenerationLedger.test.ts @@ -0,0 +1,164 @@ +import { describe, expect, it } from 'vitest'; +import { CodexGenerationLedger } from './codexGenerationLedger'; + +describe('CodexGenerationLedger', () => { + it('subtracts a command window measured by Codex itself from the round', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(1_000); // pre-round cumulative total + ledger.startTurn('t1', 0); + ledger.endTool('exec-1', 4_000, 3_000); // Codex's own duration: window [1000, 4000] + ledger.noteTokenUsage(1_050); + expect(ledger.settle('t1', 5_000, true)).toEqual({ generationMs: 2_000, generationOutputTokens: 50 }); + }); + + it('falls back to receive moments when the item carries no native timing', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(100); + ledger.startTurn('t1', 0); + ledger.beginTool('mcp-1', 1_000); + ledger.endTool('mcp-1', 2_500); + ledger.noteTokenUsage(160); + expect(ledger.settle('t1', 4_000, true)).toEqual({ generationMs: 2_500, generationOutputTokens: 60 }); + }); + + it('counts concurrent tool windows once', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(0); + ledger.startTurn('t1', 0); + ledger.beginTool('exec-1', 1_000); + ledger.beginTool('exec-2', 2_000); + ledger.endTool('exec-1', 3_000); + ledger.endTool('exec-2', 4_000); + ledger.noteTokenUsage(10); + expect(ledger.settle('t1', 5_000, true)).toEqual({ generationMs: 2_000, generationOutputTokens: 10 }); + }); + + it('excludes a wait for the user and merges it with an overlapping tool window', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(0); + ledger.startTurn('t1', 0); + // The command item opens before its approval; the wait sits inside. + ledger.beginTool('exec-1', 1_000); + const answered = ledger.beginUserWait(1_000); + answered(1_500); + ledger.endTool('exec-1', 4_000, 3_000); + ledger.noteTokenUsage(10); + // Tool window [1000, 4000] already covers the wait: 5000 - 3000. + expect(ledger.settle('t1', 5_000, true)).toEqual({ generationMs: 2_000, generationOutputTokens: 10 }); + // A standalone wait is subtracted on its own. + const second = new CodexGenerationLedger(); + second.noteTokenUsage(0); + second.startTurn('t1', 0); + const granted = second.beginUserWait(1_000); + granted(2_500); + second.noteTokenUsage(10); + expect(second.settle('t1', 5_000, true)).toEqual({ generationMs: 3_500, generationOutputTokens: 10 }); + }); + + it('derives the round output tokens from the cumulative usage delta', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(10_000); // previous turns + ledger.startTurn('t1', 0); + ledger.noteTokenUsage(10_100); // mid-turn call + ledger.noteTokenUsage(10_150); // final call + expect(ledger.settle('t1', 1_000, true)).toEqual({ generationMs: 1_000, generationOutputTokens: 150 }); + }); + + it('measures a thread the CLI seeded to zero before its first turn', () => { + // Captured from the live 2026-11-11 16:40 E2E rollout: a brand-new + // thread reports no usage before the turn starts, then cumulative + // output totals of 50 -> 63 across it. The CLI seeds a thread it + // created in this process (thread/start) to zero, so the pair must + // not depend on a pre-round usage snapshot. Resumed and forked + // threads are covered by the app-server's attach-time usage replay + // instead and never carry this seed. + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(0); + ledger.startTurn('t1', 0); + ledger.noteTokenUsage(50); + ledger.noteTokenUsage(63); + expect(ledger.settle('t1', 4_100, true)).toEqual({ generationMs: 4_100, generationOutputTokens: 63 }); + }); + + it('emits nothing without a pre-turn usage baseline', () => { + // A thread the CLI did not create (resumed or forked) learns its + // cumulative totals from the app-server's attach-time usage replay; + // until a snapshot lands before a turn, no pair is measurable, so a + // mid-turn first snapshot must not be mistaken for a zero baseline. + const ledger = new CodexGenerationLedger(); + ledger.startTurn('t1', 0); + ledger.noteTokenUsage(500); // first snapshot arrives mid-round + expect(ledger.settle('t1', 1_000, true)).toBeNull(); + }); + + it('emits nothing when the turn produced no measurable output tokens', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(500); + ledger.startTurn('t1', 0); + ledger.noteTokenUsage(500); // unchanged cumulative total + expect(ledger.settle('t1', 1_000, true)).toBeNull(); + const shrinking = new CodexGenerationLedger(); + shrinking.noteTokenUsage(500); + shrinking.startTurn('t1', 0); + shrinking.noteTokenUsage(400); + expect(shrinking.settle('t1', 1_000, true)).toBeNull(); + }); + + it('emits nothing when no usage was reported at all', () => { + const ledger = new CodexGenerationLedger(); + ledger.startTurn('t1', 0); + expect(ledger.settle('t1', 1_000, true)).toBeNull(); + }); + + it('keeps no state for a failed turn and measures the next one cleanly', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(100); + ledger.startTurn('t1', 0); + ledger.beginTool('exec-1', 200); + expect(ledger.settle('t1', 400, false)).toBeNull(); + ledger.noteTokenUsage(160); + ledger.startTurn('t2', 500); + ledger.noteTokenUsage(260); + expect(ledger.settle('t2', 1_500, true)).toEqual({ generationMs: 1_000, generationOutputTokens: 100 }); + }); + + it('records a tool window for a completion that never announced a start', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(0); + ledger.startTurn('t1', 0); + ledger.endTool('late-exec', 4_000, 3_000); + ledger.noteTokenUsage(10); + expect(ledger.settle('t1', 5_000, true)).toEqual({ generationMs: 2_000, generationOutputTokens: 10 }); + }); + + it('ignores a completion whose measured duration reaches before the round', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(0); + ledger.startTurn('t1', 3_000); + ledger.endTool('exec-1', 4_000, 10_000); // window clipped to the round + ledger.noteTokenUsage(10); + expect(ledger.settle('t1', 5_000, true)).toEqual({ generationMs: 1_000, generationOutputTokens: 10 }); + }); + + it('ignores a completion for another turn without disturbing the live round', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(0); + ledger.startTurn('live', 0); + ledger.beginTool('exec-1', 1_000); + ledger.endTool('exec-1', 4_000); + expect(ledger.settle('stale', 2_000, true)).toBeNull(); + ledger.noteTokenUsage(10); + expect(ledger.settle('live', 5_000, true)).toEqual({ generationMs: 2_000, generationOutputTokens: 10 }); + }); + + it('ignores a repeated start of the same turn', () => { + const ledger = new CodexGenerationLedger(); + ledger.noteTokenUsage(0); + ledger.startTurn('t1', 0); + ledger.beginTool('exec-1', 1_000); + ledger.startTurn('t1', 3_000); // replayed start: state and baseline kept + ledger.endTool('exec-1', 4_000); + ledger.noteTokenUsage(10); + expect(ledger.settle('t1', 5_000, true)).toEqual({ generationMs: 2_000, generationOutputTokens: 10 }); + }); +}); \ No newline at end of file diff --git a/cli/src/codex/utils/codexGenerationLedger.ts b/cli/src/codex/utils/codexGenerationLedger.ts new file mode 100644 index 00000000..149b35f5 --- /dev/null +++ b/cli/src/codex/utils/codexGenerationLedger.ts @@ -0,0 +1,121 @@ +import { generationTimeMs, type GenerationIdleWindow } from '@/agent/generationClock'; + +/** + * One Codex turn's tok/s bookkeeping, agy-style: the round minus the spans + * spent running tools or waiting for the user, over the round's output-token + * delta. Tool windows prefer Codex's own measurements (an item's + * startedAtMs/completedAtMs or a command's durationMs); HAPI receive moments + * fill in when an item carries no native timing. The token numerator is the + * thread-cumulative `total.output_tokens` delta across the round, so a turn + * is only measurable when a pre-round usage snapshot exists — either the + * app-server's attach-time usage replay for resumed and forked threads, or + * the CLI's zero seed for a thread it created in this process. Turn + * identity mirrors CodexRoundDuration: only the started turn settles, and a + * stale completion never disturbs the live round's state. + */ +export class CodexGenerationLedger { + private roundTurnId: string | null = null; + private roundStart: number | null = null; + private readonly toolWindows = new Map(); + private readonly userWaitWindows: GenerationIdleWindow[] = []; + private outputTotal: number | null = null; + private outputBaseline: number | null = null; + + /** + * Opens the round; the token baseline is whatever was reported before it. + * The CLI seeds a thread it created in this process (thread/start) to + * zero via noteTokenUsage(0), so a fresh thread's first turn measures + * from a real zero baseline. Resumed and forked threads instead receive + * the app-server's attach-time usage replay (codex + * request_processors/token_usage_replay.rs): their snapshot lands before + * the next turn/started, and until then no round is measurable — a + * mid-turn first snapshot on those threads already includes inherited + * history and must not stand in for a baseline. + */ + startTurn(turnId: string | null | undefined, startedAt: number): void { + if (!turnId || this.roundTurnId === turnId) return; + this.roundTurnId = turnId; + this.roundStart = startedAt; + this.outputBaseline = this.outputTotal; + this.toolWindows.clear(); + this.userWaitWindows.length = 0; + } + + beginTool(callId: string, at: number): void { + let window = this.toolWindows.get(callId); + if (!window) { + window = { start: at, end: null }; + this.toolWindows.set(callId, window); + } + } + + /** + * Closes a tool window. A Codex-measured duration replaces the begun + * window outright: it is immune to delivery skew. Completions without a + * start (reconnect, late shutdown) still yield their own window. + */ + endTool(callId: string, at: number, durationMs?: number): void { + const measured = typeof durationMs === 'number' && Number.isSafeInteger(durationMs) && durationMs > 0; + if (measured) { + this.toolWindows.set(callId, { start: at - durationMs, end: at }); + return; + } + const window = this.toolWindows.get(callId) ?? { start: at, end: null }; + window.end ??= at; + this.toolWindows.set(callId, window); + } + + /** + * Opens a wait-for-the-user span at the approval request; the returned + * callback closes it once the answer reached Codex. + */ + beginUserWait(startedAt: number): (endedAt: number) => void { + const window: GenerationIdleWindow = { start: startedAt, end: null }; + this.userWaitWindows.push(window); + return (endedAt: number) => { window.end ??= endedAt; }; + } + + /** Tracks the thread-cumulative output total, in and between turns. */ + noteTokenUsage(totalOutputTokens: number): void { + if (typeof totalOutputTokens === 'number' && Number.isSafeInteger(totalOutputTokens) && totalOutputTokens >= 0) { + this.outputTotal = totalOutputTokens; + } + } + + /** + * Drops the open round on app-server reconnect: the resumed turn + * re-announces itself and must re-measure from its own start, with the + * pre-disconnect tool windows and token baseline discarded. The + * cumulative output total survives — it is thread state, not turn state. + */ + reset(): void { + this.roundTurnId = null; + this.roundStart = null; + this.outputBaseline = null; + this.toolWindows.clear(); + this.userWaitWindows.length = 0; + } + + /** + * The round's generation pair, or null when nothing measurable happened: + * no matching round, no pre-turn usage baseline, no token delta, or no + * time left once tools and waits are removed. Failed turns reset without + * a pair. A completion for another turn is ignored entirely. + */ + settle(turnId: string | null | undefined, completedAt: number, completed: boolean): { generationMs: number; generationOutputTokens: number } | null { + if (!turnId || this.roundTurnId !== turnId) return null; + const roundStart = this.roundStart; + const baseline = this.outputBaseline; + const windows = [...this.toolWindows.values(), ...this.userWaitWindows]; + this.roundTurnId = null; + this.roundStart = null; + this.outputBaseline = null; + this.toolWindows.clear(); + this.userWaitWindows.length = 0; + if (!completed || roundStart === null || baseline === null || this.outputTotal === null) return null; + const generationOutputTokens = this.outputTotal - baseline; + const generationMs = generationTimeMs(roundStart, completedAt, windows); + if (!(generationOutputTokens > 0) || generationMs === null || generationMs <= 0) return null; + return { generationMs, generationOutputTokens }; + } +} \ No newline at end of file diff --git a/web/src/chat/normalize.test.ts b/web/src/chat/normalize.test.ts index 6e4b9efe..c5cf10c4 100644 --- a/web/src/chat/normalize.test.ts +++ b/web/src/chat/normalize.test.ts @@ -122,6 +122,27 @@ describe('normalizeDecryptedMessage', () => { }) }) + it('keeps the Codex generation pair on the turn-duration event only when both are valid', () => { + const normalize = (data: Record) => normalizeDecryptedMessage(makeMessage({ + role: 'agent', + content: { type: 'codex', data: { type: 'turn_duration', flavor: 'codex', turn_id: 'turn', durationMs: 4_000, ...data } } + })) + expect(normalize({ generationMs: 2_200, generationOutputTokens: 50 })).toMatchObject({ + content: { type: 'turn-duration', provider: 'codex', durationMs: 4_000, generationMs: 2_200, generationOutputTokens: 50 } + }) + for (const generation of [ + {}, { generationMs: 2_200 }, { generationOutputTokens: 50 }, + ...[0, -1, NaN, Infinity, '5', 0.5, Number.MAX_SAFE_INTEGER + 1].flatMap(value => [ + { generationMs: value, generationOutputTokens: 50 }, + { generationMs: 2_200, generationOutputTokens: value } + ]) + ]) { + const normalized = normalize(generation) + expect(normalized?.content).not.toHaveProperty('generationMs') + expect(normalized?.content).not.toHaveProperty('generationOutputTokens') + } + }) + it('drops fractional and unsafe token counters and turn counts while retaining valid model fields', () => { const message = makeMessage({ role: 'agent', diff --git a/web/src/chat/normalizeAgent.ts b/web/src/chat/normalizeAgent.ts index 4ff95441..09b9fe9f 100644 --- a/web/src/chat/normalizeAgent.ts +++ b/web/src/chat/normalizeAgent.ts @@ -1263,12 +1263,17 @@ export function normalizeAgentRecord( const scopeRole = asString(data.scope_role ?? data.scopeRole ?? scope?.role) if (data.flavor !== 'codex' || data.hapiUsageScope === 'imported-history' || scopeRole === 'child' || !turnId || durationMs === undefined) return null + const generationMs = nonNegativeSafeInteger(data.generationMs) + const generationOutputTokens = nonNegativeSafeInteger(data.generationOutputTokens) + const generation = generationMs !== undefined && generationMs > 0 + && generationOutputTokens !== undefined && generationOutputTokens > 0 + ? { generationMs, generationOutputTokens } : {} return { id: messageId, localId, createdAt, role: 'event', - content: { type: 'turn-duration', provider: 'codex', durationMs, turnId }, + content: { type: 'turn-duration', provider: 'codex', durationMs, turnId, ...generation }, isSidechain: false, meta } diff --git a/web/src/chat/reducerTimeline.test.ts b/web/src/chat/reducerTimeline.test.ts index c56cc943..7e9d691c 100644 --- a/web/src/chat/reducerTimeline.test.ts +++ b/web/src/chat/reducerTimeline.test.ts @@ -323,6 +323,36 @@ describe('reduceTimeline', () => { expect((blocks[0] as { roundSummary?: { durationMs?: number } }).roundSummary?.durationMs).toBeUndefined() }) + it('keeps the generation pair when token usage arrives after the turn duration', () => { + const messages = [ + { turn_id: 'turn', type: 'message', message: 'answer' }, + { turn_id: 'turn', type: 'turn_duration', flavor: 'codex', durationMs: 4_000, generationMs: 2_200, generationOutputTokens: 50 }, + { turn_id: 'turn', type: 'token_count', flavor: 'codex', model: 'gpt-5.4', + info: { last_token_usage: { input_tokens: 100, output_tokens: 10 } } } + ].map((data, index) => normalizeAgentRecord(`late-usage-${index}`, null, index, { type: 'codex', data })!) + const { blocks } = reduceTimeline(messages, makeContext()) + expect(blocks[0]).toMatchObject({ roundSummary: { provider: 'codex', turnId: 'turn', numTurns: 1, + durationMs: 4_000, generationMs: 2_200, generationOutputTokens: 50, + usage: { input_tokens: 100, output_tokens: 10 }, + modelUsage: { 'gpt-5.4': { inputTokens: 100, outputTokens: 10 } } } }) + expect(buildMessageMetadataLabels({ roundSummary: (blocks[0] as { roundSummary?: Record }).roundSummary as never })) + .toContain('Round: 4s · 1 turn · 22.7 tok/s') + }) + + it('carries the Codex generation pair into the round summary for the tok/s footer', () => { + const messages = [ + { turn_id: 'turn', type: 'message', message: 'answer' }, + { turn_id: 'turn', type: 'token_count', flavor: 'codex', model: 'gpt-5.4', + info: { last_token_usage: { input_tokens: 100, output_tokens: 10 } } }, + { turn_id: 'turn', type: 'turn_duration', flavor: 'codex', durationMs: 4_000, generationMs: 2_200, generationOutputTokens: 50 } + ].map((data, index) => normalizeAgentRecord(`generation-${index}`, null, index, { type: 'codex', data })!) + const { blocks } = reduceTimeline(messages, makeContext()) + expect(blocks[0]).toMatchObject({ roundSummary: { provider: 'codex', turnId: 'turn', + durationMs: 4_000, generationMs: 2_200, generationOutputTokens: 50 } }) + expect(buildMessageMetadataLabels({ roundSummary: (blocks[0] as { roundSummary?: Record }).roundSummary as never })) + .toContain('Round: 4s · 1 turn · 22.7 tok/s') + }) + it('rejects unmatched Codex metadata when the response has a different native turn ID', () => { const messages = [ { type: 'message', message: 'new answer', turn_id: 'new' }, diff --git a/web/src/chat/reducerTimeline.ts b/web/src/chat/reducerTimeline.ts index 5484a838..d499452e 100644 --- a/web/src/chat/reducerTimeline.ts +++ b/web/src/chat/reducerTimeline.ts @@ -591,8 +591,16 @@ export function reduceTimeline( } if (msg.content.type === 'turn-duration') { if (msg.content.provider === 'codex') { + // The pair rides conditionally: a later usage summary must + // not wipe a duration summary's generation fields. + const durationContent = msg.content as { generationMs?: unknown; generationOutputTokens?: unknown } + const generationMs = typeof durationContent.generationMs === 'number' ? durationContent.generationMs : undefined + const generationOutputTokens = typeof durationContent.generationOutputTokens === 'number' ? durationContent.generationOutputTokens : undefined + const generation = generationMs !== undefined && generationOutputTokens !== undefined + ? { generationMs, generationOutputTokens } : {} attachCodexRoundSummaryToLatestGroup(blocks, { - provider: 'codex', turnId: msg.content.turnId as string, modelUsage: {}, numTurns: 1, durationMs: msg.content.durationMs as number + provider: 'codex', turnId: msg.content.turnId as string, modelUsage: {}, numTurns: 1, durationMs: msg.content.durationMs as number, + ...generation }) continue } diff --git a/web/src/chat/types.ts b/web/src/chat/types.ts index 053c92ee..9788df42 100644 --- a/web/src/chat/types.ts +++ b/web/src/chat/types.ts @@ -47,7 +47,7 @@ export type AgentEvent = | { type: 'limit-warning'; /** 0–1 ratio (e.g. 0.9 = 90%), integer-precision via CLI pipe format */ utilization: number; endsAt: number; limitType: string } | { type: 'ready' } | { type: 'api-error'; retryAttempt: number; maxRetries: number; error: unknown } - | { type: 'turn-duration'; durationMs: number; targetMessageId?: string; provider?: 'codex'; turnId?: string } + | { type: 'turn-duration'; durationMs: number; targetMessageId?: string; provider?: 'codex'; turnId?: string; generationMs?: number; generationOutputTokens?: number } | { type: 'turn-summary'; summary: RoundSummary } | { type: 'token-count'; info: unknown; provider?: 'codex'; turnId?: string; model?: string | null } | { type: 'microcompact'; trigger: string; preTokens: number; tokensSaved: number }