fix(codex): fork archived sessions without reopening the source (#2231)

* fix(codex): fork archived sessions without reopening the source

* fix(codex): reconcile interrupted archived fork recovery

* fix(codex): release rejected forks and serialize source startup

* fix(codex): fence unconfirmed resume startup across retries

* test(codex): validate durable resume recovery and serialize archive

* fix(codex): block local resume of pending archived fork sources

* fix(hub): coalesce concurrent resume requests to preserve idempotent startup

* fix(hub): bypass startup coalescing for PTY sessions
This commit is contained in:
Ananovo
2026-11-01 09:55:01 +08:00
committed by GitHub
parent 639f71b6a6
commit 46bae9b0f1
30 changed files with 1377 additions and 34 deletions
@@ -29,6 +29,7 @@ vi.mock('@/ui/logger', () => ({
}));
import { CodexAppServerClient, isIndeterminateError } from './codexAppServerClient';
import { killProcessByChildProcess } from '@/utils/process';
function fakeStream(): EventEmitter & { setEncoding: ReturnType<typeof vi.fn> } {
return Object.assign(new EventEmitter(), { setEncoding: vi.fn() });
@@ -36,6 +37,8 @@ function fakeStream(): EventEmitter & { setEncoding: ReturnType<typeof vi.fn> }
function fakeChild() {
return Object.assign(new EventEmitter(), {
exitCode: null as number | null,
signalCode: null as string | null,
stdin: Object.assign(new EventEmitter(), {
end: vi.fn(),
write: vi.fn(),
@@ -60,6 +63,33 @@ describe('CodexAppServerClient process cwd', () => {
beforeEach(() => {
execFileSyncMock.mockClear();
spawnMock.mockReset();
vi.mocked(killProcessByChildProcess).mockClear();
});
it('lets a completed read/fork helper exit on stdin EOF without process-tree probing', async () => {
const child = fakeChild();
child.stdin.end.mockImplementation(() => { child.exitCode = 0; child.emit('exit', 0, null); });
spawnMock.mockReturnValue(child);
const client = new CodexAppServerClient();
await client.connect();
await client.disconnect({ gracefulTimeoutMs: 100 });
expect(child.stdin.end).toHaveBeenCalledTimes(1);
expect(killProcessByChildProcess).not.toHaveBeenCalled();
expect(client.isConnected()).toBe(false);
});
it('falls back to exact child cleanup if graceful helper shutdown does not finish', async () => {
vi.useFakeTimers();
try {
const child = fakeChild();
spawnMock.mockReturnValue(child);
const client = new CodexAppServerClient();
await client.connect();
const closing = client.disconnect({ gracefulTimeoutMs: 100 });
await vi.advanceTimersByTimeAsync(100);
await closing;
expect(killProcessByChildProcess).toHaveBeenCalledWith(child);
} finally { vi.useRealTimers(); }
});
it('passes an explicit neutral cwd to the app-server process', async () => {
+13 -2
View File
@@ -519,7 +519,7 @@ export class CodexAppServerClient extends JsonLineParser {
return response as ThreadGoalClearResponse;
}
async disconnect(): Promise<void> {
async disconnect(options?: { gracefulTimeoutMs?: number }): Promise<void> {
if (this.socket) {
const socket = this.socket;
this.socket = null;
@@ -538,7 +538,18 @@ export class CodexAppServerClient extends JsonLineParser {
try {
child?.stdin.end();
if (child) {
if (child && options?.gracefulTimeoutMs && child.exitCode === null && child.signalCode === null) {
// Read/fork helpers have no active turns after archiving their
// temporary child. EOF normally exits the native server; avoid
// an expensive Windows process-tree probe in the Runner loop.
await new Promise<void>(resolve => {
const finish = () => { clearTimeout(timer); child.off('exit', finish); child.off('error', finish); resolve(); };
const timer = setTimeout(finish, options.gracefulTimeoutMs);
child.once('exit', finish); child.once('error', finish);
if (child.exitCode !== null || child.signalCode !== null) finish();
});
}
if (child && child.exitCode === null && child.signalCode === null) {
await killProcessByChildProcess(child);
}
} catch (error) {
+162
View File
@@ -0,0 +1,162 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { ApiClient } from '@/api/api'
import { CodexAppServerClient } from '../codexAppServerClient'
import { codexHome } from './registry'
import { forkArchivedCodex, performArchivedFork, type ArchivedForkJournal } from './archivedFork'
import type { ForkArchivedCodexRequest } from '@hapi/protocol/apiTypes'
vi.mock('@/utils/process', async importOriginal => ({
...await importOriginal<typeof import('@/utils/process')>(),
// Ownership must conservatively retain a live PID with an unknown marker;
// the OS-specific marker probe is covered separately from this journal test.
getProcessStartMarker: () => undefined,
isProcessAlive: (pid: number) => pid === process.pid
}))
function fixture() {
const request: ForkArchivedCodexRequest = { operationId: 'operation', sourceSessionId: 'hapi-source', sourceThreadId: 'source', directory: '/work',
boundary: { localId: 'second', turnId: 'turn-2' } }
const journal: ArchivedForkJournal = { request: structuredClone(request), restoreRequired: false, forkIssued: false, done: false }
let archived = true
const source = { id: 'source', cwd: '/work', status: { type: 'notLoaded' }, turns: [
{ id: 'turn-1', status: 'completed', items: [{ type: 'userMessage', clientId: 'first' }] },
{ id: 'turn-2', status: 'interrupted', items: [{ type: 'userMessage', clientId: 'second' }] }
] }
const calls: string[] = []
const native = vi.fn(async (method: string, params?: unknown): Promise<unknown> => {
const p = params as Record<string, unknown>
calls.push(`${method}:${p?.threadId ?? ''}`)
if (method === 'thread/read') return { thread: source }
if (method === 'thread/loaded/list') { expect(params).toEqual({}); return { data: [] } }
if (method === 'thread/unarchive') { archived = false; return {} }
if (method === 'thread/archive') { if (p.threadId === 'source') archived = true; return {} }
if (method === 'thread/fork') {
if (archived) throw new Error('session source is archived. Run `codex unarchive source` to unarchive it first.')
return { thread: { id: 'child', forkedFromId: 'source', parentThreadId: null } }
}
throw new Error(`Unexpected method ${method}`)
})
const client = { request: native } as unknown as Parameters<typeof performArchivedFork>[0]
const snapshots: ArchivedForkJournal[] = []
const save = vi.fn(async () => { snapshots.push(structuredClone(journal)) })
const inactive = vi.fn(async () => {})
return { request, journal, client, native, source, calls, save, snapshots, inactive, archived: () => archived,
run: () => performArchivedFork(client, request, journal, save, inactive) }
}
describe('archived Codex native fork', () => {
it('unarchives, forks at the exact boundary, restores source, and releases the child writer', async () => {
const f = fixture()
await expect(f.run()).resolves.toBe('child')
expect(f.archived()).toBe(true)
expect(f.calls).toEqual(['thread/read:source', 'thread/read:source', 'thread/fork:source', 'thread/unarchive:source',
'thread/fork:source', 'thread/loaded/list:', 'thread/archive:source', 'thread/archive:child'])
expect(f.native).toHaveBeenCalledWith('thread/fork', { threadId: 'source', beforeTurnId: 'turn-2', deferGoalContinuation: true, excludeTurns: true })
expect(f.snapshots.some(snapshot => snapshot.restoreRequired && !snapshot.forkIssued)).toBe(true)
expect(f.journal).toMatchObject({ nativeSessionId: 'child', restoreRequired: false, done: true })
const count = f.native.mock.calls.length
await expect(f.run()).resolves.toBe('child')
expect(f.native).toHaveBeenCalledTimes(count)
})
it('restores a source even when the second fork fails; never replays an unconfirmed mutation', async () => {
const f = fixture()
const original = f.native.getMockImplementation()!
f.native.mockImplementation(async (method, params) => {
if (method === 'thread/fork' && !f.archived()) throw new Error('transport lost')
return original(method, params)
})
await expect(f.run()).rejects.toThrow('transport lost')
expect(f.archived()).toBe(true)
await expect(f.run()).rejects.toThrow('unconfirmed')
expect(f.native.mock.calls.filter(([method]) => method === 'thread/fork')).toHaveLength(2)
})
it('reconciles a persisted restore intent and known child without another fork', async () => {
const f = fixture()
Object.assign(f.journal, { restoreRequired: true, forkIssued: true, nativeSessionId: 'child' })
await expect(f.run()).resolves.toBe('child')
expect(f.calls).toEqual(['thread/loaded/list:', 'thread/archive:source', 'thread/archive:child'])
})
it('retains recovery intent when restoring the source fails', async () => {
const f = fixture()
const original = f.native.getMockImplementation()!
f.native.mockImplementation(async (method, params) => {
if (method === 'thread/archive' && (params as { threadId: string }).threadId === 'source') throw new Error('archive unavailable')
return original(method, params)
})
await expect(f.run()).rejects.toThrow('archive unavailable')
expect(f.journal).toMatchObject({ restoreRequired: true, nativeSessionId: 'child', done: false })
f.native.mockImplementation(original)
await expect(f.run()).resolves.toBe('child')
expect(f.native.mock.calls.filter(([method]) => method === 'thread/fork')).toHaveLength(2)
})
it.each(['loaded', 'boundary', 'cwd', 'identity', 'unfinished', 'steered'])('rejects an unsafe %s source before native mutation', async kind => {
const f = fixture()
if (kind === 'loaded') f.source.status.type = 'idle'
if (kind === 'boundary') f.request.boundary!.turnId = 'missing'
if (kind === 'cwd') f.source.cwd = '/another'
if (kind === 'identity') f.source.id = 'another'
if (kind === 'unfinished') f.source.turns[1].status = 'inProgress'
if (kind === 'steered') f.request.boundary!.localId = 'not-first'
f.journal.request = structuredClone(f.request)
await expect(f.run()).rejects.toThrow()
expect(f.native.mock.calls.some(([method]) => ['thread/fork', 'thread/unarchive'].includes(method))).toBe(false)
})
it('refuses to restore over a newly loaded source', async () => {
const f = fixture()
f.journal.restoreRequired = true
f.native.mockResolvedValue({ data: ['source'] })
await expect(f.run()).rejects.toThrow('potentially active')
expect(f.journal.restoreRequired).toBe(true)
expect(f.calls).toEqual([])
})
it('stops before any native call when HAPI source was reopened', async () => {
const f = fixture()
f.inactive.mockRejectedValue(new Error('Source session changed'))
await expect(f.run()).rejects.toThrow('Source session changed')
expect(f.native).not.toHaveBeenCalled()
})
})
describe('archived fork workspace preflight', () => {
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs() })
it.each(['fresh', 'restore', 'unconfirmed', 'known-child'].flatMap(kind => ['policy', 'ownership'].map(preflight => ({ kind, preflight }))))('rejects $preflight preflight for a $kind operation and preserves recovery intent', async ({ kind, preflight }) => {
const home = await mkdtemp(join(tmpdir(), 'hapi-archived-preflight-'))
vi.stubEnv('CODEX_HOME', home)
vi.spyOn(ApiClient, 'create').mockResolvedValue({} as ApiClient)
const connect = vi.spyOn(CodexAppServerClient.prototype, 'connect').mockRejectedValue(new Error('unexpected native startup'))
const request = fixture().request
const target = join(home, 'hapi-archived-forks', `${request.operationId}.json`)
const journal: ArchivedForkJournal = { request, restoreRequired: kind === 'restore',
forkIssued: kind === 'unconfirmed' || kind === 'known-child', done: false,
...(kind === 'known-child' ? { nativeSessionId: 'child' } : {}) }
try {
if (preflight === 'ownership') {
const owners = join(home, 'hapi-runtime-owners')
await mkdir(owners, { recursive: true })
await writeFile(join(owners, 'live.json'), JSON.stringify({ id: 'other', pid: process.pid, marker: '',
endpoint: 'mock', command: 'codex', args: [], codexHome: codexHome(), hub: 'hub', authHash: 'hash',
sessions: { source: { threadId: request.sourceThreadId, namespace: 'ns', active: true } } }))
}
if (kind !== 'fresh') {
await mkdir(join(home, 'hapi-archived-forks'), { recursive: true })
await writeFile(target, JSON.stringify(journal))
}
expect(await forkArchivedCodex(request, async () => preflight !== 'policy')).toEqual({
error: preflight === 'policy' ? 'Directory is outside workspace roots'
: 'Thread belongs to another Codex runtime. Use hapi resume source.', rollbackSafe: kind === 'fresh'
})
expect(connect).not.toHaveBeenCalled()
if (kind !== 'fresh') expect(JSON.parse(await readFile(target, 'utf8'))).toEqual(journal)
} finally { await rm(home, { recursive: true, force: true }) }
})
})
+163
View File
@@ -0,0 +1,163 @@
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
import { join, resolve } from 'node:path'
import { randomUUID } from 'node:crypto'
import { z } from 'zod'
import type { ForkArchivedCodexRequest, ForkArchivedCodexResponse } from '@hapi/protocol/apiTypes'
import { ApiClient } from '@/api/api'
import { CodexAppServerClient } from '../codexAppServerClient'
import { initializeSharedClient } from './launch'
import { codexHome, withThreadOwnership } from './registry'
import { record, string } from './gateway'
const JournalSchema = z.object({
request: z.object({ operationId: z.string(), sourceSessionId: z.string(), sourceThreadId: z.string(), directory: z.string(),
boundary: z.object({ localId: z.string(), turnId: z.string() }).optional() }),
restoreRequired: z.boolean(), forkIssued: z.boolean(), nativeSessionId: z.string().optional(), done: z.boolean()
})
export type ArchivedForkJournal = z.infer<typeof JournalSchema>
type NativeClient = Pick<CodexAppServerClient, 'request'>
async function readHistory(client: NativeClient, threadId: string): Promise<Record<string, unknown>> {
let thread = record(record(await client.request('thread/read', { threadId, includeTurns: false })).thread)
if (thread.historyMode === 'paginated') {
const turns: unknown[] = []
let cursor: string | undefined
do {
const page = record(await client.request('thread/turns/list', { threadId, cursor, sortDirection: 'asc', itemsView: 'full' }))
if (!Array.isArray(page.data)) throw new Error('Invalid native history page')
turns.push(...page.data)
cursor = string(page.nextCursor)
} while (cursor)
thread.turns = turns
} else thread = record(record(await client.request('thread/read', { threadId, includeTurns: true })).thread)
return thread
}
/** Separated from transport/locks so failure and recovery paths are testable. */
export async function performArchivedFork(
client: NativeClient, request: ForkArchivedCodexRequest, journal: ArchivedForkJournal,
save: () => Promise<void>, assertSourceInactive: () => Promise<void>
): Promise<string> {
if (JSON.stringify(journal.request) !== JSON.stringify(request)) throw new Error('Archived fork reservation does not match this request')
if (journal.done && journal.nativeSessionId) return journal.nativeSessionId
const restoreSource = async () => {
if (!journal.restoreRequired) return
await assertSourceInactive()
const loaded = record(await client.request('thread/loaded/list', {}))
if (!Array.isArray(loaded.data) || loaded.data.includes(request.sourceThreadId)) {
throw new Error('Source was loaded during archived fork; refuse to archive a potentially active conversation')
}
await client.request('thread/archive', { threadId: request.sourceThreadId })
journal.restoreRequired = false
await save()
}
// A previous process may have died after unarchive or after creating a child.
// Restore first; a dispatched fork without a returned id must never replay.
await restoreSource()
if (journal.forkIssued && !journal.nativeSessionId) {
throw new Error('Previous native fork outcome is unconfirmed; inspect the operation before retrying')
}
if (!journal.nativeSessionId) {
await assertSourceInactive()
const source = await readHistory(client, request.sourceThreadId)
if (source.id !== request.sourceThreadId || source.parentThreadId) throw new Error('Archived fork requires an exact native root thread')
if (resolve(string(source.cwd) ?? '') !== resolve(request.directory)) throw new Error('Native source directory does not match the HAPI session')
if (record(source.status).type !== 'notLoaded') throw new Error('Native source is loaded; stop it before forking archived history')
if (request.boundary) {
const turns = (Array.isArray(source.turns) ? source.turns : []).map(record)
const index = turns.findIndex(turn => turn.id === request.boundary!.turnId)
const selected = turns[index]
const user = (Array.isArray(selected?.items) ? selected.items.map(record) : []).find(item => item.type === 'userMessage')
const localId = string(user?.clientId ?? user?.clientUserMessageId)
?? (user?.id ? `codex:${request.sourceThreadId}:user:${user.id}` : undefined)
if (index < 0 || localId !== request.boundary.localId
|| turns.slice(0, index + 1).some(turn => !['completed', 'interrupted', 'failed'].includes(string(turn.status) ?? ''))) {
throw new Error('Historical fork boundary is missing, unfinished, or inside a steered native turn')
}
}
const fork = async () => {
await assertSourceInactive()
journal.forkIssued = true
await save()
const response = record(await client.request('thread/fork', {
threadId: request.sourceThreadId,
...(request.boundary ? { beforeTurnId: request.boundary.turnId } : {}),
deferGoalContinuation: true, excludeTurns: true
}))
const child = record(response.thread)
const id = string(child.id)
if (!id || id === request.sourceThreadId || child.parentThreadId === request.sourceThreadId) {
throw new Error('Native fork did not create an independent root')
}
journal.nativeSessionId = id
await save()
}
try {
try { await fork() }
catch (error) {
// Only an explicit archived rejection proves no fork occurred.
if (!(error instanceof Error) || !error.message.startsWith(`session ${request.sourceThreadId} is archived.`)) throw error
journal.forkIssued = false
journal.restoreRequired = true
await save()
await assertSourceInactive()
await client.request('thread/unarchive', { threadId: request.sourceThreadId })
await fork()
}
} finally { await restoreSource() }
}
// Release the temporary server's writer through native archive. The child
// launcher unarchives this exact id; no source resume or model turn occurs.
await client.request('thread/archive', { threadId: journal.nativeSessionId })
journal.done = true
await save()
return journal.nativeSessionId!
}
export async function forkArchivedCodex(request: ForkArchivedCodexRequest, allowsDirectory: () => Promise<boolean>): Promise<ForkArchivedCodexResponse> {
const home = codexHome()
const journalDirectory = join(home, 'hapi-archived-forks')
await mkdir(journalDirectory, { recursive: true, mode: 0o700 })
const target = join(journalDirectory, `${request.operationId}.json`)
const loadJournal = async (): Promise<ArchivedForkJournal> => {
try { return JournalSchema.parse(JSON.parse(await readFile(target, 'utf8'))) }
catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
return { request, restoreRequired: false, forkIssued: false, done: false }
}
}
const failure = (error: unknown, journal?: ArchivedForkJournal): ForkArchivedCodexResponse => ({
error: error instanceof Error ? error.message : String(error),
rollbackSafe: Boolean(journal && !journal.forkIssued && !journal.restoreRequired && !journal.nativeSessionId)
})
return withThreadOwnership(home, request.sourceThreadId, `archived-fork:${request.operationId}`, async () => {
const api = await ApiClient.create()
const assertSourceInactive = async () => {
const source = await api.getSession(request.sourceSessionId)
if (source.active || source.metadata?.codexSessionId !== request.sourceThreadId
|| source.metadata?.codexArchivedFork?.operationId !== request.operationId) {
throw new Error('Source session changed during archived fork')
}
}
const journal = await loadJournal()
const save = async () => {
const temporary = `${target}.${randomUUID()}.tmp`
await writeFile(temporary, JSON.stringify(journal), { mode: 0o600 })
await rename(temporary, target)
}
const client = new CodexAppServerClient({ cwd: request.directory })
client.setServerRequestHandler(() => {})
try {
// Report policy rejection against the persisted journal: a fresh
// attempt is safe to release, but interrupted native work is not.
if (!await allowsDirectory()) throw new Error('Directory is outside workspace roots')
await initializeSharedClient(client)
return { nativeSessionId: await performArchivedFork(client, request, journal, save, assertSourceInactive) }
} catch (error) {
return failure(error, journal)
} finally { await client.disconnect({ gracefulTimeoutMs: 2_000 }) }
}, async error => {
try { return failure(error, await loadJournal()) }
catch { return failure(error) } // Unreadable journals cannot prove rollback safe.
})
}
+19 -11
View File
@@ -79,21 +79,29 @@ export async function saveRuntime(record: CodexRuntimeRecord): Promise<void> {
}
/** The store-wide lock spans cold resume, not merely registry writes. */
export async function withThreadOwnership<T>(home: string, threadId: string, ownId: string, work: () => Promise<T>): Promise<T> {
export async function withThreadOwnership<T>(home: string, threadId: string, ownId: string, work: () => Promise<T>,
onPreflightRejected?: (error: unknown) => Promise<T>): Promise<T> {
const directory = join(home, 'hapi-runtime-owners');
await mkdir(directory, { recursive: true, mode: 0o700 });
return withSettingsFileLock(join(directory, 'ownership'), async () => {
for (const owner of await readRecords(directory, true)) {
if (owner.id === ownId || owner.codexHome !== home) continue;
if (owner.pendingCreations?.length && runtimeMayBeAlive(owner)) {
throw new Error(`Codex runtime ${owner.id} has an unconfirmed creation. Inspect/stop that runtime before cold resume; its thread ID may be unknown.`);
}
const match = Object.entries(owner.sessions).find(([, session]) => session.threadId === threadId && session.active);
if (!match) continue;
const orphanAlive = owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker);
if (generationMayBeAlive(owner.pid, owner.marker) || orphanAlive) {
throw new Error(`Thread belongs to another Codex runtime. Use hapi resume ${match[0]}.${orphanAlive && !runtimeAlive(owner) ? ' Its wrapper exited; stop the orphaned runtime before recovery.' : ''}`);
try {
for (const owner of await readRecords(directory, true)) {
if (owner.id === ownId || owner.codexHome !== home) continue;
if (owner.pendingCreations?.length && runtimeMayBeAlive(owner)) {
throw new Error(`Codex runtime ${owner.id} has an unconfirmed creation. Inspect/stop that runtime before cold resume; its thread ID may be unknown.`);
}
const match = Object.entries(owner.sessions).find(([, session]) => session.threadId === threadId && session.active);
if (!match) continue;
const orphanAlive = owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker);
if (generationMayBeAlive(owner.pid, owner.marker) || orphanAlive) {
throw new Error(`Thread belongs to another Codex runtime. Use hapi resume ${match[0]}.${orphanAlive && !runtimeAlive(owner) ? ' Its wrapper exited; stop the orphaned runtime before recovery.' : ''}`);
}
}
} catch (error) {
// Still under the store lock, before work can mutate native state.
// Recovery callers can inspect their journal without racing a writer.
if (onPreflightRejected) return onPreflightRejected(error);
throw error;
}
return work();
});
+26 -2
View File
@@ -67,6 +67,7 @@ async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; cr
const send = vi.fn();
const consumed = vi.fn();
const uncertain = vi.fn();
const sessionReady = vi.fn();
const hubArchivedListeners: Array<() => void> = [];
const session = {
sessionId: 'sid', getMetadata: () => metadata,
@@ -79,7 +80,7 @@ async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; cr
if (event === 'hub-archived') hubArchivedListeners.push(listener);
},
rpcHandlerManager: { registerHandler: (name: string, handler: (raw: unknown) => Promise<unknown>) => rpc.set(name, handler) },
sendSessionEvent() {}, sendAgentMessage: send, emitSessionReady() {},
sendSessionEvent() {}, sendAgentMessage: send, emitSessionReady: sessionReady,
sendUserMessage() {}, emitMessagesConsumed: consumed, emitSteerIndeterminate: uncertain, syncNativeQueuedMessage() {},
sendSessionDeath() {}, async flush() {}, close() {}
} as unknown as ApiSessionClient;
@@ -102,7 +103,7 @@ async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; cr
responses: Array<{ id: string | number; result: unknown }>;
};
return {
root, native, rpc, send, consumed, uncertain, metadata: () => metadata, state: () => state, updateState,
root, native, rpc, send, consumed, uncertain, sessionReady, metadata: () => metadata, state: () => state, updateState,
drain: () => (root as unknown as { notifications: Promise<void> }).notifications,
reconnect: () => reconnect?.(),
emitHubArchived: () => { for (const listener of hubArchivedListeners) listener(); },
@@ -111,6 +112,29 @@ async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; cr
};
}
describe('native readiness after Hub reconnect', () => {
it('replays readiness only after an activated root revalidates native history', async () => {
const f = await fixture()
f.reconnect()
await vi.waitFor(() => expect(f.state().steeringActive).toBe(false))
expect(f.sessionReady).not.toHaveBeenCalled()
await f.root.activate()
expect(f.sessionReady).toHaveBeenCalledTimes(1)
f.reconnect()
await vi.waitFor(() => expect(f.sessionReady).toHaveBeenCalledTimes(2))
})
it('does not replay readiness if native revalidation fails', async () => {
const f = await fixture()
await f.root.activate()
const read = vi.spyOn(f.root.client, 'request').mockRejectedValue(new Error('native unavailable'))
f.reconnect()
await vi.waitFor(() => expect(read).toHaveBeenCalledWith('thread/read', expect.anything()))
await new Promise(resolve => setTimeout(resolve, 10))
expect(f.sessionReady).toHaveBeenCalledTimes(1)
})
})
async function startCompaction(f: Awaited<ReturnType<typeof fixture>>, id = 'input', turnId = 'compacting-turn') {
f.native.queue = [{ id: `native-${id}`, clientUserMessageId: id, input: [{ type: 'text', text: id }] }];
await f.root.refresh();
+6
View File
@@ -138,6 +138,7 @@ export class SharedCodexRoot {
});
this.session.onReconnect(() => {
if (!this.threadId || this.closed || this.stopping) return;
const wasActivated = Boolean(this.heartbeat);
// An emitted socket packet is not a durable hub acknowledgement.
// Replay final native history with stable IDs after every reconnect.
this.projection?.reset();
@@ -145,6 +146,11 @@ export class SharedCodexRoot {
this.publishedPlanId = undefined;
this.publishedCompactionIds = undefined;
void this.refresh().then(() => this.refreshChildren(false)).then(() => this.queue.replay())
.then(() => {
// Hub restart loses its ephemeral readiness fence. Replay
// it only after native revalidation and completed activation.
if (wasActivated && this.heartbeat && !this.closed && !this.stopping && this.client.isInitialized()) this.session.emitSessionReady();
})
.catch(error => logger.debug('[Codex shared] hub resync', error));
});
}