diff --git a/src/main/codex/codex-structured-dispatch-echo.test.ts b/src/main/codex/codex-structured-dispatch-echo.test.ts new file mode 100644 index 000000000000..6f5de943273d --- /dev/null +++ b/src/main/codex/codex-structured-dispatch-echo.test.ts @@ -0,0 +1,232 @@ +import { describe, expect, it, vi } from 'vitest' +import type { + AgentJournalItemIdentity, + AgentJournalMessageItem +} from '../../shared/agent-session-journal-types' +import { + armCodexEchoTimeout, + createCodexDispatchEchoes, + registerCodexEchoWaiter, + resolveCodexUserMessageEcho, + retireCodexEchoWaiter, + type CodexUserMessageEcho +} from './codex-structured-dispatch-echo' +import { dispatchCodexTurn, type CodexTurnHost } from './codex-structured-turn-start' + +const THREAD_ID = 'thread-1' + +function codexIdentity(ordinal: number, turnId = 'turn-1'): AgentJournalItemIdentity { + return { provider: 'codex', threadId: THREAD_ID, turnId, ordinal } +} + +function echoFor( + clientId: string | null, + identity: AgentJournalItemIdentity = codexIdentity(0), + threadId = THREAD_ID +): CodexUserMessageEcho { + return { threadId, clientId, identity } +} + +describe('codex dispatch echo registry', () => { + it('settles the exact clientId match and leaves the other waiter pending', async () => { + const echoes = createCodexDispatchEchoes() + const a = registerCodexEchoWaiter(echoes, 'msg-A') + const b = registerCodexEchoWaiter(echoes, 'msg-B') + + resolveCodexUserMessageEcho(echoes, THREAD_ID, echoFor('msg-B', codexIdentity(2))) + + await expect(b.promise).resolves.toEqual(codexIdentity(2)) + expect(echoes.waiters).toEqual([a.waiter]) + expect(echoes.sawClientIdEcho).toBe(true) + }) + + it('never attributes repeated ID-less lifecycle frames to a later send', async () => { + const echoes = createCodexDispatchEchoes() + const a = registerCodexEchoWaiter(echoes, 'msg-A') + resolveCodexUserMessageEcho(echoes, THREAD_ID, echoFor('msg-A')) + await expect(a.promise).resolves.toEqual(codexIdentity(0)) + + const b = registerCodexEchoWaiter(echoes, 'msg-B') + resolveCodexUserMessageEcho(echoes, THREAD_ID, echoFor(null)) + expect(echoes.waiters).toEqual([b.waiter]) + resolveCodexUserMessageEcho(echoes, THREAD_ID, echoFor('msg-B', codexIdentity(2))) + await expect(b.promise).resolves.toEqual(codexIdentity(2)) + }) + + it('does not settle a sole timed-out send using an ID-less late echo', () => { + const echoes = createCodexDispatchEchoes() + const a = registerCodexEchoWaiter(echoes, 'msg-A') + retireCodexEchoWaiter(echoes, a.waiter) + const settledLate = vi.fn() + resolveCodexUserMessageEcho(echoes, THREAD_ID, echoFor(null), settledLate) + expect(settledLate).not.toHaveBeenCalled() + expect(echoes.retired).toEqual([a.waiter]) + }) + + it('retires a waiter on timeout and reports its late echo through the callback', async () => { + vi.useFakeTimers() + try { + const echoes = createCodexDispatchEchoes() + const { waiter, promise } = registerCodexEchoWaiter(echoes, 'msg-A') + armCodexEchoTimeout(echoes, waiter, 1_000) + await vi.advanceTimersByTimeAsync(1_000) + await expect(promise).resolves.toBeNull() + retireCodexEchoWaiter(echoes, waiter) + + const settledLate = vi.fn() + resolveCodexUserMessageEcho( + echoes, + THREAD_ID, + echoFor('msg-A', codexIdentity(2)), + settledLate + ) + expect(settledLate).toHaveBeenCalledWith({ + clientMessageId: 'msg-A', + providerIdentity: codexIdentity(2) + }) + expect(echoes.retired).toEqual([]) + } finally { + vi.useRealTimers() + } + }) + + it('ignores an echo from another thread and an unstable identity', () => { + const echoes = createCodexDispatchEchoes() + registerCodexEchoWaiter(echoes, 'msg-A') + + resolveCodexUserMessageEcho( + echoes, + THREAD_ID, + echoFor('msg-A', codexIdentity(0), 'thread-child') + ) + resolveCodexUserMessageEcho(echoes, THREAD_ID, { + threadId: THREAD_ID, + clientId: 'msg-A', + identity: { provider: 'orca', clientMessageId: 'codex-item:thread-1:item-9' } + }) + + expect(echoes.waiters).toHaveLength(1) + }) + + it('bounds the retired list', () => { + const echoes = createCodexDispatchEchoes() + for (let index = 0; index < 70; index += 1) { + retireCodexEchoWaiter(echoes, registerCodexEchoWaiter(echoes, `msg-${index}`).waiter) + } + expect(echoes.retired).toHaveLength(64) + expect(echoes.retired[0]?.clientMessageId).toBe('msg-6') + }) +}) + +const BODY: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'ship it' }] +} + +function hostFor(request: CodexTurnHost['connection']['request']): CodexTurnHost { + return { + threadId: THREAD_ID, + options: new Map(), + turnIdWaiters: [], + activeTurnIds: new Set(), + dispatchEchoes: createCodexDispatchEchoes(), + connection: { request } + } +} + +describe('dispatchCodexTurn echo correlation', () => { + it('accepts an echo that raced the turn/start response', async () => { + const host = hostFor(async () => { + resolveCodexUserMessageEcho(host.dispatchEchoes, THREAD_ID, echoFor('msg-A')) + return { turn: { id: 'turn-1' } } + }) + await expect( + dispatchCodexTurn(host, { clientMessageId: 'msg-A', body: BODY }, 50) + ).resolves.toEqual({ state: 'accepted', providerIdentity: codexIdentity(0) }) + }) + + it('falls back to the positional identity for a fresh turn no build echoed', async () => { + const host = hostFor(async () => { + host.turnIdWaiters.shift()?.('turn-1') + return { turn: { id: 'turn-1' } } + }) + await expect( + dispatchCodexTurn(host, { clientMessageId: 'msg-A', body: BODY }, 5_000, 25) + ).resolves.toEqual({ state: 'accepted', providerIdentity: codexIdentity(0) }) + }) + + it('uses a fresh-turn notification arriving during the echo grace and cleans up timers', async () => { + vi.useFakeTimers() + try { + const host = hostFor(async () => ({ turn: { id: 'turn-1' } })) + const dispatch = dispatchCodexTurn(host, { clientMessageId: 'msg-A', body: BODY }, 50, 25) + await vi.advanceTimersByTimeAsync(10) + host.turnIdWaiters.shift()?.('turn-1') + await vi.advanceTimersByTimeAsync(15) + await expect(dispatch).resolves.toEqual({ + state: 'accepted', + providerIdentity: codexIdentity(0) + }) + expect(host.turnIdWaiters).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + } finally { + vi.useRealTimers() + } + }) + + it('does not infer ordinal zero for a resumed turn absent from active tracking', async () => { + const host = hostFor(async () => ({ turn: { id: 'turn-1' } })) + await expect( + dispatchCodexTurn(host, { clientMessageId: 'msg-B', body: BODY }, 25) + ).resolves.toMatchObject({ state: 'unknown' }) + }) + + it('does not resurrect completed turns when their responses arrive late', async () => { + const host = hostFor(async () => { + host.activeTurnIds.add('turn-1') + host.turnIdWaiters.shift()?.('turn-1') + host.activeTurnIds.delete('turn-1') + return { turn: { id: 'turn-1' } } + }) + await dispatchCodexTurn(host, { clientMessageId: 'msg-A', body: BODY }, 25) + expect(host.activeTurnIds.size).toBe(0) + }) + + it('never falls back for a coalesced send: unknown, then the late echo settles it', async () => { + const host = hostFor(async () => ({ turn: { id: 'turn-1' } })) + // The first send proved this build echoes clientIds. + resolveCodexUserMessageEcho(host.dispatchEchoes, THREAD_ID, echoFor('warm-up')) + host.activeTurnIds.add('turn-1') + + await expect( + dispatchCodexTurn(host, { clientMessageId: 'msg-B', body: BODY }, 25) + ).resolves.toEqual({ + state: 'unknown', + reason: 'codex accepted a message but did not echo it in time' + }) + + const settledLate = vi.fn() + resolveCodexUserMessageEcho( + host.dispatchEchoes, + THREAD_ID, + echoFor('msg-B', codexIdentity(2)), + settledLate + ) + expect(settledLate).toHaveBeenCalledWith({ + clientMessageId: 'msg-B', + providerIdentity: codexIdentity(2) + }) + }) + + it('suppresses the fallback when another dispatch is still unsettled', async () => { + const host = hostFor(async () => ({ turn: { id: 'turn-1' } })) + registerCodexEchoWaiter(host.dispatchEchoes, 'msg-other') + await expect( + dispatchCodexTurn(host, { clientMessageId: 'msg-A', body: BODY }, 5_000, 25) + ).resolves.toEqual({ + state: 'unknown', + reason: 'codex accepted a message but did not echo it in time' + }) + }) +}) diff --git a/src/main/codex/codex-structured-dispatch-echo.ts b/src/main/codex/codex-structured-dispatch-echo.ts new file mode 100644 index 000000000000..1506b59f85f3 --- /dev/null +++ b/src/main/codex/codex-structured-dispatch-echo.ts @@ -0,0 +1,152 @@ +import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types' + +// Correlates a Codex `turn/start` dispatch with the `userMessage` item Codex +// echoes back for it: Orca sends `clientUserMessageId`, the echo carries it as +// `clientId`, and the echo's journal identity names the submission — including +// the true ordinal of a send Codex coalesced into an already-running turn. +// Mirrors the Claude adapter's dispatch waiters (claude-structured-dispatch.ts). + +const MAX_RETIRED_ECHO_WAITERS = 64 + +/** A live `userMessage` item as the journal translator identified it. */ +export type CodexUserMessageEcho = { + threadId: string + /** Codex's echo of `clientUserMessageId`; null on builds that predate it. */ + clientId: string | null + identity: AgentJournalItemIdentity +} + +export type CodexEchoWaiter = { + clientMessageId: string + resolve: (identity: AgentJournalItemIdentity | null) => void + timer?: ReturnType + settledIdentity?: AgentJournalItemIdentity + retired?: boolean +} + +export type CodexDispatchEchoes = { + waiters: CodexEchoWaiter[] + retired: CodexEchoWaiter[] + /** Once one exact `clientId` echo is seen this build provably correlates, so + * a missing echo means undelivered — the positional fallback stays off. */ + sawClientIdEcho: boolean +} + +/** A dispatch whose echo window expired, proven delivered by this late echo. */ +export type CodexLateEchoSettlement = (input: { + clientMessageId: string + providerIdentity: AgentJournalItemIdentity +}) => void + +export function createCodexDispatchEchoes(): CodexDispatchEchoes { + return { waiters: [], retired: [], sawClientIdEcho: false } +} + +/** Register BEFORE `turn/start` goes out: the echo can race the response. */ +export function registerCodexEchoWaiter( + echoes: CodexDispatchEchoes, + clientMessageId: string +): { waiter: CodexEchoWaiter; promise: Promise } { + let waiter!: CodexEchoWaiter + const promise = new Promise((resolve) => { + waiter = { clientMessageId, resolve } + echoes.waiters.push(waiter) + }) + return { waiter, promise } +} + +/** Armed only after the `turn/start` response classified the send, so fresh + * and coalesced turns get different windows. No-op once settled or armed. */ +export function armCodexEchoTimeout( + echoes: CodexDispatchEchoes, + waiter: CodexEchoWaiter, + timeoutMs: number +): void { + if (!echoes.waiters.includes(waiter) || waiter.timer) { + return + } + waiter.timer = setTimeout(() => { + removeWaiter(echoes.waiters, waiter) + waiter.resolve(null) + }, timeoutMs) + waiter.timer.unref?.() +} + +/** Drops a waiter whose dispatch failed outright; no echo is owed. */ +export function discardCodexEchoWaiter(echoes: CodexDispatchEchoes, waiter: CodexEchoWaiter): void { + clearTimeout(waiter.timer) + removeWaiter(echoes.waiters, waiter) + removeWaiter(echoes.retired, waiter) + waiter.resolve(null) +} + +/** Parks an expired waiter so a late echo can still settle its submission. */ +export function retireCodexEchoWaiter(echoes: CodexDispatchEchoes, waiter: CodexEchoWaiter): void { + clearTimeout(waiter.timer) + removeWaiter(echoes.waiters, waiter) + if (!waiter.retired) { + waiter.retired = true + echoes.retired.push(waiter) + if (echoes.retired.length > MAX_RETIRED_ECHO_WAITERS) { + echoes.retired.splice(0, echoes.retired.length - MAX_RETIRED_ECHO_WAITERS) + } + } +} + +export function resolveCodexUserMessageEcho( + echoes: CodexDispatchEchoes, + sessionThreadId: string | null, + echo: CodexUserMessageEcho, + onSettledLate?: CodexLateEchoSettlement +): void { + // A subagent thread's user message must never settle the primary dispatch. + if (sessionThreadId === null || echo.threadId !== sessionThreadId) { + return + } + // The `orca:` fallback namespace is unstable across resume; wait for a frame + // that names the turn rather than settling the journal on a throwaway key. + if (echo.identity.provider !== 'codex') { + return + } + if (echo.clientId !== null) { + echoes.sawClientIdEcho = true + const exact = echoes.waiters.find((candidate) => candidate.clientMessageId === echo.clientId) + if (exact) { + settleWaiter(echoes, exact, echo.identity) + return + } + const retired = echoes.retired.find((candidate) => candidate.clientMessageId === echo.clientId) + if (retired) { + removeWaiter(echoes.retired, retired) + onSettledLate?.({ clientMessageId: retired.clientMessageId, providerIdentity: echo.identity }) + } + } + // An ID-less lifecycle frame can belong to an earlier send, even with one waiter. +} + +/** Session teardown: an unresolved waiter would otherwise stall its dispatch. */ +export function settleCodexEchoWaitersOnClose(echoes: CodexDispatchEchoes): void { + for (const waiter of echoes.waiters.splice(0)) { + clearTimeout(waiter.timer) + waiter.resolve(null) + } + echoes.retired.length = 0 +} + +function settleWaiter( + echoes: CodexDispatchEchoes, + waiter: CodexEchoWaiter, + identity: AgentJournalItemIdentity +): void { + removeWaiter(echoes.waiters, waiter) + clearTimeout(waiter.timer) + waiter.settledIdentity = identity + waiter.resolve(identity) +} + +function removeWaiter(list: CodexEchoWaiter[], waiter: CodexEchoWaiter): void { + const index = list.indexOf(waiter) + if (index !== -1) { + list.splice(index, 1) + } +} diff --git a/src/main/codex/codex-structured-journal-contracts.ts b/src/main/codex/codex-structured-journal-contracts.ts index acd04a4cf30e..f247e3d106d8 100644 --- a/src/main/codex/codex-structured-journal-contracts.ts +++ b/src/main/codex/codex-structured-journal-contracts.ts @@ -1,11 +1,14 @@ import type { AgentSessionDeltaCoalescerDeps } from '../native-chat/agent-session-wire/agent-session-delta-coalescer' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import type { CodexUserMessageEcho } from './codex-structured-dispatch-echo' import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' export type CodexJournalTranslatorDeps = { sink: StructuredAgentSessionEventSink bindPromptItemId?: (journalItemId: string, threadId: string, promptKey: string) => void primaryThreadId?: () => string | null + /** Fired for every live `userMessage` item; settles echo dispatch waiters. */ + onUserMessageEcho?: (echo: CodexUserMessageEcho) => void coalesceMs?: number maxRetainedBytes?: number schedule?: AgentSessionDeltaCoalescerDeps['schedule'] diff --git a/src/main/codex/codex-structured-journal-items.ts b/src/main/codex/codex-structured-journal-items.ts index fd8fbf558a84..64c25887501f 100644 --- a/src/main/codex/codex-structured-journal-items.ts +++ b/src/main/codex/codex-structured-journal-items.ts @@ -39,7 +39,7 @@ export class CodexJournalItems { constructor( private readonly deps: Pick< CodexJournalTranslatorDeps, - 'sink' | 'coalesceMs' | 'maxRetainedBytes' | 'schedule' + 'sink' | 'coalesceMs' | 'maxRetainedBytes' | 'schedule' | 'onUserMessageEcho' >, private readonly activeTurn: (threadId: string) => string | null, private readonly suppress: (threadId: string, turnId: string) => void @@ -76,6 +76,13 @@ export class CodexJournalItems { const identity = this.identityFor(event.threadId, turnId, item) // Count echoes for stable resume ordinals, but user bubbles come from submissions. if (source === 'live' && item.type === 'userMessage') { + // Load-bearing placement: the identity comes from THIS translator's + // ordinal projection, so the settled key matches history replay's. + this.deps.onUserMessageEcho?.({ + threadId: event.threadId, + clientId: readCodexJournalString(item, 'clientId'), + identity + }) return { handled: true, admission: CODEX_JOURNAL_ADMITTED } } const translated = codexJournalItem(item) diff --git a/src/main/codex/codex-structured-session-acquire.ts b/src/main/codex/codex-structured-session-acquire.ts index 8c8b39ca48be..ad8580c82431 100644 --- a/src/main/codex/codex-structured-session-acquire.ts +++ b/src/main/codex/codex-structured-session-acquire.ts @@ -8,6 +8,10 @@ import { closeFailedCodexAcquisition, stopSupersededCodexAcquisition } from './codex-structured-acquisition-lifecycle' +import { + createCodexDispatchEchoes, + resolveCodexUserMessageEcho +} from './codex-structured-dispatch-echo' import { createCodexJournalTranslator } from './codex-structured-journal-translation' import { openCodexAppServerConnection } from './codex-app-server-connection' import { codexProcessIdentity, codexProviderHandleLink } from './codex-structured-owner-identity' @@ -74,12 +78,19 @@ export async function acquireCodexStructuredSession(input: { acquireInput.identity.providerHandle.kind === 'codex' ? acquireInput.identity.providerHandle.threadId : null + // Created before the translator so the echo hook can close over it; the + // session object adopts it later (mutable-ref pattern, like primaryThreadId). + const dispatchEchoes = createCodexDispatchEchoes() const translator = acquireInput.events ? createCodexJournalTranslator({ sink: acquireInput.events, primaryThreadId: () => primaryThreadId, bindPromptItemId: (journalItemId, threadId, promptKey) => - acquisition.prompts.bindJournalItemId(journalItemId, threadId, promptKey) + acquisition.prompts.bindJournalItemId(journalItemId, threadId, promptKey), + onUserMessageEcho: (echo) => + resolveCodexUserMessageEcho(dispatchEchoes, primaryThreadId, echo, (settlement) => + deps.onDispatchSettledLate?.({ sessionId, ...settlement }) + ) }) : null const open = deps.openConnection ?? openCodexAppServerConnection @@ -193,11 +204,12 @@ export async function acquireCodexStructuredSession(input: { threadId: opened.threadId, historyPath: opened.historyPath, historyMode: opened.historyMode, - activeTurnIds: new Set(), prompts: acquisition.prompts, options: restoredCodexSessionOptions(acquireInput.options), reportedOptions: reportedCodexThreadOptions(opened), turnIdWaiters: [], + activeTurnIds: new Set(), + dispatchEchoes, translator, forceCloseUnexpected: (reason) => input.forceCloseUnexpected( diff --git a/src/main/codex/codex-structured-session-adapter.test.ts b/src/main/codex/codex-structured-session-adapter.test.ts index 32492762121a..9856aa439646 100644 --- a/src/main/codex/codex-structured-session-adapter.test.ts +++ b/src/main/codex/codex-structured-session-adapter.test.ts @@ -4,12 +4,7 @@ import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' import { CodexAppServerRequestError } from './codex-app-server-connection' -import type { - CodexAppServerConnection, - CodexAppServerConnectionHandlers, - CodexAppServerLaunch, - openCodexAppServerConnection -} from './codex-app-server-connection' +import type { openCodexAppServerConnection } from './codex-app-server-connection' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { CODEX_SPAWN_TOKEN_ENV } from './codex-structured-owner-identity' import { ORCA_STRUCTURED_SESSION_ENV } from '../../shared/structured-session-marker' @@ -21,7 +16,7 @@ import { type CodexStructuredSessionEvent } from './codex-structured-session-adapter' -const THREAD_ID = 'thread-abc' +import { fakeCodex, THREAD_ID } from './fake-codex-app-server' function identityFor(sessionId: string): AgentSessionJournalIdentity { return { @@ -39,66 +34,6 @@ const USER_MESSAGE: AgentJournalMessageItem = { blocks: [{ type: 'text', text: 'ship it' }] } -type Route = (params: Record | undefined) => unknown - -// `closed` is readonly on the real connection; the fake flips it so a test can -// kill the child at a chosen moment. -type FakeConnection = Omit & { - closed: boolean - launch: CodexAppServerLaunch - handlers: CodexAppServerConnectionHandlers - calls: { method: string; params?: Record }[] - replies: { id: number | string; result?: unknown; code?: number; message?: string }[] - closeCount: number -} - -/** Stands in for a live `codex app-server`: every RPC is answered from `routes`, - * and the test drives Codex's own traffic through `handlers`. */ -function fakeCodex(routes: Record = {}): { - connections: FakeConnection[] - openConnection: typeof openCodexAppServerConnection - routes: Record -} { - const connections: FakeConnection[] = [] - const openConnection = (async (launch, handlers = {}) => { - const connection: FakeConnection = { - launch, - handlers, - calls: [], - replies: [], - closeCount: 0, - pid: 4321, - closed: false, - request: async (method, params) => { - connection.calls.push({ method, params }) - const route = routes[method] - return route ? route(params) : {} - }, - notify: () => {}, - respond: (id, result) => connection.replies.push({ id, result }), - respondWithError: (id, code, message) => connection.replies.push({ id, code, message }), - close: async () => { - connection.closeCount += 1 - connection.closed = true - return true - } - } - connections.push(connection) - return connection - }) as typeof openCodexAppServerConnection - routes['thread/start'] ??= () => ({ - thread: { id: THREAD_ID, path: '/rollouts/abc.jsonl' }, - model: 'gpt-live', - reasoningEffort: 'medium' - }) - routes['thread/resume'] ??= (params) => ({ - thread: { id: (params as { threadId: string }).threadId }, - model: 'gpt-live', - reasoningEffort: 'medium' - }) - return { connections, openConnection, routes } -} - function adapterFor( codex: ReturnType, launch: Partial = {}, @@ -124,6 +59,9 @@ function adapterFor( terminateTurnProcesses: async () => true, now: () => 1_700_000_000_500, mintAcquisitionGeneration: () => `generation-${++acquisitionGeneration}`, + // Most tests run without a translator, so no echo ever arrives; keep the + // fresh-turn fallback grace short instead of the production 2.5s. + dispatchEchoAckTimeoutMs: 25, ...processControl }) } @@ -432,9 +370,16 @@ describe('CodexStructuredSessionAdapter.acquire', () => { }) describe('CodexStructuredSessionAdapter.dispatch', () => { - it('accepts a turn Codex names in its response', async () => { - const codex = fakeCodex({ 'turn/start': () => ({ turn: { id: 'turn-1' } }) }) + it('accepts a fresh turn Codex names in its response and start notification', async () => { + const codex = fakeCodex() const adapter = await acquired(codex) + codex.routes['turn/start'] = () => { + codex.connections[0].handlers.onNotification?.('turn/started', { + threadId: THREAD_ID, + turn: { id: 'turn-1' } + }) + return { turn: { id: 'turn-1' } } + } const outcome = await adapter.dispatch({ sessionId: 'session-1', @@ -466,6 +411,67 @@ describe('CodexStructuredSessionAdapter.dispatch', () => { }) }) + it('adopts the ordinal Codex echoes for a send coalesced into the running turn', async () => { + const codex = fakeCodex() + const adapter = adapterFor(codex) + const sink = { appendItem: () => {}, appendTombstone: () => {}, publish: () => {} } + await adapter.acquire({ + identity: identityFor('session-1'), + fence: 7, + spawnToken: 'spawn-9', + events: sink + }) + let sends = 0 + codex.routes['turn/start'] = (params) => { + const clientId = params?.clientUserMessageId ?? null + const notify = codex.connections[0].handlers.onNotification + if (++sends === 1) { + notify?.('turn/started', { threadId: THREAD_ID, turn: { id: 'turn-1' } }) + notify?.('item/started', { + threadId: THREAD_ID, + turnId: 'turn-1', + item: { type: 'userMessage', id: 'item-user-a', clientId } + }) + } else { + // Coalesced: the running turn answers, no second `turn/started`, and + // the echo lands after the agent reply — message ordinal 2, not 0. + notify?.('item/started', { + threadId: THREAD_ID, + turnId: 'turn-1', + item: { type: 'agentMessage', id: 'item-reply', text: 'working on it' } + }) + notify?.('item/started', { + threadId: THREAD_ID, + turnId: 'turn-1', + item: { type: 'userMessage', id: 'item-user-b', clientId } + }) + } + return { turn: { id: 'turn-1' } } + } + + const first = await adapter.dispatch({ + sessionId: 'session-1', + clientMessageId: 'client-a', + body: USER_MESSAGE, + fence: 7 + }) + const second = await adapter.dispatch({ + sessionId: 'session-1', + clientMessageId: 'client-b', + body: USER_MESSAGE, + fence: 7 + }) + + expect(first).toEqual({ + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD_ID, turnId: 'turn-1', ordinal: 0 } + }) + expect(second).toEqual({ + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD_ID, turnId: 'turn-1', ordinal: 2 } + }) + }) + it('accepts a turn named only by the notification that raced the ack', async () => { const codex = fakeCodex() const events: CodexStructuredSessionEvent[] = [] @@ -534,7 +540,8 @@ describe('CodexStructuredSessionAdapter.dispatch', () => { body: USER_MESSAGE, fence: 7 }) - await vi.advanceTimersByTimeAsync(10_000) + // 10s turn-id wait, then the full echo window before settling unknown. + await vi.advanceTimersByTimeAsync(40_000) expect(await dispatching).toEqual({ state: 'unknown', diff --git a/src/main/codex/codex-structured-session-adapter.ts b/src/main/codex/codex-structured-session-adapter.ts index ebd7c3331bfc..9f49f082a0ba 100644 --- a/src/main/codex/codex-structured-session-adapter.ts +++ b/src/main/codex/codex-structured-session-adapter.ts @@ -120,6 +120,8 @@ export class CodexStructuredSessionAdapter implements StructuredAgentSessionAdap method: string, params: unknown ): CodexJournalTranslationAdmission { + // Before the cancellation branch, which may consume the frame outright: it + // maintains `activeTurnIds`, which classifies a coalesced re-send. codexRewind.observeCodexRewindActivity(session, method, params) if (this.turnCancellation.handleNotification(sessionId, session, method, params)) { return { accepted: true } @@ -182,7 +184,12 @@ export class CodexStructuredSessionAdapter implements StructuredAgentSessionAdap session.dispatchPending = true try { await this.turnCancellation.captureBaseline(session) - return await dispatchCodexTurn(session, input, this.deps.requestTimeoutMs) + return await dispatchCodexTurn( + session, + input, + this.deps.requestTimeoutMs, + this.deps.dispatchEchoAckTimeoutMs + ) } finally { session.dispatchPending = false } diff --git a/src/main/codex/codex-structured-session-cancel.test.ts b/src/main/codex/codex-structured-session-cancel.test.ts index aed0722b79b3..a16c34609dbc 100644 --- a/src/main/codex/codex-structured-session-cancel.test.ts +++ b/src/main/codex/codex-structured-session-cancel.test.ts @@ -96,6 +96,8 @@ async function acquired( readProcessStartTime: async () => 1_700_000_000_000, captureTurnProcesses: async () => ({ platform: 'win32', identities: new Map() }), terminateTurnProcesses: async () => true, + // No translator here, so no echo ever arrives; keep the fallback grace short. + dispatchEchoAckTimeoutMs: 25, ...processControl }) await adapter.acquire({ identity: identity(), fence: 7, spawnToken: 'spawn-9' }) @@ -232,19 +234,25 @@ describe('CodexStructuredSessionAdapter.cancelTurn', () => { it('accepts an immediate resend after verified interruption', async () => { let nextTurn = 0 const codex = fakeCodex() - codex.routes['turn/start'] = () => ({ turn: { id: `turn-${++nextTurn}` } }) + codex.routes['turn/start'] = () => { + const turn = { id: `turn-${++nextTurn}` } + codex.connections[0].handlers.onNotification?.('turn/started', { threadId: THREAD_ID, turn }) + return { turn } + } codex.routes['turn/interrupt'] = () => { completeTurn(codex) return {} } const adapter = await acquired(codex) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-1', - body: USER_MESSAGE, - fence: 7 - }) + await expect( + adapter.dispatch({ + sessionId: 'session-1', + clientMessageId: 'client-1', + body: USER_MESSAGE, + fence: 7 + }) + ).resolves.toMatchObject({ state: 'accepted', providerIdentity: { turnId: 'turn-1' } }) await adapter.cancelTurn({ sessionId: 'session-1', turnId: 'turn-1', fence: 7 }) await expect( diff --git a/src/main/codex/codex-structured-session-close.test.ts b/src/main/codex/codex-structured-session-close.test.ts index b04e7bc2540a..3b7a37720b20 100644 --- a/src/main/codex/codex-structured-session-close.test.ts +++ b/src/main/codex/codex-structured-session-close.test.ts @@ -9,6 +9,7 @@ import { CodexStructuredSessionAdapter, type CodexStructuredSessionEvent } from './codex-structured-session-adapter' +import { createCodexDispatchEchoes } from './codex-structured-dispatch-echo' import { handleCodexSessionExit } from './codex-structured-session-close' import type { CodexSession } from './codex-structured-session-state' import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/structured-agent-session-adapter' @@ -100,6 +101,8 @@ describe('Codex structured session close lifecycle', () => { options: new Map(), reportedOptions: {}, turnIdWaiters: [], + activeTurnIds: new Set(), + dispatchEchoes: createCodexDispatchEchoes(), translator } as CodexSession const sessions = new Map([['session-1', session]]) diff --git a/src/main/codex/codex-structured-session-close.ts b/src/main/codex/codex-structured-session-close.ts index db723096177c..ad3bdf9d4445 100644 --- a/src/main/codex/codex-structured-session-close.ts +++ b/src/main/codex/codex-structured-session-close.ts @@ -1,5 +1,6 @@ import type { CodexAppServerConnection } from './codex-app-server-connection-types' import { closeProcessRegistry } from '../../shared/child-process/close-process-registry' +import { settleCodexEchoWaitersOnClose } from './codex-structured-dispatch-echo' import { cancelCodexAcquisitionAttempt, type CodexAcquisitionRegistry, @@ -46,6 +47,7 @@ export function handleCodexSessionExit(input: { session.unbindReadingControl?.() input.onEvent?.(event) session.prompts.clear() + settleCodexEchoWaitersOnClose(session.dispatchEchoes) session.translator?.dispose() return true } diff --git a/src/main/codex/codex-structured-session-options.test.ts b/src/main/codex/codex-structured-session-options.test.ts index 1f28ff5e1979..7d927bfc2eaa 100644 --- a/src/main/codex/codex-structured-session-options.test.ts +++ b/src/main/codex/codex-structured-session-options.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import type { CodexAppServerConnection } from './codex-app-server-connection' import { CodexAcquisitionWindow } from './codex-structured-acquisition-window' +import { createCodexDispatchEchoes } from './codex-structured-dispatch-echo' import { applyCodexStructuredSessionOption, readCodexStructuredSessionOptions, @@ -30,6 +31,8 @@ function optionSession(request: CodexAppServerConnection['request']): CodexSessi options: new Map(), reportedOptions: { model: 'gpt-live', effort: 'high' }, turnIdWaiters: [], + activeTurnIds: new Set(), + dispatchEchoes: createCodexDispatchEchoes(), translator: null } } diff --git a/src/main/codex/codex-structured-session-state.ts b/src/main/codex/codex-structured-session-state.ts index 12ba28d712f3..00eec6df7dad 100644 --- a/src/main/codex/codex-structured-session-state.ts +++ b/src/main/codex/codex-structured-session-state.ts @@ -1,5 +1,9 @@ -import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' +import type { + AgentJournalItemIdentity, + AgentSessionJournalIdentity +} from '../../shared/agent-session-journal-types' import { randomUUID } from 'node:crypto' +import type { CodexDispatchEchoes } from './codex-structured-dispatch-echo' import { cancelProcessAcquisition } from '../../shared/child-process/cancel-process-acquisition' import type { CodexAppServerConnection, @@ -44,6 +48,13 @@ export type CodexStructuredSessionAdapterDeps = { /** Host capability seam; production uses the native Windows process table. */ isWindowsProcessStartTimeAvailable?: () => boolean onEvent?: (event: CodexStructuredSessionEvent) => void + /** A dispatch whose echo window expired, proven delivered by a later echo. */ + onDispatchSettledLate?: (input: { + sessionId: string + clientMessageId: string + providerIdentity: AgentJournalItemIdentity + }) => void + dispatchEchoAckTimeoutMs?: number openConnection?: typeof openCodexAppServerConnection readProcessStartTime?: (pid: number) => Promise mintLinkId?: () => string @@ -66,12 +77,14 @@ export type CodexSession = { threadId: string historyPath: string | null historyMode?: 'legacy' | 'paginated' - activeTurnIds?: Set dispatchPending?: boolean prompts: CodexAcquisitionWindow['prompts'] options: Map reportedOptions: { model?: string; effort?: string } turnIdWaiters: ((turnId: string) => void)[] + /** Turns this session believes are running; classifies coalesced re-sends. */ + activeTurnIds: Set + dispatchEchoes: CodexDispatchEchoes translator: CodexJournalTranslator | null unbindReadingControl?: () => void /** Terminates this exact child as an unexpected death and enters host recovery. */ diff --git a/src/main/codex/codex-structured-turn-start.ts b/src/main/codex/codex-structured-turn-start.ts index ffe4c850d5c9..b591792a1206 100644 --- a/src/main/codex/codex-structured-turn-start.ts +++ b/src/main/codex/codex-structured-turn-start.ts @@ -6,20 +6,37 @@ import { type CodexAppServerConnection } from './codex-app-server-connection' import { isCodexAppServerUnsupportedError } from './codex-app-server-session' +import { + armCodexEchoTimeout, + discardCodexEchoWaiter, + registerCodexEchoWaiter, + retireCodexEchoWaiter, + type CodexDispatchEchoes +} from './codex-structured-dispatch-echo' import { readCodexTurnId } from './codex-structured-thread-facts' // Starting a Codex turn and learning its id, which are not the same event: // `turn/start` returns the id on newer builds and acks before it exists on // older ones, where it arrives as a `turn/started` notification instead. -/** Codex records the user message first in a turn, so the submission Orca just - * accepted is ordinal 0 of `(threadId, turnId)`. */ +/** Fallback ordinal for the sole message that opened a fresh turn — provably + * its first message. Coalesced sends must never use it; their true ordinal + * comes from the `userMessage` echo. */ export const CODEX_USER_MESSAGE_ORDINAL = 0 /** Past this the turn is real but unnameable, which the journal renders as * delivery unconfirmed rather than failure. */ const TURN_ID_WAIT_MS = 10_000 +/** Fresh-turn echo grace. Measured on codex-cli 0.153.4: turn/start ack → + * userMessage echo ≈ +1.73s for a fresh turn. Old builds never echo, so this + * also bounds their added send latency before the positional fallback. */ +const CODEX_ECHO_ACK_WINDOW_MS = 2_500 + +/** Echo window when the request timeout is unset; mirrors the connection's + * default request timeout. */ +const CODEX_DISPATCH_ECHO_TIMEOUT_MS = 30_000 + /** Keys Codex accepts as per-turn overrides. An unlisted key would otherwise * become an arbitrary client-controlled `turn/start` parameter. */ const CODEX_TURN_OPTION_KEYS = new Set([ @@ -43,6 +60,9 @@ export type CodexTurnHost = { threadId: string options: Map turnIdWaiters: ((turnId: string) => void)[] + /** Turns this session believes are running; classifies coalesced re-sends. */ + activeTurnIds: Set + dispatchEchoes: CodexDispatchEchoes } function turnInputFor(body: AgentJournalMessageItem): Record[] { @@ -60,21 +80,40 @@ function turnInputFor(body: AgentJournalMessageItem): Record[] } /** - * Resolves the turn id, or null when Codex owns a turn it never named. Throws - * only for outcomes the wire must not read as acceptance. + * Resolves the turn id, or null when Codex owns a turn it never named, plus + * whether this dispatch's own `turn/started` notification named it — freshness + * evidence, since a coalesced start emits none. Throws only for outcomes the + * wire must not read as acceptance. */ export async function startCodexTurn( host: CodexTurnHost, input: { clientMessageId: string; body: AgentJournalMessageItem; timeoutMs?: number } -): Promise { +): Promise<{ + turnId: string | null + readonly startedNotificationObserved: boolean + dispose: () => void +}> { // Registered BEFORE the call: on builds that ack first, `turn/started` can // land while the response is still in flight. + let notifiedTurnId: string | null = null let notified: ((turnId: string) => void) | null = null + let notificationTimer: ReturnType | undefined const fromNotification = new Promise((resolve) => { - notified = resolve - host.turnIdWaiters.push(resolve) - setTimeout(() => resolve(null), TURN_ID_WAIT_MS).unref?.() + notified = (turnId: string) => { + notifiedTurnId = turnId + resolve(turnId) + } + host.turnIdWaiters.push(notified) + notificationTimer = setTimeout(() => resolve(null), TURN_ID_WAIT_MS) + notificationTimer.unref?.() }) + const dispose = (): void => { + clearTimeout(notificationTimer) + const index = notified ? host.turnIdWaiters.indexOf(notified) : -1 + if (index !== -1) { + host.turnIdWaiters.splice(index, 1) + } + } try { const started = await host.connection.request( 'turn/start', @@ -86,12 +125,17 @@ export async function startCodexTurn( }, { timeoutMs: input.timeoutMs } ) - return readCodexTurnId(started) ?? (await fromNotification) - } finally { - const index = notified ? host.turnIdWaiters.indexOf(notified) : -1 - if (index !== -1) { - host.turnIdWaiters.splice(index, 1) + const turnId = readCodexTurnId(started) ?? (await fromNotification) + return { + turnId, + get startedNotificationObserved() { + return notifiedTurnId !== null && notifiedTurnId === turnId + }, + dispose } + } catch (error) { + dispose() + throw error } } @@ -103,20 +147,58 @@ export async function startCodexTurn( export async function dispatchCodexTurn( session: CodexTurnHost, input: { clientMessageId: string; body: AgentJournalMessageItem }, - timeoutMs: number | undefined + timeoutMs: number | undefined, + echoAckWindowMs: number = CODEX_ECHO_ACK_WINDOW_MS ): Promise { - let turnId: string | null + // Registered BEFORE `turn/start`: the echo can race the response. + const echo = registerCodexEchoWaiter(session.dispatchEchoes, input.clientMessageId) + let started: Awaited> try { - turnId = await startCodexTurn(session, { ...input, timeoutMs }) + started = await startCodexTurn(session, { ...input, timeoutMs }) } catch (error) { + discardCodexEchoWaiter(session.dispatchEchoes, echo.waiter) if (isCodexAppServerRequestError(error) || isCodexAppServerUnsupportedError(error)) { return { state: 'rejected', reason: (error as Error).message } } throw error } - return turnId === null - ? { state: 'unknown', reason: 'codex app-server started a turn it did not name in time' } - : { + try { + const { turnId } = started + // THE CRUX. Codex coalesces a `turn/start` issued while a turn runs into the + // RUNNING turn: same id back, and no second `turn/started`. So a response + // naming a turn already in flight is a coalesced send whose message is NOT + // ordinal 0. An observed `turn/started` overrides: on builds that ack before + // naming, the fresh turn's own notification lands first and would otherwise + // read as "already in flight". + const coalesced = + turnId !== null && !started.startedNotificationObserved && session.activeTurnIds.has(turnId) + const fullWindowMs = timeoutMs ?? CODEX_DISPATCH_ECHO_TIMEOUT_MS + // A coalesced echo is deferred until the running turn yields (measured + // +6.15s), so it gets the full request window — the outbox honestly renders + // 'dispatching' meanwhile. A fresh turn's echo lands fast or never (old + // builds), so it gets only a short grace before the positional fallback. + armCodexEchoTimeout( + session.dispatchEchoes, + echo.waiter, + coalesced || turnId === null ? fullWindowMs : Math.min(echoAckWindowMs, fullWindowMs) + ) + const identity = await echo.promise + if (identity) { + return { state: 'accepted', providerIdentity: identity } + } + if (turnId === null) { + retireCodexEchoWaiter(session.dispatchEchoes, echo.waiter) + return { state: 'unknown', reason: 'codex app-server started a turn it did not name in time' } + } + if ( + started.startedNotificationObserved && + !session.dispatchEchoes.sawClientIdEcho && + session.dispatchEchoes.waiters.length === 0 && + session.dispatchEchoes.retired.length === 0 + ) { + // Old-build compatibility: no echo will come, and the sole message that + // opened a fresh turn is provably its ordinal 0 — exactly today's identity. + return { state: 'accepted', providerIdentity: { provider: 'codex', @@ -125,4 +207,10 @@ export async function dispatchCodexTurn( ordinal: CODEX_USER_MESSAGE_ORDINAL } } + } + retireCodexEchoWaiter(session.dispatchEchoes, echo.waiter) + return { state: 'unknown', reason: 'codex accepted a message but did not echo it in time' } + } finally { + started.dispose() + } } diff --git a/src/main/codex/fake-codex-app-server.ts b/src/main/codex/fake-codex-app-server.ts new file mode 100644 index 000000000000..e1c12d3119a7 --- /dev/null +++ b/src/main/codex/fake-codex-app-server.ts @@ -0,0 +1,68 @@ +import type { + CodexAppServerConnection, + CodexAppServerConnectionHandlers, + CodexAppServerLaunch, + openCodexAppServerConnection +} from './codex-app-server-connection' + +export const THREAD_ID = 'thread-abc' + +type Route = (params: Record | undefined) => unknown + +// `closed` is readonly on the real connection; the fake flips it so a test can +// kill the child at a chosen moment. +type FakeConnection = Omit & { + closed: boolean + launch: CodexAppServerLaunch + handlers: CodexAppServerConnectionHandlers + calls: { method: string; params?: Record }[] + replies: { id: number | string; result?: unknown; code?: number; message?: string }[] + closeCount: number +} + +/** Stands in for a live `codex app-server`: every RPC is answered from `routes`, + * and the test drives Codex's own traffic through `handlers`. */ +export function fakeCodex(routes: Record = {}): { + connections: FakeConnection[] + openConnection: typeof openCodexAppServerConnection + routes: Record +} { + const connections: FakeConnection[] = [] + const openConnection = (async (launch, handlers = {}) => { + const connection: FakeConnection = { + launch, + handlers, + calls: [], + replies: [], + closeCount: 0, + pid: 4321, + closed: false, + request: async (method, params) => { + connection.calls.push({ method, params }) + const route = routes[method] + return route ? route(params) : {} + }, + notify: () => {}, + respond: (id, result) => connection.replies.push({ id, result }), + respondWithError: (id, code, message) => connection.replies.push({ id, code, message }), + close: async () => { + connection.closeCount += 1 + connection.closed = true + return true + } + } + connections.push(connection) + return connection + }) as typeof openCodexAppServerConnection + routes['thread/start'] ??= () => ({ + thread: { id: THREAD_ID, path: '/rollouts/abc.jsonl' }, + model: 'gpt-live', + reasoningEffort: 'medium' + }) + routes['thread/resume'] ??= (params) => ({ + thread: { id: (params as { threadId: string }).threadId }, + model: 'gpt-live', + reasoningEffort: 'medium' + }) + return { connections, openConnection, routes } +} diff --git a/src/main/native-chat/agent-session-journal/journal-rapid-send-turn-coalescing.test.ts b/src/main/native-chat/agent-session-journal/journal-rapid-send-turn-coalescing.test.ts new file mode 100644 index 000000000000..e2f016069c4e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-rapid-send-turn-coalescing.test.ts @@ -0,0 +1,221 @@ +// Repro for rapid-double-send data corruption (unfiled; probed live 2026-09-07). +// +// Proven against codex-cli 0.153.4 (`codex app-server` over stdio): `turn/start` +// issued while a turn is active does NOT open a new turn — it coalesces the +// message into the RUNNING turn and returns that turn's id. Both user messages +// then live in ONE turn, at message ordinals 0 and 2. +// +// Orca's `dispatchCodexTurn` stamps every accepted send with ordinal 0 +// (CODEX_USER_MESSAGE_ORDINAL), so the second submission adopts the FIRST +// message's provider identity. `applyDispatch` re-points the alias for that key +// to the second submission, and the second message's true identity (ordinal 2) +// is claimed by nobody — so a resume/history replay appends it as a brand-new +// bubble: the prompt renders twice. + +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' +import { + createCodexDispatchEchoes, + resolveCodexUserMessageEcho +} from '../../codex/codex-structured-dispatch-echo' +import { dispatchCodexTurn, type CodexTurnHost } from '../../codex/codex-structured-turn-start' +import { createTrackedJournalOpener } from './journal-store-test-open' + +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: { kind: 'codex', threadId: 'thread-1' } +} + +let root: string +let clock = 1_000 + +function tick(): number { + clock += 1 + return clock +} + +function codexItem(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } +} + +function userBody(text: string): Extract { + return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } +} + +function assistantBody(text: string): AgentJournalItemBody { + return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } +} + +function fingerprint(body: AgentJournalItemBody): string { + return structuredAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: IDENTITY.sessionId, + fields: { body } + }) +} + +/** Codex app-server as probed: a turn/start during an active turn answers with + * the ACTIVE turn (same id), exactly once per request, `turn/started` fires + * only for the first, and each accepted message is echoed back as a + * `userMessage` item carrying the client id — A at ordinal 0, B at ordinal 2 + * (an agent reply sits between them). */ +function coalescingCodexHost(): CodexTurnHost { + const host: CodexTurnHost = { + threadId: 'thread-1', + options: new Map(), + turnIdWaiters: [], + activeTurnIds: new Set(), + dispatchEchoes: createCodexDispatchEchoes(), + connection: { + request: async (_method, params) => { + const clientId = + (params as { clientUserMessageId?: string } | undefined)?.clientUserMessageId ?? null + queueMicrotask(() => + resolveCodexUserMessageEcho(host.dispatchEchoes, 'thread-1', { + threadId: 'thread-1', + clientId, + identity: codexItem(clientId === 'msg-A' ? 0 : 2) + }) + ) + return { turn: { id: 'turn-1', status: 'inProgress' } } + } + } + } + return host +} + +const journals = createTrackedJournalOpener() + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'journal-rapid-send-')) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +describe('rapid second send while a codex turn is active', () => { + it('keeps each prompt as exactly one bubble across a thread restore', async () => { + const journal = await journals.open({ + identity: IDENTITY, + journalDir: root, + now: tick, + mintEpoch: () => `epoch-${clock}` + }) + const promptA = userBody('first prompt') + const promptB = userBody('second prompt') + const host = coalescingCodexHost() + + // Send A — performSend order: submission row, then dispatch, then resolution. + await journal.appendSubmission({ + clientMessageId: 'msg-A', + payloadFingerprint: fingerprint(promptA), + body: promptA, + fence: 0 + }) + const outcomeA = await dispatchCodexTurn(host, { clientMessageId: 'msg-A', body: promptA }, 50) + if (outcomeA.state !== 'accepted') { + throw new Error(`dispatch A ${outcomeA.state}`) + } + await journal.resolveDispatch({ + clientMessageId: 'msg-A', + state: 'accepted', + providerIdentity: outcomeA.providerIdentity, + fence: 0 + }) + + // Rapid send B while turn-1 is still running: codex coalesces it into + // turn-1 and answers turn/start with the same turn id (probed live). + await journal.appendSubmission({ + clientMessageId: 'msg-B', + payloadFingerprint: fingerprint(promptB), + body: promptB, + fence: 0 + }) + const outcomeB = await dispatchCodexTurn(host, { clientMessageId: 'msg-B', body: promptB }, 50) + if (outcomeB.state !== 'accepted') { + throw new Error(`dispatch B ${outcomeB.state}`) + } + await journal.resolveDispatch({ + clientMessageId: 'msg-B', + state: 'accepted', + providerIdentity: outcomeB.providerIdentity, + fence: 0 + }) + + // Live replies stream in one turn; message ordinals count user+agent + // messages in order: A=0, reply=1, B=2, reply=3 (probed live). + await journal.appendItem(codexItem(1), assistantBody('reply to first'), { fence: 0 }) + await journal.appendItem(codexItem(3), assistantBody('reply to second'), { fence: 0 }) + + // Eviction/restart → thread/resume → restoreCodexJournalThread replays the + // turn's persisted items as history; user messages are NOT suppressed there. + await journal.appendItem(codexItem(0), promptA, { fence: 0 }) + await journal.appendItem(codexItem(2), promptB, { fence: 0 }) + + const userTexts = journal + .snapshot() + .items.filter((item) => item.body.kind === 'message' && item.body.role === 'user') + .map((item) => (item.body.kind === 'message' ? item.body.blocks : [])) + .map((blocks) => blocks.map((block) => ('text' in block ? block.text : '')).join('')) + expect(userTexts).toEqual(['first prompt', 'second prompt']) + }) + + it('control: the true identity (ordinal 2) for the second send survives the restore', async () => { + const journal = await journals.open({ + identity: IDENTITY, + journalDir: root, + now: tick, + mintEpoch: () => `epoch-${clock}` + }) + const promptA = userBody('first prompt') + const promptB = userBody('second prompt') + await journal.appendSubmission({ + clientMessageId: 'msg-A', + payloadFingerprint: fingerprint(promptA), + body: promptA, + fence: 0 + }) + await journal.resolveDispatch({ + clientMessageId: 'msg-A', + state: 'accepted', + providerIdentity: codexItem(0), + fence: 0 + }) + await journal.appendSubmission({ + clientMessageId: 'msg-B', + payloadFingerprint: fingerprint(promptB), + body: promptB, + fence: 0 + }) + await journal.resolveDispatch({ + clientMessageId: 'msg-B', + state: 'accepted', + providerIdentity: codexItem(2), + fence: 0 + }) + await journal.appendItem(codexItem(1), assistantBody('reply to first'), { fence: 0 }) + await journal.appendItem(codexItem(3), assistantBody('reply to second'), { fence: 0 }) + await journal.appendItem(codexItem(0), promptA, { fence: 0 }) + await journal.appendItem(codexItem(2), promptB, { fence: 0 }) + + const userTexts = journal + .snapshot() + .items.filter((item) => item.body.kind === 'message' && item.body.role === 'user') + .map((item) => (item.body.kind === 'message' ? item.body.blocks : [])) + .map((blocks) => blocks.map((block) => ('text' in block ? block.text : '')).join('')) + expect(userTexts).toEqual(['first prompt', 'second prompt']) + }) +}) diff --git a/src/main/runtime/structured-agent-session-integration-replay.test.ts b/src/main/runtime/structured-agent-session-integration-replay.test.ts index 990aa293ee42..6268b84ad966 100644 --- a/src/main/runtime/structured-agent-session-integration-replay.test.ts +++ b/src/main/runtime/structured-agent-session-integration-replay.test.ts @@ -85,6 +85,17 @@ function fakeCodex(): CodexScript { return { thread: { id: connection.resumedThreadId } } } if (method === 'turn/start') { + // Codex echoes the accepted message back as a live userMessage item + // carrying the client id; dispatch settles its identity on it. + handlers.onNotification?.('item/started', { + threadId: THREAD, + turnId: TURN, + item: { + type: 'userMessage', + id: 'item-0', + clientId: (params as { clientUserMessageId?: string }).clientUserMessageId ?? null + } + }) return { turn: { id: TURN } } } if (method === 'model/list') { diff --git a/src/main/runtime/structured-agent-session-integration.test.ts b/src/main/runtime/structured-agent-session-integration.test.ts index aa14aaa56397..b5ea58b667f2 100644 --- a/src/main/runtime/structured-agent-session-integration.test.ts +++ b/src/main/runtime/structured-agent-session-integration.test.ts @@ -91,6 +91,17 @@ function fakeCodex(): CodexScript { return { thread: { id: connection.resumedThreadId } } } if (method === 'turn/start') { + // Codex echoes the accepted message back as a live userMessage item + // carrying the client id; dispatch settles its identity on it. + handlers.onNotification?.('item/started', { + threadId: THREAD, + turnId: TURN, + item: { + type: 'userMessage', + id: 'item-0', + clientId: (params as { clientUserMessageId?: string }).clientUserMessageId ?? null + } + }) return { turn: { id: TURN } } } if (method === 'model/list') { diff --git a/src/main/runtime/structured-agent-session-runtime-exit.test.ts b/src/main/runtime/structured-agent-session-runtime-exit.test.ts index 5c6e43c2bc0a..11b0617aff19 100644 --- a/src/main/runtime/structured-agent-session-runtime-exit.test.ts +++ b/src/main/runtime/structured-agent-session-runtime-exit.test.ts @@ -52,7 +52,19 @@ describe('structured session runtime provider-exit wiring', () => { return { thread: { id: (params as { threadId: string }).threadId } } } if (method === 'turn/start') { - return { turn: { id: `turn-${++turn}` } } + const turnId = `turn-${++turn}` + // Codex echoes the accepted message back as a live userMessage item + // carrying the client id; dispatch settles its identity on it. + handlers.onNotification?.('item/started', { + threadId: 'thread-runtime-exit', + turnId, + item: { + type: 'userMessage', + id: `item-user-${turn}`, + clientId: (params as { clientUserMessageId?: string }).clientUserMessageId ?? null + } + }) + return { turn: { id: turnId } } } if (method === 'model/list') { return { diff --git a/src/main/runtime/structured-agent-session-runtime.ts b/src/main/runtime/structured-agent-session-runtime.ts index d9b3e59186ab..dd5e77271635 100644 --- a/src/main/runtime/structured-agent-session-runtime.ts +++ b/src/main/runtime/structured-agent-session-runtime.ts @@ -225,6 +225,14 @@ async function install(deps: StructuredAgentSessionRuntimeDeps): Promise { + void host?.settleLateDispatch(settlement).catch((error) => + deps.onError?.({ + scope: `structured-agent-session-late-settlement:${settlement.sessionId}`, + error + }) + ) + }, onEvent: (event) => { if (event.type !== 'ended' || !('cause' in event) || event.cause !== 'unexpected-exit') { return