Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 优化 Codex 会话 fork (#3864)
DavidShenXD8289af33b094
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.tsindex e4b5394402..453cdb6146 100644--- a/apps/desktop/src/main/__tests__/fork.test.ts+++ b/apps/desktop/src/main/__tests__/fork.test.ts@@ -33,6 +33,11 @@ vi.mock('../maker-host/index.js', () => ({}),}));+const inferProviderIdForModelMock = vi.fn();+vi.mock('../maker-host/provider-route.js', () => ({+ inferProviderIdForModel: inferProviderIdForModelMock,+}));+// fake drizzle: select 链返回 thenable。写入侧 MR2.2 后走 DbClient.tx。// 每个 select() 调用按入栈顺序消费 selectQueue 的下一个返回值。type SelectStep = unknown[];@@ -102,6 +107,8 @@ beforeEach(async () => {commitContextRebuildMock.mockClear();createMessageMock.mockClear();forkSdkSessionMock.mockReset();+ inferProviderIdForModelMock.mockReset();+ inferProviderIdForModelMock.mockReturnValue(null);// 默认空 uuidMap 让 agentMeta 字段被去掉 (无映射)。具体测试按需 override。forkSdkSessionMock.mockResolvedValue({newSdkSessionId: 'sdk-new-session-uuid',@@ -355,6 +362,210 @@ describe('forkSessionAtMessage', () => {expect(result.parentSessionId).toBe('src-session');});+ it('codex path: uses the latest native turn anchor across mixed old and new history', async () => {+ const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });+ const legacyUser = makeMessageRow({+ id: 'legacy-user',+ role: 'user',+ agentKind: 'codex',+ createdAt: 1000,+ });+ const legacyAssistant = makeMessageRow({+ id: 'legacy-assistant',+ role: 'assistant',+ agentKind: 'codex',+ agentMeta: JSON.stringify({ turnCompleted: true }),+ createdAt: 1500,+ });+ const priorUser = makeMessageRow({+ id: 'user-1',+ role: 'user',+ content: '"hi"',+ agentKind: 'codex',+ createdAt: 2000,+ });+ const priorAssistant = makeMessageRow({+ id: 'asst-1',+ role: 'assistant',+ content: '"hi back"',+ agentKind: 'codex',+ agentMeta: JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-source',+ kind: 'turn',+ id: 'turn-at-boundary',+ },+ }),+ createdAt: 2500,+ });++ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'gpt-5.4',+ sdkSessionId: 'codex-thread-source',+ }),+ ]);+ selectQueue.push([target]);+ selectQueue.push([legacyUser, legacyAssistant, priorUser, priorAssistant]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-child',+ parentSessionId: 'src-session',+ }),+ ]);+ queryMock.mockResolvedValue([+ { role: 'user', content: '"later"' },+ { role: 'user', content: '"target"' },+ ]);+ forkSdkSessionMock.mockResolvedValue({+ newSdkSessionId: 'codex-thread-child',+ uuidMap: new Map<string, string>(),+ usedNativeForkAnchor: true,+ });++ await forkSessionAtMessage('src-session', 'target-user');++ expect(forkSdkSessionMock).toHaveBeenCalledWith('codex', {+ sourceSdkSessionId: 'codex-thread-source',+ model: 'gpt-5.4',+ providerId: 'xd',+ upToMessageId: undefined,+ lastTurnId: 'turn-at-boundary',+ tailTurnsToDrop: 2,+ title: '[Fork] Project A',+ workingDir: '/work',+ remoteHostId: null,+ });+ const txArgs = txCalls.find((call) => call.name === 'fork.session')!.args as {+ nativeForkAnchorSessionMap: Array<[string, string]>;+ };+ expect(txArgs.nativeForkAnchorSessionMap).toEqual([+ ['codex-thread-source', 'codex-thread-child'],+ ]);+ });++ it('codex path: keeps the legacy fork path when the latest copied turn has no native anchor', async () => {+ const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });+ const priorUser = makeMessageRow({ id: 'user-1', role: 'user', createdAt: 2000 });+ const olderAnchoredAssistant = makeMessageRow({+ id: 'asst-old-anchor',+ role: 'assistant',+ agentKind: 'codex',+ agentMeta: JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'legacy-codex-thread',+ kind: 'turn',+ id: 'older-turn',+ },+ }),+ createdAt: 2250,+ });+ const priorAssistant = makeMessageRow({+ id: 'asst-1',+ role: 'assistant',+ agentKind: 'codex',+ agentMeta: JSON.stringify({ turnCompleted: true }),+ createdAt: 2500,+ });++ selectQueue.push([+ makeSourceRow({ agentKind: 'codex', sdkSessionId: 'legacy-codex-thread' }),+ ]);+ selectQueue.push([target]);+ selectQueue.push([priorUser, olderAnchoredAssistant, priorAssistant]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'legacy-codex-child',+ parentSessionId: 'src-session',+ }),+ ]);+ queryMock.mockResolvedValue([{ role: 'user', content: '"target"' }]);+ forkSdkSessionMock.mockResolvedValue({+ newSdkSessionId: 'legacy-codex-child',+ uuidMap: new Map<string, string>(),+ });++ await forkSessionAtMessage('src-session', 'target-user');++ expect(forkSdkSessionMock).toHaveBeenCalledWith(+ 'codex',+ expect.not.objectContaining({ lastTurnId: expect.anything() }),+ );+ const txArgs = txCalls.find((call) => call.name === 'fork.session')!.args as {+ nativeForkAnchorSessionMap?: Array<[string, string]>;+ };+ expect(txArgs.nativeForkAnchorSessionMap).toBeUndefined();+ });++ it('codex path: does not reuse an older anchor after a tool-only turn', async () => {+ const priorUser = makeMessageRow({+ id: 'anchored-user',+ role: 'user',+ agentKind: 'codex',+ createdAt: 1750,+ });+ const priorAssistant = makeMessageRow({+ id: 'anchored-assistant',+ role: 'assistant',+ agentKind: 'codex',+ agentMeta: JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-source',+ kind: 'turn',+ id: 'older-turn',+ },+ }),+ createdAt: 2000,+ });+ const toolOnlyUser = makeMessageRow({+ id: 'tool-only-user',+ role: 'user',+ agentKind: 'codex',+ createdAt: 2500,+ });+ const toolResult = makeMessageRow({+ id: 'tool-result',+ role: 'tool_result',+ agentKind: 'codex',+ createdAt: 2750,+ });+ const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });++ selectQueue.push([+ makeSourceRow({ agentKind: 'codex', sdkSessionId: 'codex-thread-source' }),+ ]);+ selectQueue.push([target]);+ selectQueue.push([priorUser, priorAssistant, toolOnlyUser, toolResult]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-child',+ parentSessionId: 'src-session',+ }),+ ]);+ queryMock.mockResolvedValue([{ role: 'user', content: '"target"' }]);+ forkSdkSessionMock.mockResolvedValue({+ newSdkSessionId: 'codex-thread-child',+ uuidMap: new Map<string, string>(),+ });++ await forkSessionAtMessage('src-session', 'target-user');++ expect(forkSdkSessionMock).toHaveBeenCalledWith(+ 'codex',+ expect.not.objectContaining({ lastTurnId: expect.anything() }),+ );+ });+it('pi path: creates a new SDK session but leaves business-session activation to first-send lazy-create', async () => {const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });const priorUser = makeMessageRow({@@ -966,6 +1177,197 @@ describe('forkSessionAtMessage', () => {expect(txArgs.newSession.providerId).toBeNull();});+ it('restores the provider snapshot from a new historical switch boundary', async () => {+ const target = makeMessageRow({+ id: 'historical-codex-assistant',+ clientId: 'historical-codex-assistant-client',+ role: 'assistant',+ agentKind: 'codex',+ createdAt: 2500,+ rowid: 20,+ });+ const priorUser = makeMessageRow({+ id: 'historical-codex-user',+ role: 'user',+ agentKind: 'codex',+ createdAt: 2000,+ rowid: 10,+ });+ selectQueue.push([+ makeSourceRow({ agentKind: 'pi', model: 'pi-model', sdkSessionId: 'current-pi-session' }),+ ]);+ selectQueue.push([target]);+ selectQueue.push([]);+ selectQueue.push([priorUser, target]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'google/gemini-3.7-flash',+ providerId: 'xd',+ sdkSessionId: 'forked-codex-session',+ parentSessionId: 'src-session',+ }),+ ]);+ queryOneMock+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({+ content: JSON.stringify({+ fromAgentKind: 'codex',+ toAgentKind: 'pi',+ fromModel: 'google/gemini-3.7-flash',+ fromProviderId: 'xd',+ fromSdkSessionId: 'parked-codex-session',+ }),+ created_at: 2800,+ rowid: 30,+ });+ forkSdkSessionMock.mockResolvedValue({+ newSdkSessionId: 'forked-codex-session',+ uuidMap: new Map<string, string>(),+ });++ await forkSessionAtMessage('src-session', 'historical-codex-assistant-client');++ expect(forkSdkSessionMock).toHaveBeenCalledWith(+ 'codex',+ expect.objectContaining({+ sourceSdkSessionId: 'parked-codex-session',+ model: 'google/gemini-3.7-flash',+ providerId: 'xd',+ }),+ );+ expect(inferProviderIdForModelMock).not.toHaveBeenCalled();+ });++ it('restores provider from the nearest new entry boundary when the exit boundary is old', async () => {+ const target = makeMessageRow({+ id: 'mixed-codex-assistant',+ clientId: 'mixed-codex-assistant-client',+ role: 'assistant',+ agentKind: 'codex',+ createdAt: 2500,+ rowid: 20,+ });+ const priorUser = makeMessageRow({+ id: 'mixed-codex-user',+ role: 'user',+ agentKind: 'codex',+ createdAt: 2400,+ rowid: 15,+ });+ selectQueue.push([+ makeSourceRow({ agentKind: 'pi', model: 'pi-model', sdkSessionId: 'current-pi-session' }),+ ]);+ selectQueue.push([target]);+ selectQueue.push([]);+ selectQueue.push([priorUser, target]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'google/gemini-3.7-flash',+ providerId: 'xd',+ sdkSessionId: 'forked-codex-session',+ parentSessionId: 'src-session',+ }),+ ]);+ queryOneMock+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({+ content: JSON.stringify({+ fromAgentKind: 'codex',+ toAgentKind: 'pi',+ fromModel: 'google/gemini-3.7-flash',+ fromSdkSessionId: 'parked-codex-session',+ }),+ created_at: 2800,+ rowid: 30,+ })+ .mockResolvedValueOnce({+ content: JSON.stringify({+ fromAgentKind: 'cc',+ toAgentKind: 'codex',+ fromModel: 'claude-sonnet-4-6',+ toModel: 'google/gemini-3.7-flash',+ toProviderId: 'xd',+ fromSdkSessionId: 'parked-claude-session',+ }),+ });+ forkSdkSessionMock.mockResolvedValue({+ newSdkSessionId: 'forked-codex-session',+ uuidMap: new Map<string, string>(),+ });++ await forkSessionAtMessage('src-session', 'mixed-codex-assistant-client');++ expect(forkSdkSessionMock).toHaveBeenCalledWith(+ 'codex',+ expect.objectContaining({ providerId: 'xd' }),+ );+ expect(inferProviderIdForModelMock).not.toHaveBeenCalled();+ });++ it('infers a unique Codex provider for fully legacy switch boundaries', async () => {+ const target = makeMessageRow({+ id: 'legacy-codex-assistant',+ clientId: 'legacy-codex-assistant-client',+ role: 'assistant',+ agentKind: 'codex',+ createdAt: 2500,+ rowid: 20,+ });+ const priorUser = makeMessageRow({+ id: 'legacy-codex-user',+ role: 'user',+ agentKind: 'codex',+ createdAt: 2000,+ rowid: 10,+ });+ selectQueue.push([+ makeSourceRow({ agentKind: 'pi', model: 'pi-model', sdkSessionId: 'current-pi-session' }),+ ]);+ selectQueue.push([target]);+ selectQueue.push([]);+ selectQueue.push([priorUser, target]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'google/gemini-3.7-flash',+ providerId: 'xd',+ sdkSessionId: 'forked-codex-session',+ parentSessionId: 'src-session',+ }),+ ]);+ queryOneMock+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({+ content: JSON.stringify({+ fromAgentKind: 'codex',+ toAgentKind: 'pi',+ fromModel: 'google/gemini-3.7-flash',+ fromSdkSessionId: 'parked-codex-session',+ }),+ created_at: 2800,+ rowid: 30,+ })+ .mockResolvedValueOnce(null);+ inferProviderIdForModelMock.mockReturnValue('xd');+ forkSdkSessionMock.mockResolvedValue({+ newSdkSessionId: 'forked-codex-session',+ uuidMap: new Map<string, string>(),+ });++ await forkSessionAtMessage('src-session', 'legacy-codex-assistant-client');++ expect(inferProviderIdForModelMock).toHaveBeenCalledWith(+ 'google/gemini-3.7-flash',+ 'codex',+ );+ expect(forkSdkSessionMock).toHaveBeenCalledWith(+ 'codex',+ expect.objectContaining({ providerId: 'xd' }),+ );+ });+it('re-arms the copied handoff when forking from the first user after an engine switch', async () => {const boundary = makeMessageRow({id: 'switch-boundary',@@ -1014,12 +1416,105 @@ describe('forkSessionAtMessage', () => {expect(txArgs.newSession.agentKind).toBe('cc');});+ it('does not reuse an older Codex turn anchor for the first user after an engine switch', async () => {+ const oldCodexAssistant = makeMessageRow({+ id: 'old-codex-assistant',+ clientId: 'old-codex-assistant-client',+ role: 'assistant',+ agentKind: 'codex',+ agentMeta: JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'parked-codex-thread',+ kind: 'turn',+ id: 'old-codex-turn',+ },+ }),+ createdAt: 2000,+ rowid: 10,+ });+ const boundary = makeMessageRow({+ id: 'switch-to-codex',+ clientId: 'switch-to-codex-client',+ role: 'agent_switch',+ content: JSON.stringify({+ fromAgentKind: 'cc',+ toAgentKind: 'codex',+ fromModel: 'claude-sonnet-4-6',+ fromSdkSessionId: 'parked-claude-session',+ handoff: 'full handoff',+ consumed: true,+ }),+ createdAt: 2500,+ rowid: 20,+ });+ const target = makeMessageRow({+ id: 'first-codex-user',+ clientId: 'first-codex-user-client',+ role: 'user',+ agentKind: 'codex',+ createdAt: 3000,+ rowid: 30,+ });++ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'gpt-5.4',+ sdkSessionId: 'fresh-codex-thread',+ }),+ ]);+ selectQueue.push([target]);+ selectQueue.push([oldCodexAssistant, boundary]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'forked-codex-thread',+ parentSessionId: 'src-session',+ }),+ ]);+ queryMock.mockResolvedValue([]);+ forkSdkSessionMock.mockResolvedValue({+ newSdkSessionId: 'forked-codex-thread',+ uuidMap: new Map<string, string>(),+ });++ await forkSessionAtMessage('src-session', 'first-codex-user-client');++ expect(forkSdkSessionMock).toHaveBeenCalledWith('codex', {+ sourceSdkSessionId: 'fresh-codex-thread',+ model: 'gpt-5.4',+ providerId: 'xd',+ upToMessageId: undefined,+ tailTurnsToDrop: 0,+ title: '[Fork] Project A',+ workingDir: '/work',+ remoteHostId: null,+ });+ const txArgs = txCalls.find((call) => call.name === 'fork.session')!.args as {+ resetHandoffBoundaryClientId: string | null;+ nativeForkAnchorSessionMap?: Array<[string, string]>;+ };+ expect(txArgs.resetHandoffBoundaryClientId).toBe('switch-to-codex-client');+ expect(txArgs.nativeForkAnchorSessionMap).toBeUndefined();+ });+it('counts rollback turns only from the parked Codex thread across later resumes', async () => {const target = makeMessageRow({id: 'historical-codex-assistant',clientId: 'historical-codex-assistant-cid',role: 'assistant',agentKind: 'codex',+ agentMeta: JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'parked-codex-thread',+ kind: 'turn',+ id: 'historical-codex-turn',+ },+ }),createdAt: 2500,rowid: 20,});@@ -1086,6 +1581,7 @@ describe('forkSessionAtMessage', () => {forkSdkSessionMock.mockResolvedValue({newSdkSessionId: 'forked-codex-thread',uuidMap: new Map<string, string>(),+ usedNativeForkAnchor: true,});await forkSessionAtMessage('src-session', 'historical-codex-assistant-cid');@@ -1095,17 +1591,23 @@ describe('forkSessionAtMessage', () => {model: 'gpt-5.4',providerId: null,upToMessageId: undefined,+ lastTurnId: 'historical-codex-turn',tailTurnsToDrop: 2,title: '[Fork] Project A',workingDir: '/work',// 轮 26:Pi fork 守卫透传 remoteHostId(本地源 → null)。remoteHostId: null,});+ expect(inferProviderIdForModelMock).toHaveBeenCalledWith('gpt-5.4', 'codex');const txArgs = txCalls.find((call) => call.name === 'fork.session')!.args as {newSession: Record<string, unknown>;+ nativeForkAnchorSessionMap: Array<[string, string]>;};expect(txArgs.newSession.agentKind).toBe('codex');expect(txArgs.newSession.model).toBe('gpt-5.4');+ expect(txArgs.nativeForkAnchorSessionMap).toEqual([+ ['parked-codex-thread', 'forked-codex-thread'],+ ]);});// ── assistant 目标(fork-from-reply)────────────────────────────────────diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 9052136d42..6bc45f3f06 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -548,9 +548,8 @@ describe('maker:event hot path ordering', () => {expect(boundaryBlock).toContain("event.type === 'done'");expect(boundaryBlock).toContain("event.source !== 'codex'");expect(boundaryBlock).toContain('isSuccessfulCodexDoneEventData(event.data)');- expect(boundaryBlock).toContain(- 'markAssistantTurnCompleted(session.id, turnBoundaryAssistantPersistId)',- );+ expect(boundaryBlock).toContain('markAssistantTurnCompleted(');+ expect(boundaryBlock).toContain('nativeForkAnchor ? { nativeForkAnchor } : undefined');expect(boundaryBlock).toContain('markAssistantTurnFailed(session.id, turnBoundaryAssistantPersistId)',);diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex fab02b0c5c..3379da312f 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -2434,11 +2434,19 @@ describe('consumeLastAssistantPersistId(per-turn 费用挂载的目标消息追});it('done seal 以 durable patch 落库', async () => {- await expect(markAssistantTurnCompleted(SESSION, 'assistant-final')).resolves.toBe(true);+ const nativeForkAnchor = {+ agentKind: 'codex' as const,+ sdkSessionId: 'source-thread',+ kind: 'turn' as const,+ id: 'turn-at-boundary',+ };+ await expect(+ markAssistantTurnCompleted(SESSION, 'assistant-final', { nativeForkAnchor }),+ ).resolves.toBe(true);expect(patchMessageAgentMetaWithResult).toHaveBeenCalledWith(SESSION,'assistant-final',- { turnCompleted: true },+ { nativeForkAnchor, turnCompleted: true },);expect(broadcastMessageAgentMetaUpdate).toHaveBeenCalledWith(SESSION,diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 02e54f331d..4c099fc508 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -1650,6 +1650,7 @@ function forkSession(readyDb, args) {const targetRowid = nullableNumber(payload.targetRowid);const newSession = asRecord(payload.newSession, 'newSession');const uuidMap = normalizeUuidMap(payload.uuidMap);+ const nativeForkAnchorSessionMap = normalizeNativeForkAnchorSessionMap(payload.nativeForkAnchorSessionMap);const legacyTranscriptParentUuids = normalizeStringSet(payload.legacyTranscriptParentUuids, 'legacyTranscriptParentUuids');const toolParentUuids = normalizeStringSet(payload.toolParentUuids, 'toolParentUuids');const detachAgentSwitchSessions = payload.detachAgentSwitchSessions === true;@@ -1696,7 +1697,7 @@ function forkSession(readyDb, args) {for (let i = 0; i < sourceMessages.length; i += 1) {const message = sourceMessages[i];const ids = newMessageIds[i];- insertMessage.run(ids.id, ids.clientId, expectString(newSession.id, 'newSession.id'), message.role, sanitizeForkedMessageContent(message, { detachAgentSwitchSessions, resetHandoffBoundaryClientId }), message.tool_use_id, remapAgentMetaUuid(message.agent_meta, uuidMap, legacyTranscriptParentUuids, toolParentUuids), message.agent_kind, message.created_at);+ insertMessage.run(ids.id, ids.clientId, expectString(newSession.id, 'newSession.id'), message.role, sanitizeForkedMessageContent(message, { detachAgentSwitchSessions, resetHandoffBoundaryClientId }), message.tool_use_id, remapForkedAgentMeta(message.agent_meta, uuidMap, legacyTranscriptParentUuids, toolParentUuids, nativeForkAnchorSessionMap), message.agent_kind, message.created_at);}})();return { messageCount: sourceMessages.length };@@ -1928,7 +1929,7 @@ function extractContentText(content) {return parts.join('\\n\\n');}-function remapAgentMetaUuid(raw, map, legacyTranscriptParentUuids = new Set(), toolParentUuids = new Set()) {+function remapForkedAgentMeta(raw, map, legacyTranscriptParentUuids = new Set(), toolParentUuids = new Set(), nativeForkAnchorSessionMap = new Map()) {if (!raw || raw === 'null') return raw;let parsed;try { parsed = JSON.parse(raw); } catch (_) { return raw; }@@ -1952,6 +1953,19 @@ function remapAgentMetaUuid(raw, map, legacyTranscriptParentUuids = new Set(), tif (mapped) next.transcriptParentUuid = mapped;else delete next.transcriptParentUuid;}+ const nativeForkAnchor = next.nativeForkAnchor;+ if (+ next.turnCompleted === true &&+ isRecord(nativeForkAnchor) &&+ nativeForkAnchor.agentKind === 'codex' &&+ nativeForkAnchor.kind === 'turn' &&+ typeof nativeForkAnchor.id === 'string' &&+ nativeForkAnchor.id &&+ typeof nativeForkAnchor.sdkSessionId === 'string'+ ) {+ const mapped = nativeForkAnchorSessionMap.get(nativeForkAnchor.sdkSessionId);+ if (mapped) next.nativeForkAnchor = { ...nativeForkAnchor, sdkSessionId: mapped };+ }return JSON.stringify(next);}@@ -1961,14 +1975,22 @@ function normalizeStringSet(value, label) {}function normalizeUuidMap(value) {+ return normalizeStringMap(value, 'uuidMap');+}++function normalizeNativeForkAnchorSessionMap(value) {+ return value === undefined ? new Map() : normalizeStringMap(value, 'nativeForkAnchorSessionMap');+}++function normalizeStringMap(value, label) {if (Array.isArray(value)) {return new Map(value.map((entry) => {- if (!Array.isArray(entry) || entry.length !== 2) throw invalidArgs('uuidMap entries must be pairs');- return [expectString(entry[0], 'uuidMap.key'), expectString(entry[1], 'uuidMap.value')];+ if (!Array.isArray(entry) || entry.length !== 2) throw invalidArgs(label + ' entries must be pairs');+ return [expectString(entry[0], label + '.key'), expectString(entry[1], label + '.value')];}));}- const record = asRecord(value, 'uuidMap');- return new Map(Object.entries(record).map(([key, mapped]) => [key, expectString(mapped, 'uuidMap.' + key)]));+ const record = asRecord(value, label);+ return new Map(Object.entries(record).map(([key, mapped]) => [key, expectString(mapped, label + '.' + key)]));}function normalizeNewMessageIds(value) {diff --git a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.tsindex f7dec5446f..aa0161a8be 100644--- a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts@@ -192,6 +192,29 @@ describe('WorkerThreadTransport', () => {50,],});+ await transport.send('exec', {+ sql: `INSERT INTO messages (+ id, client_id, session_id, role, content, agent_meta, agent_kind, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ params: [+ 'assistant',+ 'assistant-client',+ 'src',+ 'assistant',+ 'reply',+ JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'source-thread',+ kind: 'turn',+ id: 'turn-1',+ },+ }),+ 'codex',+ 75,+ ],+ });await transport.send('tx', {name: 'fork.session',@@ -225,8 +248,12 @@ describe('WorkerThreadTransport', () => {updatedAt: 1,},uuidMap: [],+ nativeForkAnchorSessionMap: [['source-thread', 'child-thread']],detachAgentSwitchSessions: true,- newMessageIds: [{ id: 'forked-switch', clientId: 'forked-switch-client' }],+ newMessageIds: [+ { id: 'forked-switch', clientId: 'forked-switch-client' },+ { id: 'forked-assistant', clientId: 'forked-assistant-client' },+ ],},});@@ -243,6 +270,19 @@ describe('WorkerThreadTransport', () => {expect(JSON.parse(copiedSwitch.content)).toMatchObject({fromSdkSessionId: null,});+ const copiedAssistant = await transport.send<{ agent_meta: string }>('queryOne', {+ sql: 'SELECT agent_meta FROM messages WHERE id = ?',+ params: ['forked-assistant'],+ });+ expect(JSON.parse(copiedAssistant.agent_meta)).toEqual({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'child-thread',+ kind: 'turn',+ id: 'turn-1',+ },+ });} finally {await transport.close();}diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 3c71d2760b..c12b2163da 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -1625,7 +1625,11 @@ describe('db worker tx handlers', () => {'src','assistant','copy',- JSON.stringify({ uuid: 'old', parentUuid: 'parent', transcriptParentUuid: 'old-parent' }),+ JSON.stringify({+ uuid: 'old',+ parentUuid: 'parent',+ transcriptParentUuid: 'old-parent',+ }),'cc',100,'m2',@@ -1688,6 +1692,56 @@ describe('db worker tx handlers', () => {});});+ it('fork.session rebinds completed Codex turn anchors to the child thread', async () => {+ await withClient(async (client) => {+ await seedSession(client, 'src');+ await client.exec(+ 'INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, agent_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',+ [+ 'm1',+ 'c1',+ 'src',+ 'assistant',+ 'copy',+ JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'source-thread',+ kind: 'turn',+ id: 'turn-1',+ },+ }),+ 'codex',+ 100,+ ],+ );++ await client.tx('fork.session', {+ sourceSessionId: 'src',+ targetCreatedAt: 200,+ newSession: sessionRow('forked'),+ uuidMap: [],+ nativeForkAnchorSessionMap: [['source-thread', 'child-thread']],+ newMessageIds: [{ id: 'copy-id-1', clientId: 'copy-client-1' }],+ });++ const copied = await client.queryOne<{ agent_meta: string }>(+ 'SELECT agent_meta FROM messages WHERE session_id = ?',+ ['forked'],+ );+ expect(JSON.parse(copied?.agent_meta ?? '{}')).toEqual({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'child-thread',+ kind: 'turn',+ id: 'turn-1',+ },+ });+ });+ });+it('fork.session filters pre-clear/same-ms tail rows and detaches copied parked sessions', async () => {await withClient(async (client) => {await seedSession(client, 'src');diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex bd35c8e3ff..75d8789426 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -145,6 +145,8 @@ export interface ForkSessionArgs {updatedAt: number;};uuidMap: Array<[string, string]> | Record<string, string>;+ /** Rebind copied provider-native fork anchors to the child vendor session. */+ nativeForkAnchorSessionMap?: Array<[string, string]> | Record<string, string>;/** Legacy Claude imports may have stored transcript parentage in parentUuid. */legacyTranscriptParentUuids?: string[];/** Imported Claude assistant rows may retain an external tool-use parent id. */diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex 9cf8ff8637..40f54df3ed 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -353,7 +353,8 @@ export const messages = sqliteTable(// 的 onTurnErrorEvent)。drizzle 的 text enum 只是 TS 类型约束,SQLite 列// 无 CHECK,扩枚举不产生 migration(db:generate 应为 no-op)。// 'agent_switch':session 内 agent 引擎切换边界行(session-agent-switch),- // content 存 { fromAgentKind, toAgentKind, fromModel, toModel, handoff }。+ // content 存 { fromAgentKind, toAgentKind, fromModel, toModel,+ // fromProviderId?, toProviderId?, handoff }。// handoff 交接文本只进这里(供 UI 展开查看/debug),不作为可见消息渲染正文,// 也不落 user 消息——wire 注入与显示分离。// 'context_rebuild':消息内容删除后的内部重建标记。rewind_at 固定非 NULL,diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex b9229e598b..6fda1f95e1 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -1366,6 +1366,9 @@ function forkSession(db: Database.Database, args: unknown): { messageCount: numbconst targetRowid = nullableNumber(payload.targetRowid);const newSession = asRecord(payload.newSession, 'newSession');const uuidMap = normalizeUuidMap(payload.uuidMap);+ const nativeForkAnchorSessionMap = normalizeNativeForkAnchorSessionMap(+ payload.nativeForkAnchorSessionMap,+ );const legacyTranscriptParentUuids = normalizeStringSet(payload.legacyTranscriptParentUuids,'legacyTranscriptParentUuids',@@ -1466,11 +1469,12 @@ function forkSession(db: Database.Database, args: unknown): { messageCount: numbresetHandoffBoundaryClientId,}),message.tool_use_id,- remapAgentMetaUuid(+ remapForkedAgentMeta(message.agent_meta,uuidMap,legacyTranscriptParentUuids,toolParentUuids,+ nativeForkAnchorSessionMap,),message.agent_kind,message.created_at,@@ -2203,11 +2207,12 @@ function extractContentText(content: unknown): string {return parts.join('\n\n');}-function remapAgentMetaUuid(+function remapForkedAgentMeta(raw: string | null,map: Map<string, string>,legacyTranscriptParentUuids: Set<string> = new Set(),toolParentUuids: Set<string> = new Set(),+ nativeForkAnchorSessionMap: Map<string, string> = new Map(),): string | null {if (!raw || raw === 'null') return raw;let parsed: Record<string, unknown>;@@ -2241,6 +2246,19 @@ function remapAgentMetaUuid(if (mapped) next.transcriptParentUuid = mapped;else delete next.transcriptParentUuid;}+ const nativeForkAnchor = next.nativeForkAnchor;+ if (+ next.turnCompleted === true &&+ isRecord(nativeForkAnchor) &&+ nativeForkAnchor.agentKind === 'codex' &&+ nativeForkAnchor.kind === 'turn' &&+ typeof nativeForkAnchor.id === 'string' &&+ nativeForkAnchor.id &&+ typeof nativeForkAnchor.sdkSessionId === 'string'+ ) {+ const mapped = nativeForkAnchorSessionMap.get(nativeForkAnchor.sdkSessionId);+ if (mapped) next.nativeForkAnchor = { ...nativeForkAnchor, sdkSessionId: mapped };+ }return JSON.stringify(next);}@@ -2250,17 +2268,32 @@ function normalizeStringSet(value: unknown, label: string): Set<string> {}function normalizeUuidMap(value: unknown): Map<string, string> {+ return normalizeStringMap(value, 'uuidMap');+}++function normalizeNativeForkAnchorSessionMap(value: unknown): Map<string, string> {+ return value === undefined+ ? new Map()+ : normalizeStringMap(value, 'nativeForkAnchorSessionMap');+}++function normalizeStringMap(value: unknown, label: string): Map<string, string> {if (Array.isArray(value)) {return new Map(value.map((entry) => {- if (!Array.isArray(entry) || entry.length !== 2) throw invalidArgs('uuidMap entries must be pairs');- return [expectString(entry[0], 'uuidMap.key'), expectString(entry[1], 'uuidMap.value')];+ if (!Array.isArray(entry) || entry.length !== 2) {+ throw invalidArgs(`${label} entries must be pairs`);+ }+ return [+ expectString(entry[0], `${label}.key`),+ expectString(entry[1], `${label}.value`),+ ];}),);}- const record = asRecord(value, 'uuidMap');+ const record = asRecord(value, label);return new Map(- Object.entries(record).map(([key, mapped]) => [key, expectString(mapped, `uuidMap.${key}`)]),+ Object.entries(record).map(([key, mapped]) => [key, expectString(mapped, `${label}.${key}`)]),);}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.tsindex df6f353c09..d1ca916519 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts@@ -19,6 +19,7 @@ function makeRow(overrides: Partial<AgentSwitchSessionRow> = {}): AgentSwitchSesid: 's1',agentKind: 'cc',model: 'claude-fable-5',+ providerId: 'xd',status: 'active',remoteHostId: null,orcaRole: null,@@ -93,6 +94,8 @@ describe('performSessionAgentSwitch', () => {expect(boundary.toAgentKind).toBe('codex');expect(boundary.fromModel).toBe('claude-fable-5');expect(boundary.toModel).toBe('gpt-5.5');+ expect(boundary.fromProviderId).toBe('xd');+ expect(boundary.toProviderId).toBeNull();expect(boundary.fromSdkSessionId).toBe('sdk-old');expect(boundary.resumed).toBe(false);expect(boundary.consumed).toBe(false);@@ -115,6 +118,8 @@ describe('performSessionAgentSwitch', () => {const boundary = vi.mocked(deps.insertBoundaryMessage).mock.calls[0][1];expect(boundary.fromAgentKind).toBe('codex');expect(boundary.toAgentKind).toBe('cc');+ expect(boundary.fromProviderId).toBe('xd');+ expect(boundary.toProviderId).toBe('xd');});it('codex → pi + OpenAI 关闭旧会话并保持目标 provider route', async () => {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex ac1b6bc992..df8db4b956 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4927,7 +4927,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidif (!isSuccessfulDone) {void markAssistantTurnFailed(session.id, turnBoundaryAssistantPersistId);} else if (!isPairedFailedTurnDone) {- void markAssistantTurnCompleted(session.id, turnBoundaryAssistantPersistId);+ const nativeForkAnchor = eventAgentMeta?.nativeForkAnchor;+ void markAssistantTurnCompleted(+ session.id,+ turnBoundaryAssistantPersistId,+ nativeForkAnchor ? { nativeForkAnchor } : undefined,+ );}}// error 行在 flushOrphanToolResults 之后入队,保证 orphan tool_result 排在@@ -9320,6 +9325,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)id: sessions.id,agentKind: sessions.agentKind,model: sessions.model,+ providerId: sessions.providerId,status: sessions.status,remoteHostId: sessions.remoteHostId,orcaRole: sessions.orcaRole,diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex 5c3d333f2c..3279bd29d5 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -74,6 +74,9 @@ export interface AgentSwitchBoundaryContent {toAgentKind: DbAgentKind;fromModel: string | null;toModel: string | null;+ /** 离场引擎与目标引擎各自的 provider 快照;缺失表示旧版边界。 */+ fromProviderId?: string | null;+ toProviderId?: string | null;/*** 旧引擎的原生 session id 快照 = 它的停泊绑定:Phase 2 切回该引擎时由* findParkedEngineSession 从最近一条"它离场"的边界行读回,resume 续接。@@ -96,6 +99,7 @@ export interface AgentSwitchSessionRow {id: string;agentKind: string;model: string | null;+ providerId: string | null;status: string;remoteHostId: string | null;orcaRole: string | null;@@ -542,6 +546,9 @@ export async function performSessionAgentSwitch(toAgentKind: toDbKind,fromModel: row.model,toModel: model,+ fromProviderId: row.providerId,+ toProviderId:+ normalizedProviderId === undefined ? row.providerId : normalizedProviderId,fromSdkSessionId: row.sdkSessionId,handoff,resumed: !!parked,diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.tsindex 25d715d72d..bfadd4a216 100644--- a/apps/desktop/src/main/maker-orchestration/fork.ts+++ b/apps/desktop/src/main/maker-orchestration/fork.ts@@ -18,6 +18,7 @@ import { sessions, messages } from '../localDb/schema';import { sessionToCamel } from '../localDb/mapper';import { commitContextRebuild, createMessage } from '../localDb/ipc/messages.js';import { getMaker } from '../maker-host/index.js';+import { inferProviderIdForModel } from '../maker-host/provider-route.js';import { createBusinessSessionId } from '../sessionIds.js';import { dbToMakerAgentKind, normalizeDbAgentKind } from '../../shared/agentKindConversion.js';import type { AgentMeta, Session } from '../../renderer/lib/ccAgent.types';@@ -97,6 +98,8 @@ interface ParsedAgentSwitchBoundary {fromAgentKind: DbAgentKind;toAgentKind?: DbAgentKind;fromModel: string | null;+ fromProviderId?: string | null;+ toProviderId?: string | null;fromSdkSessionId: string | null;handoff?: string;}@@ -218,6 +221,17 @@ function parseAgentSwitchBoundary(content: string): ParsedAgentSwitchBoundary |fromAgentKind: parsed.fromAgentKind,toAgentKind,fromModel: typeof parsed.fromModel === 'string' ? parsed.fromModel : null,+ ...(Object.hasOwn(parsed, 'fromProviderId')+ ? {+ fromProviderId:+ typeof parsed.fromProviderId === 'string' ? parsed.fromProviderId : null,+ }+ : {}),+ ...(Object.hasOwn(parsed, 'toProviderId')+ ? {+ toProviderId: typeof parsed.toProviderId === 'string' ? parsed.toProviderId : null,+ }+ : {}),fromSdkSessionId:typeof parsed.fromSdkSessionId === 'string' && parsed.fromSdkSessionId? parsed.fromSdkSessionId@@ -229,6 +243,33 @@ function parseAgentSwitchBoundary(content: string): ParsedAgentSwitchBoundary |}}+function parseCodexNativeForkAnchor(raw: string | null): {+ sdkSessionId: string;+ turnId: string;+} | null {+ if (!raw) return null;+ try {+ const meta = JSON.parse(raw) as Record<string, unknown>;+ if (meta.turnCompleted !== true) return null;+ const anchor = meta.nativeForkAnchor;+ if (!anchor || typeof anchor !== 'object' || Array.isArray(anchor)) return null;+ const candidate = anchor as Record<string, unknown>;+ if (+ candidate.agentKind !== 'codex' ||+ candidate.kind !== 'turn' ||+ typeof candidate.sdkSessionId !== 'string' ||+ !candidate.sdkSessionId ||+ typeof candidate.id !== 'string' ||+ !candidate.id+ ) {+ return null;+ }+ return { sdkSessionId: candidate.sdkSessionId, turnId: candidate.id };+ } catch {+ return null;+ }+}+function isBefore(left: MessagePosition, right: MessagePosition): boolean {if (left.createdAt !== right.createdAt) return left.createdAt < right.createdAt;if (left.rowid === null) return false;@@ -305,11 +346,42 @@ async function resolveForkNativeSource(if (!parsed?.fromSdkSessionId) {throw forkError('UNSUPPORTED_HISTORY', '目标消息对应的历史引擎会话不可用');}+ const model = parsed.fromModel ?? source.model;+ let providerId: string | null;+ if (Object.hasOwn(parsed, 'fromProviderId')) {+ providerId = parsed.fromProviderId ?? null;+ } else {+ const previousSwitch = await client.queryOne<{ content: string }>(+ `SELECT content FROM messages+ WHERE session_id = ?+ AND role = 'agent_switch'+ AND rewind_at IS NULL+ AND (created_at < ? OR (created_at = ? AND rowid < ?))+ ORDER BY created_at DESC, rowid DESC+ LIMIT 1`,+ positionParams,+ );+ const previousBoundary = previousSwitch+ ? parseAgentSwitchBoundary(previousSwitch.content)+ : null;+ if (+ previousBoundary?.toAgentKind === parsed.fromAgentKind &&+ Object.hasOwn(previousBoundary, 'toProviderId')+ ) {+ providerId = previousBoundary.toProviderId ?? null;+ } else if (parsed.fromAgentKind === normalizeDbAgentKind(source.agentKind)) {+ providerId = source.providerId;+ } else if (parsed.fromAgentKind === 'codex') {+ providerId = inferProviderIdForModel(model, 'codex');+ } else {+ providerId = null;+ }+ }return {agentKind: parsed.fromAgentKind,sdkSessionId: parsed.fromSdkSessionId,- model: parsed.fromModel ?? source.model,- providerId: parsed.fromAgentKind === source.agentKind ? source.providerId : null,+ model,+ providerId,nextSwitch: { createdAt: nextSwitch.created_at, rowid: nextSwitch.rowid },reuseVendorSession: true,};@@ -411,6 +483,34 @@ function resolveClaudeAssistantAnchor(return undefined;}+function resolveCodexTurnAnchor(+ rows: ForkTimelineMessage[],+ sourceSdkSessionId: string,+): string | undefined {+ let timelineSdkSessionId: string | null = sourceSdkSessionId;+ for (let i = rows.length - 1; i >= 0; i -= 1) {+ const row = rows[i];+ if (row.role === 'context_rebuild') {+ timelineSdkSessionId = null;+ continue;+ }+ if (row.role === 'agent_switch') {+ timelineSdkSessionId = parseAgentSwitchBoundary(row.content)?.fromSdkSessionId ?? null;+ continue;+ }+ if (row.role === 'user' && timelineSdkSessionId === sourceSdkSessionId) {+ return undefined;+ }+ if (row.role !== 'assistant' || timelineSdkSessionId !== sourceSdkSessionId) continue;+ const anchor = parseCodexNativeForkAnchor(row.agentMeta);+ // The newest assistant in this native segment is the requested boundary.+ // If that row predates anchors, belongs to a failed turn, or is malformed,+ // fall back for the whole fork instead of silently truncating at an older turn.+ return anchor?.sdkSessionId === sourceSdkSessionId ? anchor.turnId : undefined;+ }+ return undefined;+}+async function countCodexTailTurns(sourceSessionId: string,sourceCurrentSdkSessionId: string | null,@@ -688,6 +788,7 @@ export async function forkSessionAtMessage(// 到目标 user 消息。只有 Claude(cc)走 message-uuid 锚点路径。const usesTailTurnFork = isCodex || forkSource.agentKind === 'pi';let assistantUuid: string | undefined;+ let lastTurnId: string | undefined;let tailTurnsToDrop: number | undefined;let claudeAnchorIndex: ClaudeTranscriptAnchorIndex | null = null;const resetHandoffBoundaryClientId = findFirstUserAfterSwitchBoundary(@@ -711,6 +812,9 @@ export async function forkSessionAtMessage(throw forkError('NO_PRIOR_ASSISTANT', '请在 AI 回复之后的提问上 fork');}} else if (forkSource.reuseVendorSession && forkSource.sdkSessionId) {+ if (isCodex) {+ lastTurnId = resolveCodexTurnAnchor(sourceMessages, forkSource.sdkSessionId);+ }tailTurnsToDrop = await countCodexTailTurns(sourceSessionId,source.sdkSessionId,@@ -726,6 +830,7 @@ export async function forkSessionAtMessage(let newSdkSessionId: string | null = null;let uuidMap = new Map<string, string>();let initialContextTokens: number | undefined;+ let usedNativeForkAnchor = false;if (forkSource.reuseVendorSession &&forkSource.sdkSessionId &&@@ -737,6 +842,7 @@ export async function forkSessionAtMessage(sourceSdkSessionId: forkSource.sdkSessionId,...(isCodex ? { model: forkSource.model, providerId: forkSource.providerId } : {}),upToMessageId: assistantUuid,+ ...(lastTurnId ? { lastTurnId } : {}),...(tailTurnsToDrop !== undefined ? { tailTurnsToDrop } : {}),title: newTitle,workingDir: source.workingDir ?? undefined,@@ -752,7 +858,7 @@ export async function forkSessionAtMessage(const detail = codexForkFailureDetail(err);throw forkError('CODEX_FORK_STATE_UNAVAILABLE', detail);});- ({ newSdkSessionId, uuidMap, initialContextTokens } = forkResult);+ ({ newSdkSessionId, uuidMap, initialContextTokens, usedNativeForkAnchor = false } = forkResult);}const forkContextTokens = normalizePositiveInt(initialContextTokens);const forkContextWindow = normalizePositiveInt(source.contextWindow);@@ -811,6 +917,9 @@ export async function forkSessionAtMessage(updatedAt: now,},uuidMap: Array.from(txUuidMap.entries()),+ ...(usedNativeForkAnchor && forkSource.sdkSessionId && newSdkSessionId+ ? { nativeForkAnchorSessionMap: [[forkSource.sdkSessionId, newSdkSessionId]] }+ : {}),...(legacyTranscriptParentUuids.length > 0 ? { legacyTranscriptParentUuids } : {}),...(toolParentUuids.length > 0 ? { toolParentUuids } : {}),detachAgentSwitchSessions: true,diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex 3a6b67f7b9..84c856c1c4 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -343,10 +343,12 @@ function markAssistantTurnBoundary(sessionId: string,clientId: string | undefined,completed: boolean,+ metaPatch?: Pick<AgentMeta, 'nativeForkAnchor'>,): Promise<boolean> {if (!sessionId || !clientId) return Promise.resolve(false);return enqueueDurableWrite(`turn-boundary:${sessionId}:${clientId}:${completed}`, async (ownerScope) => {const patched = await patchMessageAgentMetaWithResult(sessionId, clientId, {+ ...metaPatch,turnCompleted: completed,});if (!patched) return false;@@ -362,8 +364,9 @@ function markAssistantTurnBoundary(export function markAssistantTurnCompleted(sessionId: string,clientId: string | undefined,+ metaPatch?: Pick<AgentMeta, 'nativeForkAnchor'>,): Promise<boolean> {- return markAssistantTurnBoundary(sessionId, clientId, true);+ return markAssistantTurnBoundary(sessionId, clientId, true, metaPatch);}/**diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.tsindex e02bc6ca78..6c6fe243b0 100644--- a/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts+++ b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts@@ -132,7 +132,11 @@ describe('Codex Micro guard store and manager', () => {const linkedRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-guard-link-'));roots.push(linkedRoot);fs.mkdirSync(path.join(linkedRoot, 'real'));- fs.symlinkSync(path.join(linkedRoot, 'real'), path.join(linkedRoot, 'support'));+ fs.symlinkSync(+ path.join(linkedRoot, 'real'),+ path.join(linkedRoot, 'support'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );expect(() => new CodexMicroGuardStore(path.join(linkedRoot, 'support')).prepare()).toThrow('unsafe',);diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex fc0c656b53..88cf05337b 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -20,6 +20,14 @@ export type AgentKind = 'cc' | 'codex' | 'pi';export type MakerVendor = AgentKind | 'orca';export type OrcaRole = 'lead' | 'worker';+/** Provider-native fork boundary. Extend this union when another Agent adopts it. */+export type NativeForkAnchor = {+ agentKind: 'codex';+ sdkSessionId: string;+ kind: 'turn';+ id: string;+};+/*** Host-side 消息来源标记:标识一条 user 消息是自动化任务注入的,* 而非用户手动输入。scheduler runner 落库时写入 agentMeta.origin,@@ -48,6 +56,8 @@ export interface CcMeta {/** Claude transcript chain parent. Do not confuse with parentUuid, which is parent_tool_use_id. */transcriptParentUuid?: string;sdkSessionId?: string;+ /** Exact provider boundary used by message-level fork when available. */+ nativeForkAnchor?: NativeForkAnchor;// assistant 专属model?: string;@@ -346,6 +356,9 @@ export interface AgentSwitchContent {toAgentKind: 'cc' | 'codex' | 'pi';fromModel: string | null;toModel: string | null;+ /** Agent 切换时的来源快照;缺失表示旧版边界数据。 */+ fromProviderId?: string | null;+ toProviderId?: string | null;handoff: string;/** Phase 2:true = 目标引擎续接(resume)了自己的停泊原生会话,交接为增量模式。 */resumed?: boolean;diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.tsindex 7d986d18d7..9729715ada 100644--- a/packages/maker-core/src/agents/codex/app-server/host.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.ts@@ -1538,6 +1538,11 @@ export class AppServerHost {return this.subscribers.size;}+ /** Whether this process already owns the live state for a root thread. */+ hasThreadSubscription(threadId: string): boolean {+ return this.subscribers.has(threadId);+ }+/** 是否已经 spawn 过子进程 (但可能已 close)。 */get hasStarted(): boolean {return this.client !== null;diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.tsindex d75fa3f61b..5ebc36b0e6 100644--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts@@ -452,9 +452,11 @@ export type SandboxPolicy =export interface ThreadForkParams {threadId: string;+ /** Fork the source thread at this provider-native turn boundary. */+ lastTurnId?: string;/** 可选: 从特定 rollout path fork (绝大多数场景用 threadId)。 */path?: string;- /** Codex 自家前端 fork 精确节点时会开启, 保留完整历史供后续 rollback。 */+ /** Legacy fork + rollback path only; lastTurnId precision path omits it. */persistExtendedHistory?: boolean;model?: string;cwd?: string;diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 32412a4e84..a9100239a5 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -540,6 +540,7 @@ function installFakeHost(openAiWebSocketsEnabled?: boolean;userAgent?: string;codexHome?: string;+ activeThreadIds?: string[];buildSessionMcpConfig?: (sessionInstanceId?: string) => Record<string, unknown>;} = {},) {@@ -594,6 +595,9 @@ function installFakeHost(return { release: vi.fn() };});const unsubscribeThread = vi.fn(async () => {});+ const hasThreadSubscription = vi.fn((threadId: string) =>+ opts.activeThreadIds?.includes(threadId) === true,+ );const isCodexProxyActive = vi.fn(() => opts.codexProxyActive === true);const isCodexBrowserUseAvailable = vi.fn(() => opts.codexBrowserUseAvailable === true,@@ -651,6 +655,7 @@ function installFakeHost(request,subscribeThread,unsubscribeThread,+ hasThreadSubscription,isCodexProxyActive,isCodexBrowserUseAvailable,getCodexBrowserUseVersion,@@ -21221,7 +21226,149 @@ describe('CodexAgent resume preparation', () => {});});+describe('CodexAgent native fork anchor events', () => {+ it('attaches the source thread and completed turn to a successful done event', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-native-fork-anchor',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const iterator = handle.events()[Symbol.asyncIterator]();+ const handlers = host.getThreadHandlers();+ if (!handlers) throw new Error('expected thread handlers');++ handlers.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-native-anchor', status: 'completed' },+ });++ await expect(nextEvent(iterator)).resolves.toMatchObject({ type: 'status' });+ await expect(nextEvent(iterator)).resolves.toMatchObject({+ type: 'done',+ agentMeta: {+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: 'start-thread-id',+ kind: 'turn',+ id: 'turn-native-anchor',+ },+ },+ });+ await handle.close();+ });+});+describe('CodexAgent.forkSdkSession', () => {+ it('reuses the shared host and forks directly at a native turn', async () => {+ const prepareCodexResumeSession = vi.fn(async () => {});+ const agent = new CodexAgent(createDeps({}, { prepareCodexResumeSession }));+ const host = installFakeHost(agent, undefined, {+ userAgent: 'mock-codex/0.145.0',+ activeThreadIds: ['source-thread-id'],+ });+ const retireHostKey = vi.spyOn(+ agent as unknown as { retireHostKey: (...args: unknown[]) => Promise<void> },+ 'retireHostKey',+ );++ const result = await agent.forkSdkSession({+ sourceSdkSessionId: 'source-thread-id',+ upToMessageId: undefined,+ lastTurnId: 'turn-at-boundary',+ tailTurnsToDrop: 2,+ workingDir: '/repo',+ });++ expect(host.getHost).toHaveBeenCalledWith(undefined, undefined, {+ ignoreBindingLeases: 1,+ });+ expect(prepareCodexResumeSession).not.toHaveBeenCalled();+ expect(host.request).toHaveBeenCalledTimes(1);+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {+ threadId: 'source-thread-id',+ lastTurnId: 'turn-at-boundary',+ excludeTurns: true,+ cwd: '/repo',+ });+ expect(host.request).not.toHaveBeenCalledWith(Method.ThreadRollback, expect.anything());+ expect(host.unsubscribeThread).toHaveBeenCalledWith('fork-thread-id');+ expect(retireHostKey).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ newSdkSessionId: 'fork-thread-id',+ usedNativeForkAnchor: true,+ });+ });++ it('prepares an unloaded source thread before a native-turn fork', async () => {+ const prepareCodexResumeSession = vi.fn(async () => {});+ const agent = new CodexAgent(createDeps({}, { prepareCodexResumeSession }));+ const host = installFakeHost(agent, undefined, {+ userAgent: 'mock-codex/0.145.0',+ });++ await agent.forkSdkSession({+ sourceSdkSessionId: 'imported-source-thread',+ upToMessageId: undefined,+ lastTurnId: 'turn-at-boundary',+ });++ expect(prepareCodexResumeSession).toHaveBeenCalledWith('imported-source-thread');+ expect(prepareCodexResumeSession.mock.invocationCallOrder[0]).toBeLessThan(+ host.request.mock.invocationCallOrder[0],+ );+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {+ threadId: 'imported-source-thread',+ lastTurnId: 'turn-at-boundary',+ excludeTurns: true,+ });+ });++ it('uses the isolated rollback fallback when bounded native-turn fork is unavailable', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, undefined, { userAgent: 'mock-codex/0.144.6' });++ const result = await agent.forkSdkSession({+ sourceSdkSessionId: 'source-thread-id',+ upToMessageId: undefined,+ lastTurnId: 'turn-at-boundary',+ tailTurnsToDrop: 1,+ });++ expect(host.request).toHaveBeenNthCalledWith(1, Method.ThreadFork, {+ threadId: 'source-thread-id',+ persistExtendedHistory: true,+ });+ expect(host.request).toHaveBeenNthCalledWith(2, Method.ThreadRollback, {+ threadId: 'fork-thread-id',+ numTurns: 1,+ });+ expect(result.usedNativeForkAnchor).toBeUndefined();+ });++ it('fails a precise fork without retiring the shared host when child unload fails', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, undefined, {+ userAgent: 'mock-codex/0.145.0',+ activeThreadIds: ['source-thread-id'],+ });+ host.unsubscribeThread.mockRejectedValueOnce(new Error('unsubscribe failed'));+ const retireHostKey = vi.spyOn(+ agent as unknown as { retireHostKey: (...args: unknown[]) => Promise<void> },+ 'retireHostKey',+ );++ await expect(agent.forkSdkSession({+ sourceSdkSessionId: 'source-thread-id',+ upToMessageId: undefined,+ lastTurnId: 'turn-at-boundary',+ })).rejects.toThrow('unsubscribe failed');++ expect(retireHostKey).not.toHaveBeenCalled();+ expect(host.unsubscribeThread).not.toHaveBeenCalledWith('source-thread-id');+ });+it('prepares an imported source thread before thread/fork', async () => {const order: string[] = [];const prepareCodexResumeSession = vi.fn(async () => {diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 16b5bfe265..ce53a90a31 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -10,7 +10,7 @@* - ✅ Approval: setRequestHandler 接 commandExecution / fileChange RequestApproval* → dispatchInteraction (复用 Claude 那条 PermissionPrompt 通道)* - ✅ 运行时切: setModel / setEffort / setPermissionMode 都生效, 下一 turn 自动透传- * - ✅ Fork: thread/fork + optional thread/rollback → 新 thread_id+ * - ✅ Fork: thread/fork(lastTurnId);旧历史回退 fork + rollback → 新 thread_id* - ✅ oneShot: 走 host 临时 thread (起标题), Phase 4 删 SDK dep 后唯一通路** 输出契约:@@ -363,6 +363,22 @@ function normalizeTailTurnsToDrop(value: number | undefined): number {return Math.max(0, Math.floor(value));}+function normalizeNativeForkTurnId(value: string | undefined): string | undefined {+ const normalized = value?.trim();+ return normalized ? normalized : undefined;+}++function nativeForkAnchorAgentMeta(threadId: string, turnId: string): Record<string, unknown> {+ return {+ nativeForkAnchor: {+ agentKind: 'codex',+ sdkSessionId: threadId,+ kind: 'turn',+ id: turnId,+ },+ };+}+function prefixId(value: string | undefined): string | undefined {return value ? value.slice(0, 8) : undefined;}@@ -559,6 +575,11 @@ function supportsCodexForkExcludeTurns(userAgent: string | undefined): boolean {return codexUserAgentAtLeast(userAgent, [0, 145, 0]);}+/** Direct lastTurnId fork is used only together with the bounded response contract. */+function supportsCodexNativeTurnFork(userAgent: string | undefined): boolean {+ return supportsCodexForkExcludeTurns(userAgent);+}+const READONLY_REFERENCES_PERMISSION_PROFILE = 'cindy-readonly-references';const REVIEW_PERMISSION_PROFILE = 'cindy-review-readonly';const REVIEW_CREDENTIAL_GLOB_DENIES: Record<string, 'deny'> = Object.fromEntries(@@ -9380,6 +9401,7 @@ export class CodexAgent extends BaseAgent {plan: latestPlanByTurn.get(turn.id) ?? null,},source: 'codex',+ agentMeta: nativeForkAnchorAgentMeta(threadId, turn.id),};if (yieldClaim?.state === 'awaiting') {attachYieldContinuationClaim(idleStatusEvent, yieldClaim);@@ -12718,11 +12740,11 @@ export class CodexAgent extends BaseAgent {** 与 Claude 不同:* - Claude fork 可 truncate 到指定 message uuid (sdkForkSession upToMessageId)- * - Codex 协议没有 message uuid 概念; 精确 fork 需要先 fork latest,- * 再对新 thread 调 thread/rollback 从尾部移除 N 个 turn+ * - Codex 新消息保存原生 turn id,直接用 lastTurnId 精确 fork+ * - 老消息没有原生锚点时,仍先 fork latest 再 rollback 尾部 turn*- * opts.upToMessageId 在 Codex 这里被忽略。uuidMap 返回空 — Codex agentMeta 不存- * message uuid, maker 那边也找不到东西可 remap, 不会 break。+ * opts.upToMessageId 在 Codex 这里被忽略。uuidMap 返回空 — Codex 不使用+ * Claude message uuid;原生 turn 锚点由 usedNativeForkAnchor 单独声明可复用。*/private hasLocalCodexHome(): boolean {return Boolean(this.codexHome) && !isRemoteLikePath(this.codexHome ?? '');@@ -12795,9 +12817,106 @@ export class CodexAgent extends BaseAgent {}}+ private async tryForkSdkSessionAtNativeTurn(+ opts: ForkSdkSessionOptions,+ lastTurnId: string,+ credentialMode: AgentCredentialMode | undefined,+ ): Promise<ForkSdkSessionResult | null> {+ const log = this.deps.logger.child('codex/fork');+ const sharedHostKey = hostKey();+ let releaseHostBindingLease: (() => void) | null = null;+ let nativeForkRequestStarted = false;+ const startedAt = Date.now();+ try {+ await this.waitForHostCredentialModeSwitch(sharedHostKey);+ releaseHostBindingLease = this.acquireHostSessionBindingLease(sharedHostKey);+ const hostStartedAt = Date.now();+ const sharedHost = await this.getHost(undefined, credentialMode, {+ ignoreBindingLeases: 1,+ });+ const initResp = await sharedHost.ensureStarted();+ const hostReadyMs = Date.now() - hostStartedAt;+ if (!supportsCodexNativeTurnFork(initResp.userAgent)) {+ log.info('native-turn fork unavailable; using legacy isolated fallback', {+ userAgent: initResp.userAgent ?? null,+ });+ return null;+ }++ if (initResp.codexHome) this.codexHome = initResp.codexHome;+ const prepareStartedAt = Date.now();+ if (!sharedHost.hasThreadSubscription(opts.sourceSdkSessionId)) {+ await this.deps.prepareCodexResumeSession?.(opts.sourceSdkSessionId);+ }+ const prepareMs = Date.now() - prepareStartedAt;+ const forkStartedAt = Date.now();+ nativeForkRequestStarted = true;+ const resp = await sharedHost.request<ThreadForkResponse>(Method.ThreadFork, {+ threadId: opts.sourceSdkSessionId,+ lastTurnId,+ excludeTurns: true,+ ...(opts.workingDir ? { cwd: opts.workingDir } : {}),+ } satisfies ThreadForkParams);+ const threadForkMs = Date.now() - forkStartedAt;+ const newSdkSessionId = resp.thread.id;+ const cleanupStartedAt = Date.now();+ try {+ await sharedHost.unsubscribeThread(newSdkSessionId);+ } catch (error) {+ log.warn('precise fork child cleanup failed', {+ threadId: newSdkSessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ throw error;+ }+ const cleanupMs = Date.now() - cleanupStartedAt;+ log.info('forkSdkSession ◀', {+ newSdkSessionId,+ mode: 'native-turn',+ hostReadyMs,+ prepareMs,+ threadForkMs,+ cleanupMs,+ totalMs: Date.now() - startedAt,+ });+ return {+ newSdkSessionId,+ uuidMap: new Map(),+ usedNativeForkAnchor: true,+ };+ } catch (error) {+ if (nativeForkRequestStarted) throw error;+ log.warn('shared host unavailable before precise fork; using legacy isolated fallback', {+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ } finally {+ releaseHostBindingLease?.();+ }+ }+async forkSdkSession(opts: ForkSdkSessionOptions): Promise<ForkSdkSessionResult> {const log = this.deps.logger.child('codex/fork');const tailTurnsToDrop = normalizeTailTurnsToDrop(opts.tailTurnsToDrop);+ const lastTurnId = normalizeNativeForkTurnId(opts.lastTurnId);+ const forkCredentialMode = resolveAgentCredentialMode({+ agentKind: 'codex',+ providerId: opts.providerId,+ model: opts.model,+ });++ // Keep exact native-turn forks on the regular host so an active source+ // thread is already hydrated. The helper holds a binding lease across the+ // control-plane request and returns null only before a fork is attempted.+ if (lastTurnId && !opts.stripEncryptedReasoning) {+ const nativeForkResult = await this.tryForkSdkSessionAtNativeTurn(+ opts,+ lastTurnId,+ forkCredentialMode,+ );+ if (nativeForkResult) return nativeForkResult;+ }+let stripCopyPath: string | undefined;// 故障半径隔离(2026-08-08 实排):thread/fork 的响应体与源 thread 历史成正比、// 无上界 —— 47MB rollout 实测产出 31MiB 单行 NDJSON,超过 client 16MiB@@ -12831,17 +12950,13 @@ export class CodexAgent extends BaseAgent {log.info('forkSdkSession ▶', {sourceSdkSessionId: opts.sourceSdkSessionId,upToMessageId: opts.upToMessageId,+ lastTurnId,tailTurnsToDrop,stripEncryptedReasoning: opts.stripEncryptedReasoning === true,forkHostKey,note: 'Codex 精确 fork: 独立一次性 host 上 thread/fork 后按需 thread/rollback 新 thread 尾部 turn',});try {- const forkCredentialMode = resolveAgentCredentialMode({- agentKind: 'codex',- providerId: opts.providerId,- model: opts.model,- });const host = await this.getHost(undefined, forkCredentialMode, {keyOverride: forkHostKey,hostPurpose: 'control-plane',diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex eae5c5a1e5..ad3320929e 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -448,6 +448,11 @@ export interface ForkSdkSessionOptions {* Codex 精确 fork 使用 thread/rollback 实现;Claude 路径不消费此字段。*/tailTurnsToDrop?: number;+ /**+ * Codex only: provider-native turn boundary for a direct thread/fork.+ * Old messages omit it and keep using tailTurnsToDrop + rollback.+ */+ lastTurnId?: string;/** 新 session title (可选, 仅给 SDK 写入 jsonl 头)。 */title?: string;/** workingDir — 用于定位 Claude SDK project JSONL 并修复 fork 后的 uuid 引用。 */@@ -476,6 +481,8 @@ export interface ForkSdkSessionResult {* upToMessageId 锚点能在新 jsonl 里查到。*/uuidMap: Map<string, string>;+ /** Codex only: copied native turn ids remain valid in the returned child thread. */+ usedNativeForkAnchor?: boolean;/** Pi-only runtime command catalog captured from the forked runtime, if available. */runtimeCapabilities?: PiRuntimeCapabilityManifest;}