Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 2 additions & 0 deletions src/main/codex/codex-requested-close-turn-timing.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createCodexDispatchEchoes } from './codex-structured-dispatch-echo'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
Expand Down Expand Up @@ -57,6 +58,7 @@ describe('requested-close durable turn timing', () => {
acquisitionGeneration: 'generation-1',
threadId: 'thread-1',
prompts: { clear: vi.fn() },
dispatchEchoes: createCodexDispatchEchoes(),
translator
} as unknown as CodexSession
const sessions = new Map([['session-1', session]])
Expand Down
152 changes: 152 additions & 0 deletions src/main/codex/codex-structured-dispatch-admission.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { describe, expect, it } from 'vitest'
import {
acquiredCodexAdapter,
echoUserMessage,
fakeCodexAppServer,
startTurn,
CODEX_TEST_THREAD_ID,
CODEX_TEST_USER_MESSAGE,
type LateSettlement
} from './codex-structured-dispatch-test-support'

function send(
adapter: Awaited<ReturnType<typeof acquiredCodexAdapter>>,
clientMessageId: string
): Promise<unknown> {
return adapter.dispatch({
sessionId: 'session-1',
clientMessageId,
body: CODEX_TEST_USER_MESSAGE,
fence: 7
})
}

describe('codex dispatch admission', () => {
it('admits a send queued behind a running turn and settles it when Codex echoes it', async () => {
// Measured on codex-cli 0.153.4: a `turn/start` issued while a turn runs is
// COALESCED into it -- same turn id back, no second `turn/started`, and the
// user message echoed only once the running turn reaches it.
const codex = fakeCodexAppServer({
'turn/start': () => ({ turn: { id: 'turn-1', status: 'inProgress' } })
})
const settlements: LateSettlement[] = []
const adapter = await acquiredCodexAdapter({ codex, settlements })
const connection = codex.connections[0]!
startTurn(connection, 'turn-1')
echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-u1', clientId: 'client-1' })

const outcome = await send(adapter, 'client-2')

// No doubt: elapsed time is not evidence, so nothing invites a Retry.
expect(outcome).toEqual({ state: 'admitted' })
expect(settlements).toEqual([])

echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-u2', clientId: 'client-2' })

// Ordinal 1, not 0: the queued send is the SECOND user message of the turn
// it was coalesced into, which is the key a history replay computes for it.
expect(settlements).toEqual([
{
sessionId: 'session-1',
clientMessageId: 'client-2',
providerIdentity: {
provider: 'codex',
threadId: CODEX_TEST_THREAD_ID,
turnId: 'turn-1',
ordinal: 1
}
}
])
})

it('correlates each send by client message id, not queue order', async () => {
const codex = fakeCodexAppServer({ 'turn/start': () => ({ turn: { id: 'turn-1' } }) })
const settlements: LateSettlement[] = []
const adapter = await acquiredCodexAdapter({ codex, settlements })
const connection = codex.connections[0]!
startTurn(connection, 'turn-1')

await send(adapter, 'client-1')
await send(adapter, 'client-2')

// The echoes arrive in the opposite order to the sends.
echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-u2', clientId: 'client-2' })
echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-u1', clientId: 'client-1' })

expect(
settlements.map((settlement) => [
settlement.clientMessageId,
(settlement.providerIdentity as { ordinal: number }).ordinal
])
).toEqual([
['client-2', 0],
['client-1', 1]
])
})

it('settles nothing for a user message this session never sent', async () => {
const codex = fakeCodexAppServer({ 'turn/start': () => ({ turn: { id: 'turn-1' } }) })
const settlements: LateSettlement[] = []
const adapter = await acquiredCodexAdapter({ codex, settlements })
const connection = codex.connections[0]!
startTurn(connection, 'turn-1')
await send(adapter, 'client-1')

// A message another client sent on the same thread, and one Codex did not
// correlate at all.
echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-x', clientId: 'someone-else' })
echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-y' })

expect(settlements).toEqual([])
})

it('rejects only when Codex answered and declined, and arms nothing for it', async () => {
const { CodexAppServerRequestError } = await import('./codex-app-server-connection')
const codex = fakeCodexAppServer({
'turn/start': () => {
throw new CodexAppServerRequestError('turn/start', -32602, 'thread not found')
}
})
const settlements: LateSettlement[] = []
const adapter = await acquiredCodexAdapter({ codex, settlements })
const connection = codex.connections[0]!
startTurn(connection, 'turn-1')

expect(await send(adapter, 'client-1')).toEqual({
state: 'rejected',
reason: 'thread not found'
})

// A refused write is disarmed, so a later echo of that id settles nothing.
echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-u1', clientId: 'client-1' })
expect(settlements).toEqual([])
})

it('leaves no waiter behind when the session closes', async () => {
const codex = fakeCodexAppServer({ 'turn/start': () => ({ turn: { id: 'turn-1' } }) })
const settlements: LateSettlement[] = []
const adapter = await acquiredCodexAdapter({ codex, settlements })
const connection = codex.connections[0]!
startTurn(connection, 'turn-1')
await send(adapter, 'client-1')

await adapter.closeSession('session-1')

echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-u1', clientId: 'client-1' })
expect(settlements).toEqual([])
})

it('leaves no waiter behind when the child exits', async () => {
const codex = fakeCodexAppServer({ 'turn/start': () => ({ turn: { id: 'turn-1' } }) })
const settlements: LateSettlement[] = []
const adapter = await acquiredCodexAdapter({ codex, settlements })
const connection = codex.connections[0]!
startTurn(connection, 'turn-1')
await send(adapter, 'client-1')

connection.handlers.onExit?.(new Error('codex app-server exited'))

echoUserMessage(connection, { turnId: 'turn-1', itemId: 'item-u1', clientId: 'client-1' })
expect(settlements).toEqual([])
})
})
107 changes: 107 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,107 @@
import { describe, expect, it } from 'vitest'
import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types'
import {
createCodexDispatchEchoes,
readCodexDispatchEcho,
MAX_CODEX_PENDING_DISPATCH_ECHOES
} from './codex-structured-dispatch-echo'

const CODEX_IDENTITY: AgentJournalItemIdentity = {
provider: 'codex',
threadId: 'thread-1',
turnId: 'turn-1',
ordinal: 3
}

describe('codex dispatch echoes', () => {
it('settles by client message id rather than arrival order', () => {
const echoes = createCodexDispatchEchoes()
echoes.arm('client-1')
echoes.arm('client-2')

// Codex coalesces both sends into one turn, and the second can be echoed
// first. Queue position would settle the wrong submission here.
expect(echoes.settle('client-2')).toBe(true)
expect(echoes.settle('client-1')).toBe(true)
expect(echoes.size).toBe(0)
})

it('refuses an echo this session never armed', () => {
const echoes = createCodexDispatchEchoes()
echoes.arm('client-1')

expect(echoes.settle('client-from-history')).toBe(false)
expect(echoes.size).toBe(1)
})

it('settles a send exactly once', () => {
const echoes = createCodexDispatchEchoes()
echoes.arm('client-1')

expect(echoes.settle('client-1')).toBe(true)
expect(echoes.settle('client-1')).toBe(false)
})

it('drops a send whose write never reached the provider', () => {
const echoes = createCodexDispatchEchoes()
echoes.arm('client-1')
echoes.disarm('client-1')

expect(echoes.settle('client-1')).toBe(false)
})

it('clears every armed send', () => {
const echoes = createCodexDispatchEchoes()
echoes.arm('client-1')
echoes.arm('client-2')

echoes.clear()

expect(echoes.size).toBe(0)
expect(echoes.settle('client-1')).toBe(false)
})

it('retains a bounded window, dropping the oldest first', () => {
const echoes = createCodexDispatchEchoes()
for (let index = 0; index <= MAX_CODEX_PENDING_DISPATCH_ECHOES; index += 1) {
echoes.arm(`client-${index}`)
}

expect(echoes.size).toBe(MAX_CODEX_PENDING_DISPATCH_ECHOES)
expect(echoes.settle('client-0')).toBe(false)
expect(echoes.settle(`client-${MAX_CODEX_PENDING_DISPATCH_ECHOES}`)).toBe(true)
})
})

describe('readCodexDispatchEcho', () => {
it('reads the client message id off a user message', () => {
expect(
readCodexDispatchEcho(
{ type: 'userMessage', id: 'item-1', clientId: 'client-1' },
CODEX_IDENTITY
)
).toEqual({ clientMessageId: 'client-1', providerIdentity: CODEX_IDENTITY })
})

it('ignores an item that is not a user message', () => {
expect(
readCodexDispatchEcho(
{ type: 'agentMessage', id: 'item-1', clientId: 'client-1' },
CODEX_IDENTITY
)
).toBeNull()
})

it('ignores a user message Codex did not correlate', () => {
expect(readCodexDispatchEcho({ type: 'userMessage', id: 'item-1' }, CODEX_IDENTITY)).toBeNull()
})

it('ignores an item with no durable Codex identity', () => {
expect(
readCodexDispatchEcho(
{ type: 'userMessage', id: 'item-1', clientId: 'client-1' },
{ provider: 'orca', clientMessageId: 'codex-item:thread-1:item-1' }
)
).toBeNull()
})
})
61 changes: 61 additions & 0 deletions src/main/codex/codex-structured-dispatch-echo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types'

/** Sends awaiting their echo, oldest first. A send whose echo never arrives is
* retired by the journal's pending-submission recovery on exit, not from here. */
export const MAX_CODEX_PENDING_DISPATCH_ECHOES = 256

/**
* Which sends this session is still waiting to hear back about, keyed by the
* client message id Codex echoes on the user message.
*
* Keyed rather than ordered on purpose: Codex coalesces a `turn/start` issued
* while a turn is running into that turn, so two sends can share one turn id and
* their echoes arrive far apart. Queue position identifies neither.
*/
export type CodexDispatchEchoes = {
/** Arms settlement for a send about to be written. */
arm: (clientMessageId: string) => void
/** True once, for a send this session armed and has not yet settled. */
settle: (clientMessageId: string) => boolean
/** Drops an armed send whose write never reached the provider. */
disarm: (clientMessageId: string) => void
clear: () => void
readonly size: number
}

export function createCodexDispatchEchoes(): CodexDispatchEchoes {
const armed = new Set<string>()
return {
arm(clientMessageId) {
armed.delete(clientMessageId)
armed.add(clientMessageId)
while (armed.size > MAX_CODEX_PENDING_DISPATCH_ECHOES) {
const oldest = armed.values().next().value
if (typeof oldest !== 'string') {
break
}
armed.delete(oldest)
}
},
settle: (clientMessageId) => armed.delete(clientMessageId),
disarm: (clientMessageId) => void armed.delete(clientMessageId),
clear: () => armed.clear(),
get size() {
return armed.size
}
}
}

/** The user-message echo a settlement is read off, or null for any other item. */
export function readCodexDispatchEcho(
item: { type: string; id: string } & Record<string, unknown>,
identity: AgentJournalItemIdentity
): { clientMessageId: string; providerIdentity: AgentJournalItemIdentity } | null {
if (item.type !== 'userMessage' || identity.provider !== 'codex') {
return null
}
const clientMessageId = item.clientId
return typeof clientMessageId === 'string' && clientMessageId.length > 0
? { clientMessageId, providerIdentity: identity }
: null
}
Loading