Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
7606062
fix(native-chat): a provider's own retry progress is quoted in its re…
brennanb2025 Sep 28, 2026
fdaecf0
fix(native-chat): a Codex stream retry is one warning row that update…
brennanb2025 Sep 28, 2026
21e414f
fix(native-chat): a Codex retry row says it is retrying and keeps the…
brennanb2025 Sep 28, 2026
6b2261b
Merge remote-tracking branch 'origin/main' into brennanb2025/codex-re…
brennanb2025 Sep 28, 2026
59ab176
test(native-chat): a Codex retry re-handled after backpressure keeps …
brennanb2025 Sep 28, 2026
0fe303c
perf(native-chat): a Codex frame with no retry run open is not classi…
brennanb2025 Sep 28, 2026
23e3cb4
fix(native-chat): each Codex retry attempt is its own warning row, wi…
brennanb2025 Sep 30, 2026
7ccdf8b
Merge remote-tracking branch 'origin/main' into brennanb2025/codex-re…
brennanb2025 Sep 30, 2026
5ba6281
fix(native-chat): a transcript draws only the latest row of a provide…
brennanb2025 Sep 30, 2026
b57ae21
test(native-chat): the retry-run render test uses the message list's …
brennanb2025 Sep 30, 2026
0194b45
fix(native-chat): a Codex frame row is named for its connection, so a…
brennanb2025 Sep 30, 2026
a19c7bc
Merge remote-tracking branch 'origin/main' into brennanb2025/codex-re…
brennanb2025 Sep 30, 2026
252cd9c
fix(native-chat): agents retrying at once each keep one row, read fro…
brennanb2025 Sep 30, 2026
100e92c
test(native-chat): a reconnect's Codex rows are named for the acquisi…
brennanb2025 Sep 30, 2026
1a86450
fix(native-chat): a retry run is one agent's, so another agent's row …
brennanb2025 Sep 30, 2026
c4570a4
Merge remote-tracking branch 'origin/main' into brennanb2025/codex-re…
brennanb2025 Sep 30, 2026
7af0a14
test(native-chat): a subagent's retry run is checked in its own secti…
brennanb2025 Sep 30, 2026
04467ce
test(mobile): the retry-rows test typechecks, so the test ratchet kee…
brennanb2025 Sep 30, 2026
bc37c61
Merge remote-tracking branch 'origin/main' into brennanb2025/codex-re…
brennanb2025 Sep 30, 2026
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, expect, it, vi } from 'vitest'
import { agentSessionFailureWords } from '../../../src/shared/agent-session-failure-words'
import type { AgentJournalRenderItem } from '../../../src/shared/agent-session-journal-types'
import type { AgentSessionSubscribeEvent } from '../../../src/shared/agent-session-wire'
import type { RpcClient } from '../transport/rpc-client'
import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session'

vi.mock('@react-native-async-storage/async-storage', () => ({
default: { getItem: vi.fn(async () => null), setItem: vi.fn(), removeItem: vi.fn() }
}))

function retry(sequence: number, attempt: number): AgentJournalRenderItem {
return {
itemId: `retry-${sequence}`,
revision: 1,
sequence,
observedAt: sequence,
body: {
kind: 'status',
tone: 'warning',
...agentSessionFailureWords(
{
kind: 'providerRetrying',
detail: { text: `Reconnecting... ${attempt}/5`, audience: 'person' },
retry: { cause: 'stream disconnected before completion' }
},
{ surface: 'row', agentName: 'Codex' }
)
}
}
}

function snapshot(items: AgentJournalRenderItem[]): AgentSessionSubscribeEvent {
const newest = items.length
return {
type: 'snapshot',
sessionId: 'session-1',
fence: 3,
page: {
sessionId: 'session-1',
epoch: 'epoch-1',
fence: 3,
direction: 'tail',
items,
removedItemIds: [],
submissions: [],
window: {
oldest: { epoch: 'epoch-1', sequence: 1 },
newest: { epoch: 'epoch-1', sequence: newest },
nextCursor: { epoch: 'epoch-1', sequence: newest + 1 }
},
liveCursor: { epoch: 'epoch-1', sequence: newest },
hasOlder: false,
hasNewer: false
}
}
}

// Module scope: the harness assigns these, which a test body's own `let` would narrow to null.
let renderer: ReactTestRenderer | null = null
let hook: ReturnType<typeof useMobileStructuredAgentSession> | null = null
let listener: ((value: unknown) => void) | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
hook = null
listener = null
})

it('draws one row for a run of provider retries, with what failed on its second line', async () => {
const client: RpcClient = {
sendRequest: async () => ({
id: 'request-1',
ok: true,
result: {},
_meta: { runtimeId: 'runtime-1' }
}),
subscribe: (_method, _params, onData) => {
listener = onData
return () => {}
},
updateTerminalSubscriptionViewport: () => {},
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => null,
onStateChange: () => () => {},
notifyForeground: () => {},
close: () => {}
}
function Harness(): null {
hook = useMobileStructuredAgentSession({
client,
sessionId: 'session-1',
sourceIdentity: 'host-a\0workspace-a',
enabled: true,
connected: true,
agent: 'codex',
hostSupport: null,
onSendError: vi.fn()
})
return null
}

await act(async () => {
renderer = create(createElement(Harness))
})
await vi.waitFor(() => expect(listener).toEqual(expect.any(Function)))
act(() => listener?.(snapshot([retry(1, 1), retry(2, 2), retry(3, 3)])))

expect(hook?.session.messages.map((message) => message.blocks)).toEqual([
[
expect.objectContaining({
type: 'text',
text: 'Codex is retrying: Reconnecting... 3/5.\nstream disconnected before completion'
})
]
])
})
142 changes: 142 additions & 0 deletions src/main/codex/codex-provider-retry-idle-sweep.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// A Codex that keeps reconnecting is working, so the idle sweep must not stop it. Every retry
// frame writes and publishes its own row, and that publish is the activity the sweep reads.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import { AgentSessionRecordStore } from '../runtime/agent-session-record-store'
import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
import { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host'
import { STRUCTURED_AGENT_SESSION_IDLE_MS } from '../native-chat/agent-session-wire/structured-agent-session-idle-sweep'
import {
HOST_TEST_NOW as NOW,
HOST_TEST_SESSION as SESSION,
HOST_TEST_THREAD as THREAD,
hostTestAttachParams,
resetHostTestOperationIds
} from '../native-chat/agent-session-wire/structured-agent-session-host-test-data'
import { createCodexJournalTranslator } from './codex-structured-journal-translation'
import { openTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support'

const SWEEP_MS = 5
const RETRY_GAP_MS = 10 * 60_000

let root: string
let host: StructuredAgentSessionHost
let sink: StructuredAgentSessionEventSink | null
let closeSession: Mock<NonNullable<StructuredAgentSessionAdapter['closeSession']>>
let clock: number

function streamRetry(attempt: number): Record<string, unknown> {
return {
threadId: THREAD,
turnId: 'turn-1',
willRetry: true,
error: {
message: `Reconnecting... ${attempt}/5`,
codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 502 } }
}
}
}

/** Long enough for many sweep ticks, so "still open" means the sweep declined. */
function waitOutSeveralSweeps(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, SWEEP_MS * 20))
}

beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-codex-retry-sweep-'))
resetHostTestOperationIds()
sink = null
clock = NOW
closeSession = vi.fn(async () => true)
const store = await AgentSessionRecordStore.open({
directory: join(root, 'store'),
hostId: 'local'
})
const adapter: StructuredAgentSessionAdapter = {
acquire: async ({ fence, spawnToken, events }) => {
sink = events ?? null
return {
process: { hostId: 'local', pid: 4242, processStartTimeMs: NOW - 1_000, spawnToken },
acquisitionGeneration: 'generation-1',
link: {
linkId: `link-${fence}`,
handle: { provider: 'codex', threadId: THREAD },
origin: 'created',
mintedAtFence: fence,
observedAt: NOW
}
}
},
closeSession,
releaseAcquisition: async () => true,
dispatch: async () => ({ state: 'admitted' }),
cancelTurn: async () => ({ cancelled: false }),
answerPrompt: async () => undefined,
setOption: async () => undefined
}
host = new StructuredAgentSessionHost({
store,
adapter,
journalDatabase: openTestJournalHostDatabase(root),
claimKeyId: 'key-1',
mintSpawnToken: () => 'spawn-1',
idleSweep: { intervalMs: SWEEP_MS, idleMs: STRUCTURED_AGENT_SESSION_IDLE_MS },
now: () => clock
})
})

afterEach(async () => {
await host.flushAllStreamedEvents()
await rm(root, { recursive: true, force: true })
})

describe('a Codex reconnecting a dropped stream', () => {
it('keeps the conversation open past the idle window while retry frames arrive', async () => {
expect(await host.attach({ callerKey: 'client-1' }, hostTestAttachParams(null))).toMatchObject({
ok: true
})
if (!sink) {
throw new Error('the host never handed the provider its event sink')
}
const translator = createCodexJournalTranslator({ sink, primaryThreadId: () => THREAD })

// Five frames ten minutes apart: fifty minutes, well past the thirty-minute idle window.
for (let attempt = 1; attempt <= 5; attempt += 1) {
clock += RETRY_GAP_MS
translator.handle({
type: 'notification',
sessionId: SESSION,
threadId: THREAD,
method: 'error',
params: streamRetry(attempt)
})
await waitOutSeveralSweeps()
expect(closeSession).not.toHaveBeenCalled()
expect(host.hasSession(SESSION)).toBe(true)
}

const items = host['sessions'].get(SESSION)?.journal.snapshot().items ?? []
const retryRows = items.filter(
(item) => item.body.kind === 'status' && item.body.failure?.kind === 'providerRetrying'
)
expect(retryRows.map((row) => row.body)).toEqual(
[1, 2, 3, 4, 5].map((attempt) =>
expect.objectContaining({
failure: expect.objectContaining({
detail: expect.objectContaining({ text: `Reconnecting... ${attempt}/5` })
})
})
)
)

// Once the frames stop, the same clock does let the sweep close it.
clock += STRUCTURED_AGENT_SESSION_IDLE_MS
await vi.waitFor(() => {
expect(closeSession).toHaveBeenCalledWith(SESSION)
expect(host.hasSession(SESSION)).toBe(false)
})
})
})
Loading
Loading