Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 232 additions & 0 deletions src/main/codex/codex-structured-dispatch-echo.test.ts
Original file line number Diff line number Diff line change
@@ -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'
})
})
})
152 changes: 152 additions & 0 deletions src/main/codex/codex-structured-dispatch-echo.ts
Original file line number Diff line number Diff line change
@@ -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<typeof setTimeout>
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<AgentJournalItemIdentity | null> } {
let waiter!: CodexEchoWaiter
const promise = new Promise<AgentJournalItemIdentity | null>((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)
}
}
Loading
Loading