From 5e76af561500e959db63b4166e93bc2ac2baae70 Mon Sep 17 00:00:00 2001 From: Ananovo Date: Wed, 11 Nov 2026 13:04:43 +0800 Subject: [PATCH] feat(codex): fork running sessions through the last completed turn (#2369) --- .github/workflows/test.yml | 2 +- cli/src/codex/shared/root.test.ts | 69 +++++++- cli/src/codex/shared/root.ts | 50 +++++- docs/guide/codex-shared-sessions.md | 15 ++ e2e/session-list-fork-menu.spec.ts | 18 ++ hub/src/sync/forkWhileRunning.test.ts | 29 ++++ hub/src/sync/rpcGateway.ts | 2 +- hub/src/sync/syncEngine.ts | 19 +- hub/src/web/routes/sessions.ts | 3 +- shared/src/apiTypes.ts | 6 +- shared/src/conversationHistory.ts | 1 + shared/src/latestCompletedFork.test.ts | 20 +++ shared/src/schemas.ts | 1 + .../session-list-fork-menu-fixture.tsx | 13 +- web/e2e/codex-fork-while-running.spec.ts | 4 +- web/e2e/codex-list-completed-fork.spec.ts | 164 ++++++++++++++++++ web/playwright.live.config.ts | 1 + web/src/api/client.ts | 4 +- .../SessionList.directory-action.test.tsx | 29 ++++ web/src/components/SessionList.tsx | 11 +- web/src/lib/locales/en.ts | 2 + web/src/lib/locales/ru.ts | 2 + web/src/lib/locales/zh-CN.ts | 2 + 23 files changed, 444 insertions(+), 23 deletions(-) create mode 100644 shared/src/latestCompletedFork.test.ts create mode 100644 web/e2e/codex-list-completed-fork.spec.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 77c1ec92..1aff2656 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,7 @@ jobs: # Required by cli/src/utils/windowsProcessTree.pwsh.test.ts — image # inspect alone does not pull; silent skip was fake B1 coverage (#1911). - run: docker pull mcr.microsoft.com/powershell:latest - - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts scrollbar-auto-hide.spec.ts attachment-removal.spec.ts history-navigation-layout.spec.ts share-turn.spec.ts share-turn-blob-export.spec.ts composer-attachment-controls.spec.ts image-preview-back.spec.ts + - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts session-list-fork-menu.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts scrollbar-auto-hide.spec.ts attachment-removal.spec.ts history-navigation-layout.spec.ts share-turn.spec.ts share-turn-blob-export.spec.ts composer-attachment-controls.spec.ts image-preview-back.spec.ts - run: bun run test # Serial runner-integration suite: starts real detached runner/session diff --git a/cli/src/codex/shared/root.test.ts b/cli/src/codex/shared/root.test.ts index 320f1686..dbc5ee3a 100644 --- a/cli/src/codex/shared/root.test.ts +++ b/cli/src/codex/shared/root.test.ts @@ -1,9 +1,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import type { ApiSessionClient } from '@/api/apiSession'; import type { AgentState, Metadata } from '@/api/types'; import type { SessionBootstrapResult } from '@/agent/sessionFactory'; -import { SharedCodexRoot, type RootHost } from './root'; +import { SharedCodexRoot, latestCompletedForkCutoff, type RootHost } from './root'; import { codexPlanProposalId } from './plan'; import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; import { asyncQuestionsForItem } from './asyncQuestions'; @@ -59,7 +61,7 @@ afterEach(async () => { }); async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; create?: RootHost['create'] }) { - const directory = await mkdtemp('/tmp/hapi-shared-root-'); + const directory = await mkdtemp(join(tmpdir(), 'hapi-shared-root-')); let state: AgentState = { steeringActive: true }; let metadata: Metadata = { path: directory, host: 'test', flavor: 'codex' }; let reconnect: (() => void) | null = null; @@ -636,3 +638,66 @@ describe('shared steering availability', () => { await vi.waitFor(() => expect(end).toHaveBeenCalledTimes(1)); }); }); + +describe('latest completed list fork', () => { + it('uses an inclusive fixed cutoff while later source turns advance', async () => { + const initialSettings = vi.fn(async () => {}); + const create = vi.fn(async (_method, params) => { + expect(params).toMatchObject({ threadId: 'thread', lastTurnId: 'two' }); + expect(params).not.toHaveProperty('beforeTurnId'); + f.native.thread.turns.push({ id: 'later', status: 'inProgress', items: [] }); + return { threadId: 'child', session: { sessionId: 'child-session' }, initialSettings, + readThread: async () => ({ turns: f.native.thread.turns.slice(0, 2) }) } as unknown as SharedCodexRoot; + }); + const f = await fixture({ create }); + f.native.thread.turns = [ + { id: 'one', status: 'completed', items: [{ id: 'u1', type: 'userMessage', clientId: 'first' }] }, + { id: 'two', status: 'completed', items: [{ id: 'u2', type: 'userMessage', clientId: 'second' }] }, + { id: 'three', status: 'inProgress', items: [{ id: 'u3', type: 'userMessage', clientId: 'running' }] } + ]; + await f.root.refresh(); await f.root.activate(); + expect(f.metadata().capabilities?.conversationHistory?.forkLatestCompleted).toBe(true); + const request = vi.spyOn(f.root.client, 'request'); + await expect(f.rpc.get(RPC_METHODS.ForkConversation)!({ latestCompleted: true })).resolves.toEqual({ + nativeSessionId: 'child', sessionId: 'child-session', completedTurnId: 'two' + }); + expect(create).toHaveBeenCalledTimes(1); + expect(f.state().steeringActive).toBe(true); + expect(request.mock.calls.some(([method]) => method === 'turn/interrupt')).toBe(false); + }); + it('refuses empty, unknown and mixed boundary requests before mutation', async () => { + const create = vi.fn(); + const f = await fixture({ create }); await f.root.activate(); + const fork = f.rpc.get(RPC_METHODS.ForkConversation)!; + await expect(fork({ latestCompleted: true })).rejects.toThrow('No completed'); + f.native.thread.turns = [{ id: 'bad', status: 'unknown', items: [] }]; + await expect(fork({ latestCompleted: true })).rejects.toThrow('prefix'); + await expect(fork({ latestCompleted: true, messageLocalId: 'first' })).rejects.toThrow(); + expect(create).not.toHaveBeenCalled(); + }); +}); + +describe('completed native prefix validation', () => { + it('rejects duplicate or unknown native turn identities and states', () => { + expect(() => latestCompletedForkCutoff([{ id: 'one', status: 'completed' }, { id: 'one', status: 'inProgress' }])).toThrow('ambiguous'); + expect(() => latestCompletedForkCutoff([{ id: 'one', status: 'unknown' }, { id: 'two', status: 'completed' }])).toThrow('prefix'); + expect(() => latestCompletedForkCutoff([{ status: 'completed' }])).toThrow('ambiguous'); + }); + it('uses the last completed turn and excludes a failed trailing turn', () => { + expect(latestCompletedForkCutoff([{ id: 'one', status: 'completed' }, { id: 'two', status: 'failed' }, { id: 'three', status: 'inProgress' }])).toBe('one'); + expect(latestCompletedForkCutoff([{ id: 'one', status: 'completed' }, { id: 'two', status: 'completed' }])).toBe('two'); + }); +}); + +it('closes a native child whose inherited prefix does not match the requested cutoff', async () => { + const child = { threadId: 'wrong-child', session: { sessionId: 'wrong-session' }, + readThread: async () => ({ turns: [{ id: 'one' }, { id: 'running' }] }) } as unknown as SharedCodexRoot; + const end = vi.fn(async () => {}); + const create = vi.fn(async () => child); + const f = await fixture({ create, end }); + f.native.thread.turns = [{ id: 'one', status: 'completed', items: [] }, { id: 'running', status: 'inProgress', items: [] }]; + await f.root.refresh(); await f.root.activate(); + await expect(f.rpc.get(RPC_METHODS.ForkConversation)!({ latestCompleted: true })).rejects.toThrow('does not match'); + expect(end).toHaveBeenCalledWith(child); + expect(f.state().steeringActive).toBe(true); +}); diff --git a/cli/src/codex/shared/root.ts b/cli/src/codex/shared/root.ts index b7ad5cc7..a2e9d80d 100644 --- a/cli/src/codex/shared/root.ts +++ b/cli/src/codex/shared/root.ts @@ -97,6 +97,9 @@ export class SharedCodexRoot { } if (method === 'turn/completed' && (!this.currentTurn || record(record(params).turn).id === this.currentTurn)) { this.turnRevision++; this.currentTurn = undefined; this.interrupted = record(record(params).turn).status === 'interrupted'; + if (record(record(params).turn).status === 'completed') this.session.updateMetadata(metadata => ({ ...metadata, + capabilities: { ...metadata.capabilities, conversationHistory: { ...metadata.capabilities?.conversationHistory, + forkLatestCompleted: true } } })); this.publishSteering(); } const p = record(params); @@ -233,7 +236,7 @@ export class SharedCodexRoot { ...metadata.capabilities, concurrentClients: true, terminal: true, // In-place rewind needs a native + hub commit barrier. Do not // advertise a destructive operation we cannot make atomic yet. - conversationHistory: { forkCurrent: true, forkAtMessage: true, rewindToMessage: false } + conversationHistory: { forkCurrent: true, forkAtMessage: true, forkLatestCompleted: false, rewindToMessage: false } } })); this.session.updateAgentState(state => ({ ...state, controlledByUser: false, startingMode: undefined, codexPlanProposalId: null, codexCompactionPendingMessageIds: [], requests: {}, completedRequests: { ...state.completedRequests, ...Object.fromEntries(Object.entries(state.requests ?? {}).map(([id, request]) => @@ -386,6 +389,12 @@ export class SharedCodexRoot { const id = string(last?.id); this.latestTurn = id && last ? { id, status: string(last.status) ?? 'unknown', planId: planProposalForTurn(this.threadId, last) } : undefined; } + const canForkLatest = turns.some(turn => turn.status === 'completed') + || (this.lazyHistory() && this.session.getMetadata()?.capabilities?.conversationHistory?.forkLatestCompleted === true); + if (this.session.getMetadata()?.capabilities?.conversationHistory?.forkLatestCompleted !== canForkLatest) { + this.session.updateMetadata(metadata => ({ ...metadata, capabilities: { ...metadata.capabilities, + conversationHistory: { ...metadata.capabilities?.conversationHistory, forkLatestCompleted: canForkLatest } } })); + } await this.projectHistory(this.projection, thread); await this.queue.reconcile(); this.alive(); } private async refreshChildren(subscribe: boolean): Promise { @@ -582,7 +591,30 @@ export class SharedCodexRoot { const child = await this.newConversation(); return { sessionId: child.session.sessionId }; }); rpc.registerHandler(RPC_METHODS.ForkConversation, async raw => { - const { messageLocalId } = z.object({ messageLocalId: z.string().optional() }).parse(raw); + const { messageLocalId, latestCompleted } = z.object({ messageLocalId: z.string().optional(), latestCompleted: z.boolean().optional() }) + .refine(value => !(value.messageLocalId && value.latestCompleted)).parse(raw); + if (latestCompleted) { + const thread = await this.readThread(this.threadId, true); + const turns = (Array.isArray(thread.turns) ? thread.turns : []).map(record); + const cutoff = latestCompletedForkCutoff(turns); + // An explicit inclusive native cutoff remains fixed even if the source advances. + // Shared children hydrate directly from native fork history, never a moving Hub tail. + const child = await this.host.create('thread/fork', { ...this.freshParams(), threadId: this.threadId, + lastTurnId: cutoff }, this); + try { + const expected = turns.slice(0, turns.findIndex(turn => turn.id === cutoff) + 1).map(turn => string(turn.id)); + const inherited = await child.readThread(child.threadId, true); + const actual = (Array.isArray(inherited.turns) ? inherited.turns : []).map(value => string(record(value).id)); + if (actual.length !== expected.length || actual.some((id, index) => id !== expected[index])) { + throw new Error('Native fork history does not match the completed-turn cutoff'); + } + await child.initialSettings({ collaborationMode: this.settings.collaborationMode }); + return { nativeSessionId: child.threadId, sessionId: child.session.sessionId, completedTurnId: cutoff }; + } catch (error) { + await this.host.end(child).catch(cleanup => logger.debug('[Codex shared] invalid fork cleanup failed', cleanup)); + throw error; + } + } if (this.currentTurn && !messageLocalId) throw new Error('Session is busy'); const beforeTurnId = messageLocalId ? this.projection.turnFor(messageLocalId) : undefined; if (messageLocalId && !beforeTurnId) throw new Error('No native history point for this message'); @@ -683,3 +715,17 @@ export class SharedCodexRoot { })(); } } + +/** Resolve an inclusive immutable prefix from authoritative native history. */ +export function latestCompletedForkCutoff(turns: Record[]): string { + const ids = turns.map(turn => string(turn.id)); + if (ids.some(id => !id) || new Set(ids).size !== ids.length) throw new Error('Native turn history is ambiguous'); + let completed: string | undefined; + for (const turn of turns) { + if (turn.status === 'inProgress' || turn.status === 'in_progress') break; + if (!['completed', 'interrupted', 'failed'].includes(string(turn.status) ?? '')) throw new Error('Native history prefix is not complete'); + if (turn.status === 'completed') completed = string(turn.id); + } + if (!completed) throw new Error('No completed turn is available to fork'); + return completed; +} diff --git a/docs/guide/codex-shared-sessions.md b/docs/guide/codex-shared-sessions.md index 84c27d25..c70934a7 100644 --- a/docs/guide/codex-shared-sessions.md +++ b/docs/guide/codex-shared-sessions.md @@ -199,3 +199,18 @@ not a fake Codex executable. Coverage includes keyboard/Web answers, sibling question isolation, native queue editing/deletion, fork, primary-terminal exit, secondary attachment/detachment, Web→Runner resume with the same HAPI/native identity, and safe pending-message recovery. + +### Fork the latest completed turn from the session list + +For an updated Shared Codex runtime, **Fork session** remains available while a +turn is running if a completed turn is known. The confirmation explains that the +unfinished turn is excluded and the source continues running. A first running +turn without completed history is disabled; older runtimes retain the busy guard. + +The Hub requests an explicit latest-completed boundary. The Runner reads native +history and forks inclusively through the selected completed turn with +`lastTurnId`. That cutoff is fixed before the native mutation, so later source +progress cannot widen the child. Shared children hydrate from the native fork; +the Hub does not copy the source's changing message tail. Unsupported or +unverified boundaries are rejected rather than falling back to a current fork. +Manual **Fork at message** keeps its existing exclusive boundary semantics. diff --git a/e2e/session-list-fork-menu.spec.ts b/e2e/session-list-fork-menu.spec.ts index 61085c99..91a5b2a2 100644 --- a/e2e/session-list-fork-menu.spec.ts +++ b/e2e/session-list-fork-menu.spec.ts @@ -59,3 +59,21 @@ test('forks an archived Codex session directly from the mobile list menu', async await expect(page.getByTestId('selected-session')).toHaveText('fork-child') await expect(page.locator('body')).toHaveAttribute('data-fork-source', 'archived-source') }) + +test('forks the latest completed prefix from a running list row and disables an empty first turn', async ({ page }) => { + await page.setViewportSize({ width: 393, height: 844 }) + await page.goto('/e2e-fixtures/session-list-fork-menu-fixture.html?lang=zh-CN') + await page.getByRole('button', { name: /运行中已有历史/ }).click({ button: 'right' }) + const action = page.getByRole('menuitem', { name: '分叉会话', exact: true }) + await expect(action).not.toHaveAttribute('aria-disabled', 'true') + const runtime = process.env.HAPI_TASK_RUNTIME + if (runtime) { await mkdir(join(runtime, 'screenshots'), { recursive: true }); await page.screenshot({ path: join(runtime, 'screenshots', 'running-fork-menu.png') }) } + await action.click() + await expect(page.getByRole('dialog')).toContainText('最后一个已完成轮次') + if (runtime) await page.screenshot({ path: join(runtime, 'screenshots', 'running-fork-confirm.png') }) + await page.getByRole('dialog').getByRole('button', { name: '确定', exact: true }).click() + await expect(page.locator('body')).toHaveAttribute('data-latest-completed', 'true') + await page.getByRole('button', { name: /首轮运行中/ }).click({ button: 'right' }) + await expect(page.getByRole('menuitem', { name: '分叉会话', exact: true })).toHaveAttribute('aria-disabled', 'true') + await expect(page.getByText('暂无已完成轮次可分叉。', { exact: true })).toBeAttached() +}) diff --git a/hub/src/sync/forkWhileRunning.test.ts b/hub/src/sync/forkWhileRunning.test.ts index f87e3fc7..83acbc02 100644 --- a/hub/src/sync/forkWhileRunning.test.ts +++ b/hub/src/sync/forkWhileRunning.test.ts @@ -96,3 +96,32 @@ describe('historical forks while the source runs', () => { } finally { engine.stop() } }) }) + +describe('latest completed mode admission', () => { + it('fails closed for old Runner capabilities and non-Codex sessions', async () => { + const { engine, source, rpc } = fixture(); + try { + let calls = 0; + rpc.forkConversation = async () => { calls++; return { nativeSessionId: 'unused' }; }; + expect(await engine.forkConversation(source.id, 'default', undefined, true)).toMatchObject({ type: 'error' }); + expect(calls).toBe(0); + } finally { engine.stop(); } + }); + it('requires a verified shared child rather than copying a moving source tail', async () => { + const { engine, store, source, rpc } = fixture(); + try { + const current = store.sessions.getSession(source.id)!; + store.sessions.updateSessionMetadata(source.id, { ...current.metadata as object, + capabilities: { conversationHistory: { forkCurrent: true, forkLatestCompleted: true } } }, current.metadataVersion, 'default'); + (engine as any).sessionCache.refreshSession(source.id); + rpc.forkConversation = async (_id, payload) => { + expect(payload).toEqual({ latestCompleted: true }); + return { nativeSessionId: 'unverified' }; + }; + expect(await engine.forkConversation(source.id, 'default', undefined, true)).toEqual({ + type: 'error', message: 'Runner did not verify the completed-turn fork boundary' + }); + expect(engine.getSession(source.id)?.thinking).toBe(true); + } finally { engine.stop(); } + }); +}); diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index dc2d8513..5d1fd9d4 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -644,7 +644,7 @@ export class RpcGateway { async forkConversation( sessionId: string, - params: { messageLocalId?: string } + params: { messageLocalId?: string; latestCompleted?: boolean } ): Promise { return await this.sessionRpc( sessionId, diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 16d3970a..e0f71f08 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -2283,7 +2283,8 @@ export class SyncEngine { async forkConversation( sessionId: string, namespace: string, - messageLocalId?: string + messageLocalId?: string, + latestCompleted = false ): Promise<{ type: 'success'; sessionId: string } | { type: 'error'; message: string }> { const candidate = this.sessionCache.getSessionByNamespace(sessionId, namespace) if (candidate?.metadata?.codexResumePending) { @@ -2297,7 +2298,7 @@ export class SyncEngine { } this.historyActionsInFlight.add(sessionId) try { - return await this.forkConversationUnlocked(sessionId, namespace, messageLocalId) + return await this.forkConversationUnlocked(sessionId, namespace, messageLocalId, latestCompleted) } finally { this.historyActionsInFlight.delete(sessionId) } @@ -2306,16 +2307,21 @@ export class SyncEngine { private async forkConversationUnlocked( sessionId: string, namespace: string, - messageLocalId?: string + messageLocalId?: string, + latestCompleted = false ): Promise<{ type: 'success'; sessionId: string } | { type: 'error'; message: string }> { const access = this.resolveSessionAccess(sessionId, namespace) if (!access.ok) { return { type: 'error', message: access.reason === 'not-found' ? 'Session not found' : 'Access denied' } } let source = access.session + if (latestCompleted && (messageLocalId || !source.active || this.resolveFlavor(source) !== 'codex' + || source.metadata?.capabilities?.conversationHistory?.forkLatestCompleted !== true)) { + return { type: 'error', message: 'No verified completed turn is available for this session' } + } if (!source.active) return this.forkArchivedCodexSession(source, namespace, messageLocalId) try { - this.assertConversationHistoryIdle(source, Boolean(messageLocalId) && this.resolveFlavor(source) === 'codex') + this.assertConversationHistoryIdle(source, (Boolean(messageLocalId) || latestCompleted) && this.resolveFlavor(source) === 'codex') } catch (error) { return { type: 'error', message: error instanceof Error ? error.message : String(error) } } @@ -2344,7 +2350,7 @@ export class SyncEngine { try { rpcResult = await this.rpcGateway.forkConversation( sessionId, - messageLocalId ? { messageLocalId } : {} + latestCompleted ? { latestCompleted: true } : messageLocalId ? { messageLocalId } : {} ) } catch (error) { return { type: 'error', message: error instanceof Error ? error.message : String(error) } @@ -2368,6 +2374,9 @@ export class SyncEngine { ) { return { type: 'error', message: 'Native fork did not return a session id' } } + if (latestCompleted && (!rpcResult.sessionId || !rpcResult.completedTurnId)) { + return { type: 'error', message: 'Runner did not verify the completed-turn fork boundary' } + } if (rpcResult.sessionId) { const child = await this.validateSharedChild(source, rpcResult.sessionId, rpcResult.nativeSessionId) if (!child || child.metadata?.forkedFrom !== sessionId) return { type: 'error', message: 'Invalid shared-runtime fork binding' } diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index cf81e51c..cf7ef6c5 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -601,7 +601,8 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho const result = await engine.forkConversation( sessionResult.sessionId, c.get('namespace'), - parsed.data.messageLocalId + parsed.data.messageLocalId, + parsed.data.latestCompleted ) if (result.type === 'error') { return c.json({ error: result.message }, 409) diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index a2d76844..b82c12cd 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -659,8 +659,9 @@ export const SendMessageRequestSchema = z.object({ export type SendMessageRequest = z.infer export const ForkConversationRequestSchema = z.object({ - messageLocalId: z.string().min(1).optional() -}) + messageLocalId: z.string().min(1).optional(), + latestCompleted: z.boolean().optional() +}).refine(value => !(value.messageLocalId && value.latestCompleted), { message: 'Choose one fork boundary mode' }) export type ForkConversationRequest = z.infer @@ -692,6 +693,7 @@ export type RewindConversationResponse = { /** CLI → hub RPC result for native fork (before HAPI child binding). */ export type ForkConversationRpcResult = { + completedTurnId?: string nativeSessionId: string /** Shared runtimes bind the child themselves; hub must not spawn another engine. */ sessionId?: string diff --git a/shared/src/conversationHistory.ts b/shared/src/conversationHistory.ts index f6aedffa..60d31b76 100644 --- a/shared/src/conversationHistory.ts +++ b/shared/src/conversationHistory.ts @@ -8,6 +8,7 @@ export type ConversationHistoryCapabilityStates = { export type ConversationHistoryCapabilities = { forkCurrent?: boolean + forkLatestCompleted?: boolean forkAtMessage?: boolean rewindToMessage?: boolean } diff --git a/shared/src/latestCompletedFork.test.ts b/shared/src/latestCompletedFork.test.ts new file mode 100644 index 00000000..3cfde42b --- /dev/null +++ b/shared/src/latestCompletedFork.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'bun:test' +import { ForkConversationRequestSchema } from './apiTypes' +import { MetadataSchema } from './schemas' +import { toSessionSummaryMetadata } from './sessionSummary' + +describe('latest completed fork wire contract', () => { + it('rejects mixed boundary modes while preserving existing requests', () => { + expect(ForkConversationRequestSchema.parse({ latestCompleted: true })).toEqual({ latestCompleted: true }) + expect(ForkConversationRequestSchema.safeParse({ latestCompleted: true, messageLocalId: 'user' }).success).toBe(false) + expect(ForkConversationRequestSchema.parse({ messageLocalId: 'user' })).toEqual({ messageLocalId: 'user' }) + expect(ForkConversationRequestSchema.parse({})).toEqual({}) + }) + it('preserves supported and no-completed-history states in list summaries', () => { + for (const available of [false, true]) { + const metadata = MetadataSchema.parse({ path: '/work', host: 'test', flavor: 'codex', + capabilities: { conversationHistory: { forkCurrent: true, forkLatestCompleted: available } } }) + expect(toSessionSummaryMetadata(metadata)?.conversationHistory?.forkLatestCompleted).toBe(available) + } + }) +}) diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index f468386d..04bfe17e 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -21,6 +21,7 @@ const MetadataSummarySchema = z.object({ const ConversationHistoryCapabilitiesSchema = z.object({ forkCurrent: z.boolean().optional(), + forkLatestCompleted: z.boolean().optional(), forkAtMessage: z.boolean().optional(), rewindToMessage: z.boolean().optional() }) diff --git a/web/e2e-fixtures/session-list-fork-menu-fixture.tsx b/web/e2e-fixtures/session-list-fork-menu-fixture.tsx index 6225c15b..3b5c61d7 100644 --- a/web/e2e-fixtures/session-list-fork-menu-fixture.tsx +++ b/web/e2e-fixtures/session-list-fork-menu-fixture.tsx @@ -53,6 +53,16 @@ const initialSessions: SessionSummary[] = [ conversationHistory: { forkCurrent: true }, }, }, + { + ...base, id: 'running-completed-source', thinking: true, + metadata: { path: '/work/completed', name: '运行中已有历史', flavor: 'codex', + conversationHistory: { forkCurrent: true, forkLatestCompleted: true } }, + }, + { + ...base, id: 'running-empty-source', thinking: true, + metadata: { path: '/work/empty', name: '首轮运行中', flavor: 'codex', + conversationHistory: { forkCurrent: true, forkLatestCompleted: false } }, + }, { ...base, id: 'archived-source', @@ -72,7 +82,8 @@ const initialSessions: SessionSummary[] = [ function Fixture() { const [selected, setSelected] = useState(null) const api = { - forkConversation: async (sessionId: string) => { + forkConversation: async (sessionId: string, _message?: string, latestCompleted?: boolean) => { + document.body.dataset.latestCompleted = String(latestCompleted) document.body.dataset.forkSource = sessionId return { sessionId: 'fork-child' } }, diff --git a/web/e2e/codex-fork-while-running.spec.ts b/web/e2e/codex-fork-while-running.spec.ts index e5993b6c..82f63d7d 100644 --- a/web/e2e/codex-fork-while-running.spec.ts +++ b/web/e2e/codex-fork-while-running.spec.ts @@ -118,8 +118,8 @@ for (const mobile of [false, true]) { expect(childHistory).toContain(retained) expect(childHistory).not.toContain(excluded) expect(childHistory).not.toContain(running) - await expect(page.getByText(retained, { exact: true })).toBeVisible() - await expect(page.getByText(excluded, { exact: true })).toHaveCount(0) + await expect(page.locator('[data-hapi-message-role="user"]').getByText(retained, { exact: true })).toBeVisible() + await expect(page.locator('[data-hapi-message-role="user"]').getByText(excluded, { exact: true })).toHaveCount(0) await api(`/sessions/${child}/messages`, { text: childProbe, localId: childProbe }) await expect.poll(() => messages(child), { timeout: 30_000 }).toContain('CHILD_CONTEXT_OK') const childInput = modelInputs.find(input => input.includes(childProbe))! diff --git a/web/e2e/codex-list-completed-fork.spec.ts b/web/e2e/codex-list-completed-fork.spec.ts new file mode 100644 index 00000000..45667984 --- /dev/null +++ b/web/e2e/codex-list-completed-fork.spec.ts @@ -0,0 +1,164 @@ +import { expect, test } from '@playwright/test' +import { createServer, type ServerResponse } from 'node:http' +import { mkdir, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { randomUUID } from 'node:crypto' +import { getHapiBaseUrl, installHapiAuth } from './helpers/hapi-live' + +// The task Runner must inherit CODEX_HOME=/codex-home. +// Uses the installed Codex binary and a deterministic local Responses server, +// with a real isolated Hub, Runner, machine and browser. Never use production. +test.use({ serviceWorkers: 'block' }) + +const enabled = process.env.HAPI_LIVE === '1' && process.env.HAPI_FORK_LIVE === '1' + && Boolean(process.env.HAPI_FORK_TEST_DIR) && Boolean(process.env.HAPI_ACCESS_TOKEN) + +for (const mobile of [false, true]) { + test(`latest completed list fork preserves a running source (${mobile ? 'mobile' : 'desktop'})`, async ({ page, request }, testInfo) => { + test.skip(!enabled, 'Requires an isolated Full environment and explicit HAPI_FORK_LIVE opt-in') + test.setTimeout(300_000) + const base = process.env.HAPI_FORK_LOCAL_URL ?? getHapiBaseUrl() + const directory = process.env.HAPI_FORK_TEST_DIR! + const accessToken = process.env.HAPI_ACCESS_TOKEN! + const auth = await request.post(`${base}/api/auth`, { data: { accessToken } }) + expect(auth.ok()).toBe(true) + const headers = { Authorization: `Bearer ${(await auth.json()).token}` } + const api = async (path: string, data?: unknown) => { + const response = data === undefined + ? await request.get(`${base}/api${path}`, { headers }) + : await request.post(`${base}/api${path}`, { headers, data, timeout: 60_000 }) + expect(response.ok(), `${path}: ${await response.text()}`).toBe(true) + return response.json() + } + const run = randomUUID() + const retained = `RETAINED_${run}` + const secondCompleted = `COMPLETED_SECOND_${run}` + const running = `RUNNING_${run}` + const childProbe = `CHILD_PROBE_${run}` + let held: { response: ServerResponse; id: string } | undefined + const modelInputs: string[] = [] + const event = (response: ServerResponse, body: { type: string; [key: string]: unknown }) => + response.write(`event: ${body.type}\ndata: ${JSON.stringify(body)}\n\n`) + const finish = (response: ServerResponse, id: string, text: string) => { + event(response, { type: 'response.output_item.done', item: { type: 'message', role: 'assistant', + id: `msg_${id}`, content: [{ type: 'output_text', text }] } }) + event(response, { type: 'response.completed', response: { id, + usage: { input_tokens: 12, output_tokens: 3, total_tokens: 15 } } }) + response.end() + } + const provider = createServer((incoming, response) => { + const chunks: Buffer[] = [] + incoming.on('data', chunk => chunks.push(Buffer.from(chunk))) + incoming.on('end', () => { + if (!incoming.url?.endsWith('/responses')) { response.writeHead(404).end(); return } + const input = Buffer.concat(chunks).toString() + modelInputs.push(input) + const id = randomUUID() + response.writeHead(200, { 'Content-Type': 'text/event-stream' }) + event(response, { type: 'response.created', response: { id } }) + if (input.includes(childProbe)) finish(response, id, 'CHILD_CONTEXT_OK') + else if (input.includes(running)) held = { response, id } + else finish(response, id, input.includes(secondCompleted) ? 'SECOND_DONE' : 'FIRST_DONE') + }) + }) + const sessions: string[] = [] + try { + await new Promise(resolve => provider.listen(0, '127.0.0.1', resolve)) + const port = (provider.address() as { port: number }).port + const home = join(directory, 'codex-home') + await mkdir(home, { recursive: true }) + const cwd = join(directory, `work-${run}`) + await mkdir(cwd, { recursive: true }) + await writeFile(join(home, 'config.toml'), `model = "mock-model"\nmodel_provider = "mock_provider"\napproval_policy = "never"\nsandbox_mode = "read-only"\ncheck_for_update_on_startup = false\n[model_providers.mock_provider]\nname = "Isolated fork test"\nbase_url = "http://127.0.0.1:${port}/v1"\nwire_api = "responses"\nrequires_openai_auth = false\nsupports_websockets = false\nrequest_max_retries = 0\nstream_max_retries = 0\n[analytics]\nenabled = false\n[feedback]\nenabled = false\n`) + const { machines } = await api('/machines') + expect(machines).toHaveLength(1) + const spawn = await api(`/machines/${machines[0].id}/spawn`, { + directory: cwd, agent: 'codex', model: 'mock-model', permissionMode: 'read-only' + }) + let source = spawn.type === 'success' ? spawn.sessionId as string : undefined + if (!source) await expect.poll(async () => { + const list = await api('/sessions') + source = list.sessions.find((session: { active: boolean; metadata?: { path?: string } }) => + session.active && session.metadata?.path === cwd)?.id + return Boolean(source) + }, { timeout: 90_000 }).toBe(true) + if (!source) throw new Error('Source did not become ready') + sessions.push(source) + const detail = async (id: string) => (await api(`/sessions/${id}`)).session + const messages = async (id: string) => JSON.stringify(await api(`/sessions/${id}/messages?limit=200`)) + await expect.poll(async () => (await detail(source)).metadata?.capabilities?.conversationHistory?.forkAtMessage, + { timeout: 90_000 }).toBe(true) + for (const [text, result] of [[retained, 'FIRST_DONE'], [secondCompleted, 'SECOND_DONE']]) { + await api(`/sessions/${source}/messages`, { text, localId: text }) + await expect.poll(() => messages(source), { timeout: 30_000 }).toContain(result) + await expect.poll(async () => (await detail(source)).thinking).toBe(false) + } + await api(`/sessions/${source}/messages`, { text: running, localId: running }) + await expect.poll(() => Boolean(held), { timeout: 90_000 }).toBe(true) + await expect.poll(async () => (await detail(source)).thinking).toBe(true) + // Both API and UI must retain the busy guard for current forks. + const current = await request.post(`${base}/api/sessions/${source}/fork`, { headers, data: {} }) + expect(current.status()).toBe(409) + expect(await current.json()).toMatchObject({ error: 'Session is busy' }) + const activeBoundary = await request.post(`${base}/api/sessions/${source}/fork`, { + headers, data: { messageLocalId: running } + }) + expect(activeBoundary.status()).toBe(409) + await installHapiAuth(page, base, accessToken) + await page.setViewportSize(mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }) + await page.goto(`${base}/sessions/${source}`) + expect((await request.patch(`${base}/api/sessions/${source}`, { headers, data: { name: `Completed fork ${run}` } })).ok()).toBe(true) + await page.goto(`${base}/sessions`) + await page.getByRole('button', { name: new RegExp(`Completed fork ${run}`) }).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Fork session', exact: true }).click() + await expect(page.getByRole('dialog')).toContainText('last completed turn') + await mkdir(join(directory, 'screenshots'), { recursive: true }) + await page.screenshot({ path: join(directory, 'screenshots', `real-running-confirm-${mobile}.png`) }) + const forkResponse = page.waitForResponse(response => response.url().endsWith(`/sessions/${source}/fork`) && response.request().method() === 'POST') + const requestsBeforeFork = modelInputs.length + await page.getByRole('dialog').getByRole('button', { name: 'Confirm', exact: true }).click() + const response = await forkResponse + expect(response.ok(), await response.text()).toBe(true) + expect(modelInputs).toHaveLength(requestsBeforeFork) + const child = (await response.json()).sessionId as string + sessions.push(child) + await expect(page).toHaveURL(new RegExp(`/sessions/${child}$`)) + expect((await detail(source)).thinking).toBe(true) + expect(held?.response.writableEnded).toBe(false) + const childHistory = await messages(child) + expect(childHistory).toContain(retained) + expect(childHistory).toContain(secondCompleted) + expect(childHistory).not.toContain(running) + await expect(page.locator('[data-hapi-message-role="user"]').getByText(retained, { exact: true })).toBeVisible() + await expect(page.locator('[data-hapi-message-role="user"]').getByText(secondCompleted, { exact: true })).toBeVisible() + for (const button of await page.getByRole('button', { name: 'Got it', exact: true }).all()) { + if (await button.isVisible()) await button.click() + } + await page.screenshot({ path: join(directory, 'screenshots', `real-child-history-${mobile}.png`) }) + await api(`/sessions/${child}/messages`, { text: childProbe, localId: childProbe }) + await expect.poll(() => messages(child), { timeout: 30_000 }).toContain('CHILD_CONTEXT_OK') + const childInput = modelInputs.find(input => input.includes(childProbe))! + expect(childInput).toContain(retained) + expect(childInput).toContain(secondCompleted) + expect(childInput).not.toContain(running) + // The first historical boundary produces an empty native prefix. + const emptyFork = await api(`/sessions/${source}/fork`, { messageLocalId: retained }) + sessions.push(emptyFork.sessionId) + const emptyHistory = await messages(emptyFork.sessionId) + expect(emptyHistory).not.toContain(retained) + expect(emptyHistory).not.toContain(secondCompleted) + expect((await detail(source)).thinking).toBe(true) + finish(held!.response, held!.id, 'SOURCE_COMPLETED_AFTER_FORK') + await expect.poll(() => messages(source), { timeout: 30_000 }).toContain('SOURCE_COMPLETED_AFTER_FORK') + await expect.poll(async () => (await detail(source)).thinking).toBe(false) + expect(await messages(child)).not.toContain('SOURCE_COMPLETED_AFTER_FORK') + await testInfo.attach('native-fork-context', { body: JSON.stringify({ source, child, modelRequests: modelInputs.length, + inheritedRetained: childInput.includes(retained), inheritedSecondCompleted: childInput.includes(secondCompleted), inheritedRunning: childInput.includes(running) }), contentType: 'application/json' }) + } finally { + if (held && !held.response.writableEnded) held.response.end() + for (const id of sessions.reverse()) await api(`/sessions/${id}/archive`, {}).catch(() => {}) + provider.closeAllConnections() + await new Promise(resolve => provider.close(() => resolve())) + } + }) +} diff --git a/web/playwright.live.config.ts b/web/playwright.live.config.ts index cebd0759..20876e78 100644 --- a/web/playwright.live.config.ts +++ b/web/playwright.live.config.ts @@ -9,6 +9,7 @@ export default defineConfig({ 'mermaid-lightbox-session.spec.ts', 'latex-bracket-math-session.spec.ts', 'codex-fork-while-running.spec.ts', + 'codex-list-completed-fork.spec.ts', 'codex-archived-fork.spec.ts', 'codex-session-list-fork.spec.ts', 'late-codex-command-session.spec.ts', diff --git a/web/src/api/client.ts b/web/src/api/client.ts index ba682040..807ae31d 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -758,12 +758,12 @@ export class ApiClient { }) } - async forkConversation(sessionId: string, messageLocalId?: string): Promise<{ sessionId: string }> { + async forkConversation(sessionId: string, messageLocalId?: string, latestCompleted = false): Promise<{ sessionId: string }> { return await this.request<{ sessionId: string }>( `/api/sessions/${encodeURIComponent(sessionId)}/fork`, { method: 'POST', - body: JSON.stringify(messageLocalId ? { messageLocalId } : {}) + body: JSON.stringify(latestCompleted ? { latestCompleted: true } : messageLocalId ? { messageLocalId } : {}) } ) } diff --git a/web/src/components/SessionList.directory-action.test.tsx b/web/src/components/SessionList.directory-action.test.tsx index 94414b32..63006c23 100644 --- a/web/src/components/SessionList.directory-action.test.tsx +++ b/web/src/components/SessionList.directory-action.test.tsx @@ -334,6 +334,35 @@ describe('SessionList fork session action', () => { expect(onSelect).toHaveBeenCalledWith('child-session') }) + it('forks a running capable session through the latest completed native turn', async () => { + const forkConversation = vi.fn(async () => ({ sessionId: 'child-session' })) + const onSelect = vi.fn() + const session = makeSession({ + id: 'source-session', + active: true, + thinking: true, + updatedAt: Date.now(), + metadata: { + path: '/work/source', + name: 'Source session', + flavor: 'codex', + conversationHistory: { forkCurrent: true, forkAtMessage: true, forkLatestCompleted: true }, + }, + }) + renderWithProviders() + + fireEvent.contextMenu(screen.getByRole('button', { name: /Source session/ })) + fireEvent.click(screen.getByRole('menuitem', { name: 'Fork session' })) + const dialog = screen.getByRole('dialog') + expect(within(dialog).getByRole('heading', { name: 'Fork session' })).toBeInTheDocument() + fireEvent.click(within(dialog).getByRole('button', { name: 'Confirm' })) + + await waitFor(() => expect(forkConversation).toHaveBeenCalledWith('source-session', undefined, true)) + expect(onSelect).toHaveBeenCalledWith('child-session') + }) + it('keeps Fork session disabled while the source turn is running', () => { const session = makeSession({ id: 'running-source', diff --git a/web/src/components/SessionList.tsx b/web/src/components/SessionList.tsx index b7c1ff76..d68582bf 100644 --- a/web/src/components/SessionList.tsx +++ b/web/src/components/SessionList.tsx @@ -1218,7 +1218,8 @@ const SessionItem = memo(function SessionItem(props: { const supportsArchivedFork = !s.active && s.metadata?.flavor === 'codex' && s.metadata?.lifecycleState === 'archived' && Boolean(s.metadata.agentSessionId && s.metadata.machineId) - const forkDisabledReason = supportsCurrentFork && s.thinking ? t('session.action.forkRunning') : undefined + const supportsCompletedFork = s.metadata?.conversationHistory?.forkLatestCompleted === true + const forkDisabledReason = supportsCurrentFork && s.thinking && !supportsCompletedFork ? t(s.metadata?.conversationHistory?.forkLatestCompleted === false ? 'session.action.forkNoCompleted' : 'session.action.forkRunning') : undefined const longPressHandlers = useLongPress({ onLongPress: (point) => { @@ -1310,7 +1311,7 @@ const SessionItem = memo(function SessionItem(props: { onRename={() => setRenameOpen(true)} onExport={() => setExportOpen(true)} onMarkUnread={() => markSessionUnread(s.id, s.readState)} - onForkSession={api && ((supportsCurrentFork && !s.thinking) || supportsArchivedFork) + onForkSession={api && ((supportsCurrentFork && (!s.thinking || supportsCompletedFork)) || supportsArchivedFork) ? () => setForkOpen(true) : undefined} forkDisabledReason={forkDisabledReason} @@ -1327,7 +1328,7 @@ const SessionItem = memo(function SessionItem(props: { isOpen={true} onClose={() => { if (!forkPending) setForkOpen(false) }} title={t('dialog.sessionFork.title')} - description={t('dialog.sessionFork.description')} + description={t(s.thinking && supportsCompletedFork ? 'dialog.sessionFork.completedDescription' : 'dialog.sessionFork.description')} confirmLabel={t('dialog.sessionFork.confirm')} confirmingLabel={t('dialog.sessionFork.confirming')} isPending={forkPending} @@ -1337,7 +1338,9 @@ const SessionItem = memo(function SessionItem(props: { if (!api) return setForkPending(true) try { - const result = await api.forkConversation(s.id) + const result = s.thinking && supportsCompletedFork + ? await api.forkConversation(s.id, undefined, true) + : await api.forkConversation(s.id) onSelect(result.sessionId) } finally { setForkPending(false) diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index 47ae10d3..6235968b 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -334,6 +334,8 @@ export default { 'session.action.copy': 'Copy', 'session.action.copyReference': 'Copy reference', 'session.action.fork': 'Fork session', + 'session.action.forkNoCompleted': 'No completed turn is available to fork.', + 'dialog.sessionFork.completedDescription': 'Fork through the last completed turn. The running turn is excluded and the source keeps running.', 'session.action.forkRunning': 'Wait for the current turn to finish before forking this session.', // Dialogs diff --git a/web/src/lib/locales/ru.ts b/web/src/lib/locales/ru.ts index 06c4548b..e3dfa7bc 100644 --- a/web/src/lib/locales/ru.ts +++ b/web/src/lib/locales/ru.ts @@ -295,6 +295,8 @@ export default { 'session.action.copy': 'Копировать', 'session.action.copyReference': 'Копировать ссылку', 'session.action.fork': 'Форк сессии', + 'session.action.forkNoCompleted': 'Нет завершённых ходов для создания ветки.', + 'dialog.sessionFork.completedDescription': 'Создать ветку до последнего завершённого хода. Текущий ход исключён; исходная сессия продолжит работу.', 'session.action.forkRunning': 'Дождитесь завершения текущего хода, прежде чем создавать форк.', // Диалоги diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 3e123647..c7896973 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -334,6 +334,8 @@ export default { 'session.action.copy': '复制', 'session.action.copyReference': '复制引用', 'session.action.fork': '分叉会话', + 'session.action.forkNoCompleted': '暂无已完成轮次可分叉。', + 'dialog.sessionFork.completedDescription': '分叉到最后一个已完成轮次,不包含正在进行的轮次,原会话继续运行。', 'session.action.forkRunning': '当前轮次完成后才能分叉此会话。', // Dialogs