diff --git a/cli/README.md b/cli/README.md index a08c3731..318ab3c7 100644 --- a/cli/README.md +++ b/cli/README.md @@ -333,6 +333,30 @@ For an all-in-one binary that also embeds the web app: bun run build:single-exe ``` +## Large Codex thread recovery + +Cold resumes and established internal subscriptions exclude inline turns; HAPI +reads history separately. The initial root subscription retains the existing +response behavior so empty native threads can initialize their history source. +This does not truncate the native rollout or reduce the context restored by Codex. + +For exceptionally large threads, set `HAPI_CODEX_LAZY_HISTORY_IDS` to a +comma-separated list of native Codex thread IDs in the Runner environment before +starting the Runner. Only these roots replay their newest turn when reading +paginated history and skip child history replay. Other threads retain full replay; +legacy native threads without paginated history still use the full-history path. +Descendant discovery and subscriptions to loaded children are retained, including +after reconnect, so pending questions and live child events can still reach HAPI. + +This option favors recovery latency over Hub history completeness. It does not +implement UI-driven pagination or asynchronous backfill. Older turns and child +traces missing from the Hub may remain missing after reconnect; messages with an +uncertain delivery state may need manual inspection if their acceptance evidence +is in an older turn. Native rollout files remain intact. Historical fork checks +still read complete history when the message-to-turn mapping is already known; +older messages without that mapping cannot be forked through the Hub. A single +turn can still be large, so this is a turn limit rather than a byte limit. + ## Source structure - `src/api/` - Hub communication (Socket.IO + REST). diff --git a/cli/src/codex/shared/root.test.ts b/cli/src/codex/shared/root.test.ts index 7e88d0f9..a4268d97 100644 --- a/cli/src/codex/shared/root.test.ts +++ b/cli/src/codex/shared/root.test.ts @@ -8,6 +8,7 @@ import { codexPlanProposalId } from './plan'; import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; type NativeTurn = { id: string; status: string; items: unknown[] }; +type NativeRequest = { id: string | number; method: string; params: unknown }; vi.mock('../codexAppServerClient', () => ({ CodexAppServerClient: class { @@ -17,9 +18,12 @@ vi.mock('../codexAppServerClient', () => ({ queue: Array<{ id: string; clientUserMessageId: unknown; input: unknown }> = []; notify?: (method: string, params: unknown) => void; abandoned?: () => void; + serverRequest?: (request: NativeRequest) => void; + responses: Array<{ id: string | number; result: unknown }> = []; setNotificationHandler(handler: typeof this.notify) { this.notify = handler; } setTransportAbandonedHandler(handler: (() => void) | null) { this.abandoned = handler ?? undefined; } - setServerRequestHandler() {} + setServerRequestHandler(handler: (request: NativeRequest) => void) { this.serverRequest = handler; } + respond(id: string | number, result: unknown) { this.responses.push({ id, result }); } async connect() {} async initialize() { this.initialized = true; } isInitialized() { return this.initialized; } @@ -94,6 +98,8 @@ async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; cr queue: Array<{ id: string; clientUserMessageId: string; input: unknown }>; notify(method: string, params: unknown): void; abandoned(): void; + serverRequest(request: NativeRequest): void; + responses: Array<{ id: string | number; result: unknown }>; }; return { root, native, rpc, send, consumed, uncertain, metadata: () => metadata, state: () => state, updateState, @@ -119,6 +125,104 @@ async function startCompaction(f: Awaited>, id = 'inp return turn; } +describe('optional bounded history replay', () => { + it.each([ + { selected: true, fullHistory: false, bounded: true }, + { selected: true, fullHistory: true, bounded: false }, + { selected: false, fullHistory: false, bounded: false }, + ])('reads the expected history window: %j', async ({ selected, fullHistory, bounded }) => { + const f = await fixture(); + vi.stubEnv('HAPI_CODEX_LAZY_HISTORY_IDS', selected ? ' other, thread ' : 'other'); + const request = vi.spyOn(f.root.client, 'request'); + request.mockResolvedValueOnce({ thread: { id: 'thread', historyMode: 'paginated' } }); + if (bounded) request.mockResolvedValueOnce({ data: [{ id: 'new', items: [] }], nextCursor: 'older' }); + else request.mockResolvedValueOnce({ data: [{ id: 'old', items: [] }], nextCursor: 'next' }) + .mockResolvedValueOnce({ data: [{ id: 'new', items: [] }] }); + try { + expect((await f.root.readThread('thread', fullHistory)).turns).toEqual( + bounded ? [{ id: 'new', items: [] }] : [{ id: 'old', items: [] }, { id: 'new', items: [] }]); + const calls = request.mock.calls.filter(([method]) => method === 'thread/turns/list'); + expect(calls).toHaveLength(bounded ? 1 : 2); + expect(calls[0]?.[1]).toMatchObject(bounded + ? { sortDirection: 'desc', limit: 1, itemsView: 'full' } + : { sortDirection: 'asc', itemsView: 'full' }); + } finally { request.mockRestore(); vi.unstubAllEnvs(); } + }); + + it('retains legacy history reads when the native thread does not support pagination', async () => { + const f = await fixture(); + vi.stubEnv('HAPI_CODEX_LAZY_HISTORY_IDS', 'thread'); + const request = vi.spyOn(f.root.client, 'request'); + request.mockResolvedValueOnce({ thread: { id: 'thread' } }) + .mockResolvedValueOnce({ thread: { id: 'thread', turns: [{ id: 'old', items: [] }] } }); + try { + expect((await f.root.readThread()).turns).toEqual([{ id: 'old', items: [] }]); + expect(request).toHaveBeenLastCalledWith('thread/read', { threadId: 'thread', includeTurns: true }); + } finally { request.mockRestore(); vi.unstubAllEnvs(); } + }); + + it.each([true, false])('preserves initial subscription and child discovery; selected root: %s', async selected => { + const f = await fixture(); + vi.stubEnv('HAPI_CODEX_LAZY_HISTORY_IDS', selected ? 'thread' : 'other'); + const request = vi.spyOn(f.root.client, 'request'); + try { + await f.root.bind('thread', {}, true); + expect(request).toHaveBeenCalledWith('thread/resume', { threadId: 'thread' }); + expect(request.mock.calls.some(([method]) => method === 'thread/list')).toBe(true); + } finally { request.mockRestore(); vi.unstubAllEnvs(); } + }); + + it('restores loaded child subscriptions, pending questions and live events after a lazy-root reconnect', async () => { + const f = await fixture(); + vi.stubEnv('HAPI_CODEX_LAZY_HISTORY_IDS', 'thread'); + const question: NativeRequest = { id: 'native-question', method: 'item/tool/requestUserInput', params: { + threadId: 'child', turnId: 'child-turn', itemId: 'question', + questions: [{ id: 'choice', header: 'Choose', question: 'Which?', options: [{ label: 'A', description: 'A' }] }] + } }; + const original = f.root.client.request.bind(f.root.client); + const request = vi.spyOn(f.root.client, 'request').mockImplementation(async (method, params) => { + const p = params as Record | undefined; + if (method === 'thread/list') return { data: [{ id: 'child', parentThreadId: 'thread' }, { id: 'unloaded', parentThreadId: 'thread' }] }; + if (method === 'thread/loaded/list') return { data: ['child', 'unrelated'] }; + if (method === 'thread/read' && p?.threadId === 'child') return { thread: { id: 'child', parentThreadId: 'thread' } }; + if (method === 'thread/resume' && p?.threadId === 'child') { + f.native.serverRequest(question); + f.native.notify('item/completed', { threadId: 'child', turnId: 'child-turn', + item: { id: 'answer', type: 'agentMessage', text: 'Child still connected' } }); + return { thread: { id: 'child' } }; + } + return original(method, params); + }); + try { + await f.root.activate(); + f.native.serverRequest(question); + await vi.waitFor(() => expect(Object.keys(f.state().requests ?? {})).toHaveLength(1)); + const oldKey = Object.keys(f.state().requests!)[0]; + f.native.initialized = false; f.native.abandoned(); + await vi.waitFor(() => expect(request).toHaveBeenCalledWith('thread/resume', { threadId: 'child', excludeTurns: true })); + await vi.waitFor(() => { + expect(f.state().completedRequests?.[oldKey]?.status).toBe('canceled'); + expect(Object.keys(f.state().requests ?? {})).toHaveLength(1); + expect(Object.keys(f.state().requests!)[0]).not.toBe(oldKey); + }); + const newKey = Object.keys(f.state().requests!)[0]; + await f.rpc.get(RPC_METHODS.Permission)!({ id: newKey, approved: true, answers: { choice: ['A'] } }); + await vi.waitFor(() => expect(f.native.responses).toContainEqual({ + id: 'native-question', result: { answers: { choice: { answers: ['A'] } } } + })); + await vi.waitFor(() => expect(f.send).toHaveBeenCalledWith(expect.objectContaining({ + type: 'agent-run-trace', agentId: 'child', message: expect.objectContaining({ type: 'message', message: 'Child still connected' }) + }), expect.any(String))); + expect(request.mock.calls.some(([method, params]) => method === 'thread/resume' + && ['unloaded', 'unrelated'].includes(String((params as Record)?.threadId)))).toBe(false); + expect(request.mock.calls.some(([method, params]) => method === 'thread/read' + && (params as Record)?.includeTurns === true + && (params as Record)?.threadId === 'child')).toBe(false); + expect(request.mock.calls.some(([method, params]) => method === 'thread/turns/list' + && (params as Record)?.threadId === 'child')).toBe(false); + } finally { request.mockRestore(); vi.unstubAllEnvs(); } + }); +}); describe('historical fork during generation', () => { it('rejects steered and unknown-status boundaries before creating a child', async () => { const create = vi.fn() diff --git a/cli/src/codex/shared/root.ts b/cli/src/codex/shared/root.ts index 01c5afec..a98ce2f4 100644 --- a/cli/src/codex/shared/root.ts +++ b/cli/src/codex/shared/root.ts @@ -212,6 +212,7 @@ export class SharedCodexRoot { completedRequests: { ...state.completedRequests, ...Object.fromEntries(Object.entries(state.requests ?? {}).map(([id, request]) => [id, { ...request, completedAt: Date.now(), status: 'canceled' as const }])) } })); + // 空会话的首次订阅保留完整响应,以兼容原生历史源文件的初始化。 if (subscribe) response = record(await this.client.request('thread/resume', { threadId })); this.acceptSettings(response); this.acceptSettings(this.host.settingsFor(threadId) ?? {}); await this.projection.history(response.thread); await this.refresh(); await this.refreshChildren(true); @@ -315,9 +316,22 @@ export class SharedCodexRoot { } await this.projection.notification(method, params, modelAtReceipt, receivedAt); this.publishCompaction(); this.alive(); } - async readThread(threadId = this.threadId): Promise> { + private lazyHistory(): boolean { + return !!this.threadId && (process.env.HAPI_CODEX_LAZY_HISTORY_IDS ?? '') + .split(',').map(id => id.trim()).includes(this.threadId); + } + async readThread(threadId = this.threadId, fullHistory = false): Promise> { let thread = record(record(await this.client.request('thread/read', { threadId, includeTurns: false })).thread); if (thread.historyMode === 'paginated') { + // 显式选择快速恢复时只回放最近一轮,原生上下文仍由 Codex 自己恢复。 + if (this.lazyHistory() && !fullHistory && threadId === this.threadId) { + const page = record(await this.client.request('thread/turns/list', { + threadId, sortDirection: 'desc', itemsView: 'full', limit: 1 + })); + if (!Array.isArray(page.data)) throw new Error('Invalid Codex history'); + thread.turns = [...page.data].reverse(); + return thread; + } const turns: unknown[] = []; let cursor: string | undefined; do { const page = record(await this.client.request('thread/turns/list', { threadId, cursor, sortDirection: 'asc', itemsView: 'full' })); @@ -346,6 +360,8 @@ export class SharedCodexRoot { await this.projection.history(thread); await this.queue.reconcile(); this.alive(); } private async refreshChildren(subscribe: boolean): Promise { + // 历史回放可省略,子代理发现与实时订阅仍需在重连后恢复。 + const replayHistory = !this.lazyHistory(); let cursor: string | undefined; do { const page = record(await this.client.request('thread/list', { ancestorThreadId: this.threadId, cursor, @@ -368,8 +384,10 @@ export class SharedCodexRoot { for (const [id, projection] of this.children) { // Replaying a completed/unloaded child must not start its engine. try { - if (subscribe && loaded.has(id)) await this.client.request('thread/resume', { threadId: id }); - projection.reset(); await projection.history(await this.readThread(id)); + if (subscribe && loaded.has(id)) await this.client.request('thread/resume', { threadId: id, excludeTurns: true }); + if (replayHistory) { + projection.reset(); await projection.history(await this.readThread(id)); + } } catch (error) { logger.debug('[Codex shared] child history unavailable', { id, error }); } } } @@ -392,7 +410,7 @@ export class SharedCodexRoot { this.permissions = new SharedCodexPermissions(this.session, this.client, `${this.host.generation}:${randomUUID()}`); this.client.setServerRequestHandler(request => { void this.receiveRequest(request); }); const settingsRevision = this.settingsRevision; - const response = record(await this.client.request('thread/resume', { threadId: this.threadId })); + const response = record(await this.client.request('thread/resume', { threadId: this.threadId, excludeTurns: true })); const observedSettings = this.settingsRevision !== settingsRevision; this.acceptSettings(response); if (!observedSettings) this.acceptSettings(this.host.settingsFor(this.threadId) ?? {}); @@ -557,7 +575,7 @@ export class SharedCodexRoot { }); } private async assertBoundary(localId: string, turnId: string): Promise> { - const thread = await this.readThread(); + const thread = await this.readThread(this.threadId, true); const turn = (Array.isArray(thread.turns) ? thread.turns.map(record) : []).find(turn => turn.id === turnId); const first = (Array.isArray(turn?.items) ? turn.items.map(record) : []).find(item => item.type === 'userMessage'); const firstId = string(first?.clientId ?? first?.clientUserMessageId) ?? (first?.id ? `codex:${this.threadId}:user:${first.id}` : undefined); diff --git a/cli/src/codex/shared/runtime.integration.test.ts b/cli/src/codex/shared/runtime.integration.test.ts index c2d98e9a..9134b5b7 100644 --- a/cli/src/codex/shared/runtime.integration.test.ts +++ b/cli/src/codex/shared/runtime.integration.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { createServer } from 'node:http'; +import { EventEmitter } from 'node:events'; import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; @@ -13,19 +14,19 @@ import { notifyRunnerSessionStarted } from '@/runner/controlClient'; const state = vi.hoisted(() => ({ home: '', sessions: new Map(), beforeBootstrap: undefined as (() => Promise) | undefined })); const BOOTSTRAP_START_MARKER = vi.hoisted(() => 'Tue Sep 29 09:00:00 2026'); -class MockSession { +class MockSession extends EventEmitter { readonly sessionId = randomUUID(); state: AgentState = { requests: { 'old-worker': { tool: 'request_user_input', arguments: {}, createdAt: 0 } } }; metadata: Metadata; messages: unknown[] = []; consumed: string[] = []; dead = false; user?: (message: { content: { text: string } }, id?: string) => void; rpc = new Map Promise>(); rpcHandlerManager = { registerHandler: (name: string, fn: (params: unknown) => Promise) => { this.rpc.set(name, fn); } }; - constructor(cwd: string) { this.metadata = { path: cwd, host: 'test', hostPid: process.pid, machineId: 'test', flavor: 'codex', capabilities: { concurrentClients: true } }; } + constructor(cwd: string) { super(); this.metadata = { path: cwd, host: 'test', hostPid: process.pid, machineId: 'test', flavor: 'codex', capabilities: { concurrentClients: true } }; } getMetadata() { return this.metadata; } updateMetadata(fn: (m: Metadata) => Metadata) { this.metadata = fn(this.metadata); } updateAgentState(fn: (s: AgentState) => AgentState) { this.state = fn(this.state); } onUserMessage(fn: MockSession['user']) { this.user = fn; } - onCancelQueuedMessage() {} onRetryQueuedMessage() {} onReconnect() {} on() {} + onCancelQueuedMessage() {} onRetryQueuedMessage() {} onReconnect() {} sendUserMessage(text: string) { this.messages.push({ user: text }); } sendAgentMessage(body: unknown) { this.messages.push(body); } sendSessionEvent(body: unknown) { this.messages.push(body); } diff --git a/cli/src/codex/shared/runtime.ts b/cli/src/codex/shared/runtime.ts index a6645aef..76fd1c9b 100644 --- a/cli/src/codex/shared/runtime.ts +++ b/cli/src/codex/shared/runtime.ts @@ -104,7 +104,7 @@ export async function runSharedRuntime(options: SharedLaunchOptions, onReady?: ( try { await initializeSharedClient(control); // Roots remain loaded by their independent side-clients. - for (const threadId of roots.keys()) await control.request('thread/resume', { threadId }); + for (const threadId of roots.keys()) await control.request('thread/resume', { threadId, excludeTurns: true }); return; } catch (error) { logger.debug('[Codex shared] control reconnect', error); @@ -220,7 +220,7 @@ export async function runSharedRuntime(options: SharedLaunchOptions, onReady?: ( assertRunning(); // Cold-resumed threads predate the control connection's automatic // new-thread subscription. Subscribe once without changing settings. - await control.request('thread/resume', { threadId }); + await control.request('thread/resume', { threadId, excludeTurns: true }); await root.activate(initialOptions); await root.session.flush(); await persist(); @@ -375,7 +375,7 @@ export async function runSharedRuntime(options: SharedLaunchOptions, onReady?: ( const root = await prepare(launch.cwd, existing); await reserveRecord(root, threadId); return root; }); - const params = root.config({ ...launch.threadParams, threadId }); + const params = root.config({ ...launch.threadParams, threadId, excludeTurns: true }); let response: Record; try { response = record(await root.client.request('thread/resume', params));