Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): 回退换 thread 时重映射原生锚点, 拒绝跨会话重建回退
ficowang7741750357b1
diff --git a/apps/desktop/src/main/__tests__/rewind.test.ts b/apps/desktop/src/main/__tests__/rewind.test.tsindex eb98e535f0..b007bb3b89 100644--- a/apps/desktop/src/main/__tests__/rewind.test.ts+++ b/apps/desktop/src/main/__tests__/rewind.test.ts@@ -949,7 +949,38 @@ describe('commitRewindAtMessage', () => {expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, lastTurnId: 'turn-9' });const txCall = txCalls.find((c) => c.name === 'rewind.commit');- expect(txCall?.args).toMatchObject({ sdkSessionId: 'fork-thread-id' });+ // 换出新 thread:保留消息的原生锚点在同一事务里重映射到新 thread。+ expect(txCall?.args).toMatchObject({+ sdkSessionId: 'fork-thread-id',+ nativeForkAnchorSessionMap: [['codex-thread-old', 'fork-thread-id']],+ });+ });++ it('Codex: does not request anchor remap when the thread id is unchanged (#4423)', async () => {+ useFakeSession('codex');+ commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'codex-thread-old' });+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);+ selectQueue.push([]);+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ selectQueue.push([]);+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);++ await commitRewindAtMessage('sess-1', 'client-id');++ const txCall = txCalls.find((c) => c.name === 'rewind.commit');+ expect(txCall?.args).not.toHaveProperty('nativeForkAnchorSessionMap');+ });++ it('Codex: 目标在 context_rebuild 边界之前 → REWIND_UNSUPPORTED_HISTORY,SDK 与 DB 均未执行 (#4423)', async () => {+ useFakeSession('codex');+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]); // target user msg+ selectQueue.push([{ rowid: 11 }]); // agent_switch / context_rebuild 边界守卫命中++ await expect(commitRewindAtMessage('sess-1', 'client-id')).rejects.toMatchObject({+ code: 'REWIND_UNSUPPORTED_HISTORY',+ });+ expect(commitRewindFilesMock).not.toHaveBeenCalled();+ expect(txCalls).toHaveLength(0);});it('Codex: falls back to the last model-output timestamp when no native anchor is persisted (#4421)', async () => {diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 77eb0340ba..c544cde739 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -1145,6 +1145,55 @@ describe('db worker tx handlers', () => {},);+ it('rewind.commit remaps surviving native fork anchors to the replacement thread', async () => {+ await withClient(async (client) => {+ await seedSession(client, 's1');+ const keptMeta = JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: { agentKind: 'codex', kind: 'turn', sdkSessionId: 'thread-old', id: 'turn-1' },+ });+ const foreignMeta = JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: { agentKind: 'codex', kind: 'turn', sdkSessionId: 'thread-other', id: 'turn-x' },+ });+ const droppedMeta = JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: { agentKind: 'codex', kind: 'turn', sdkSessionId: 'thread-old', id: 'turn-2' },+ });+ await client.exec(+ 'INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, created_at) VALUES (?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?)',+ [+ 'm1', 'c1', 's1', 'assistant', 'kept', keptMeta, 100,+ 'm2', 'c2', 's1', 'assistant', 'foreign', foreignMeta, 150,+ 'm3', 'c3', 's1', 'user', 'target', null, 200,+ 'm4', 'c4', 's1', 'assistant', 'dropped', droppedMeta, 300,+ ],+ );++ await client.tx('rewind.commit', {+ sessionId: 's1',+ targetCreatedAt: 200,+ sdkSessionId: 'thread-new',+ nativeForkAnchorSessionMap: [['thread-old', 'thread-new']],+ now: 999,+ });++ const rows = await client.query('SELECT id, rewind_at, agent_meta FROM messages ORDER BY id') as Array<{+ id: string; rewind_at: number | null; agent_meta: string | null;+ }>;+ expect(rows.map((r) => [r.id, r.rewind_at])).toEqual([+ ['m1', null], ['m2', null], ['m3', 999], ['m4', 999],+ ]);+ expect(JSON.parse(rows[0]!.agent_meta!)).toEqual({+ turnCompleted: true,+ nativeForkAnchor: { agentKind: 'codex', kind: 'turn', sdkSessionId: 'thread-new', id: 'turn-1' },+ });+ // 异线程锚点与被软删的行都不动。+ expect(rows[1]!.agent_meta).toBe(foreignMeta);+ expect(rows[3]!.agent_meta).toBe(droppedMeta);+ });+ });+it('rewind.commit uses target message id to avoid same-timestamp over-delete', async () => {await withClient(async (client) => {await seedSession(client, 's1');diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 65302bdb80..a040ee7730 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -111,6 +111,12 @@ export interface RewindCommitArgs {preserveMessageUuid?: string;/** Replacement SDK session/thread id to persist atomically with rewind. */sdkSessionId?: string;+ /**+ * Codex thread/rollback 或分页 fork 换出新 thread 时,把保留消息 agent_meta 里+ * `nativeForkAnchor.sdkSessionId` 从旧 thread 重映射到新 thread(pairs,语义同+ * fork.session 的同名字段),否则后续回退/fork 会把这些锚点当异线程丢弃。+ */+ nativeForkAnchorSessionMap?: Array<[string, string]>;now: number;}diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex c1adafa2d3..f7bb759019 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -2159,6 +2159,9 @@ function rewindCommit(db: Database.Database, args: unknown): void {const sdkSessionId =typeof payload.sdkSessionId === 'string' && payload.sdkSessionId ? payload.sdkSessionId : null;const requireLatestUser = payload.requireLatestUser === true;+ const nativeForkAnchorSessionMap = normalizeNativeForkAnchorSessionMap(+ payload.nativeForkAnchorSessionMap,+ );const now = expectNumber(payload.now, 'now');const rows = db.prepare(@@ -2213,8 +2216,19 @@ function rewindCommit(db: Database.Database, args: unknown): void {AND started_at >= ?`,): null;+ const updateAgentMeta = db.prepare('UPDATE messages SET agent_meta = ? WHERE id = ?');const transaction = db.transaction(() => {for (const id of idsToRewind) updateMessage.run(now, id);+ // 保留下来的消息若持有旧 thread 的原生 turn 锚点,随 thread 替换一起重映射+ // (与 fork.session 复制消息时的处理一致),软删与重映射同一事务。+ if (nativeForkAnchorSessionMap.size > 0) {+ const rewoundIds = new Set(idsToRewind);+ for (const row of rows) {+ if (rewoundIds.has(row.id) || !row.agent_meta) continue;+ const remapped = remapNativeForkAnchorSession(row.agent_meta, nativeForkAnchorSessionMap);+ if (remapped !== row.agent_meta) updateAgentMeta.run(remapped, row.id);+ }+ }if (rewindSubagentByParent && rewindParentlessSubagentTail) {const rewoundIds = new Set(idsToRewind);const parentToolUseIds = new Set(@@ -3443,6 +3457,29 @@ function remapForkedAgentMeta(return JSON.stringify(next);}+/** 只重映射 nativeForkAnchor.sdkSessionId,不动 uuid / parent 链(rewind 不复制消息)。 */+function remapNativeForkAnchorSession(raw: string, map: Map<string, string>): string {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return raw;+ }+ if (!isRecord(parsed)) return raw;+ const nativeForkAnchor = parsed.nativeForkAnchor;+ if (+ !isRecord(nativeForkAnchor) ||+ nativeForkAnchor.agentKind !== 'codex' ||+ nativeForkAnchor.kind !== 'turn' ||+ typeof nativeForkAnchor.sdkSessionId !== 'string'+ ) {+ return raw;+ }+ const mapped = map.get(nativeForkAnchor.sdkSessionId);+ if (!mapped || mapped === nativeForkAnchor.sdkSessionId) return raw;+ return JSON.stringify({ ...parsed, nativeForkAnchor: { ...nativeForkAnchor, sdkSessionId: mapped } });+}+function normalizeStringSet(value: unknown, label: string): Set<string> {if (value === undefined) return new Set();return new Set(expectArray(value, label).map((item, index) => expectString(item, `${label}.${index}`)));diff --git a/apps/desktop/src/main/maker-orchestration/rewind.ts b/apps/desktop/src/main/maker-orchestration/rewind.tsindex 551e9ca3a0..d40aba44c8 100644--- a/apps/desktop/src/main/maker-orchestration/rewind.ts+++ b/apps/desktop/src/main/maker-orchestration/rewind.ts@@ -21,7 +21,7 @@* tailTurnsToDrop 调 thread/rollback。*/-import { and, asc, desc, eq, gt, gte, isNull, lt, or, sql } from 'drizzle-orm';+import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm';import { getDbClient } from '../localDb/client/current';import { sessions, messages } from '../localDb/schema';@@ -226,13 +226,18 @@ async function loadRewindContext(// agent_switch 行 = target 属于上一个引擎时代——当前引擎的原生会话里没有那些// turn 的锚点(Claude 的 assistant uuid / Codex 的 tail turn 计数都会错配),// 强行执行要么报错要么错删。v1 每次切换重新交接,不保留切回指针,故直接拒绝。+ // Codex / Pi 还要拦 context_rebuild(原生会话重建):重建后的 live thread 里没有+ // 重建前那些 turn,按 tail turn 数 rollback 或按边界 fork 都对不上目标(#4423+ // review P1)。Claude 路径按 assistant uuid 锚点回退,不在此处拦。+ const boundaryRoles: Array<'agent_switch' | 'context_rebuild'> =+ agentKind === 'claude-code' ? ['agent_switch'] : ['agent_switch', 'context_rebuild'];const [boundaryAfterTarget] = await db.select({ rowid: messageRowid }).from(messages).where(and(eq(messages.sessionId, sessionId),- eq(messages.role, 'agent_switch'),+ inArray(messages.role, boundaryRoles),isNull(messages.rewindAt),or(gt(messages.createdAt, target.createdAt),@@ -244,7 +249,7 @@ async function loadRewindContext(if (boundaryAfterTarget) {throw rewindError('REWIND_UNSUPPORTED_HISTORY',- '目标消息在引擎切换边界之前,当前引擎的会话历史无法回滚到那里',+ '目标消息在引擎切换或会话重建边界之前,当前引擎的会话历史无法回滚到那里',);}@@ -572,7 +577,7 @@ async function loadCodexRewindNativeBoundary(sessionId: string,ctx: Pick<RewindContext, 'targetCreatedAt' | 'targetRowid'>,liveSdkSessionId: string | undefined,-): Promise<{ lastTurnId?: string; forkAtTimestampMs?: number }> {+): Promise<{ sdkSessionId?: string; lastTurnId?: string; forkAtTimestampMs?: number }> {const currentSessionMeta = await getMaker().getSessionMeta(sessionId);const sdkSessionId =activeSdkSessionId(liveSdkSessionId) ??@@ -600,9 +605,9 @@ async function loadCodexRewindNativeBoundary(.limit(200);const rows = [...recent].reverse();const lastTurnId = resolveCodexTurnAnchor(rows, sdkSessionId);- if (lastTurnId) return { lastTurnId };+ if (lastTurnId) return { sdkSessionId, lastTurnId };const forkAtTimestampMs = resolveCodexForkEventTimestamp(rows);- return forkAtTimestampMs !== undefined ? { forkAtTimestampMs } : {};+ return forkAtTimestampMs !== undefined ? { sdkSessionId, forkAtTimestampMs } : { sdkSessionId };}export async function commitRewindAtMessage(@@ -622,11 +627,12 @@ export async function commitRewindAtMessage(// userUuid 缺失 (老消息) 时跳 SDK 文件回滚, 直接进 DB 段; ctx.assistantUuid 设进// pendingRewindTo, 下次 send 仍走三件套 (forkSession=true CLI 端兜底回滚)。let rewindResult: Awaited<ReturnType<typeof makerSession.commitRewindFiles>> | undefined;+ let nativeForkAnchorSessionMap: Array<[string, string]> | undefined;if (ctx.agentKind === 'codex' || ctx.agentKind === 'pi') {const filePlan = await buildCodexFilePlanForSession(sessionId, clientId, ctx.codexUserMessages ?? [], makerSession);// Codex 分页线程拒绝 thread/rollback(#4421):把 target 之前的原生 turn 边界// (持久化锚点或事件时间戳)一并交给 maker-core,遇拒绝时改走 thread/fork。- const nativeBoundary =+ const { sdkSessionId: previousSdkSessionId, ...nativeBoundary } =ctx.agentKind === 'codex'? await loadCodexRewindNativeBoundary(sessionId, ctx, makerSession.sdkSessionId): {};@@ -654,6 +660,17 @@ export async function commitRewindAtMessage(logCompensationError(compErr, execution.rollbackCommit),});rewindResult = result.threadRollback;+ // thread/rollback 或分页 fork 换出新 thread id 时,保留消息里的 nativeForkAnchor+ // 仍指向旧 thread,下一次回退/fork 会把它们判为异线程锚点丢弃(#4423 review+ // P2)。与 fork.session 一样在同一事务里把 sdkSessionId 重映射到新 thread。+ if (+ ctx.agentKind === 'codex' &&+ previousSdkSessionId &&+ rewindResult?.sdkSessionId &&+ rewindResult.sdkSessionId !== previousSdkSessionId+ ) {+ nativeForkAnchorSessionMap = [[previousSdkSessionId, rewindResult.sdkSessionId]];+ }} else if (ctx.userUuid) {rewindResult = await makerSession.commitRewindFiles(ctx.userUuid, ctx.assistantUuid!);} else {@@ -685,6 +702,7 @@ export async function commitRewindAtMessage(sdkSessionId: rewindResult?.sdkSessionId,now,...(opts?.requireLatestUser ? { requireLatestUser: true } : {}),+ ...(nativeForkAnchorSessionMap ? { nativeForkAnchorSessionMap } : {}),});if (ctx.assistantUuid) {setLastAssistantTranscriptUuid(sessionId, ctx.assistantUuid);