Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop,maker-shared): 计划终态按 turnId 存活跨段;终态判据与 main 逐字同序
Kafeifei64bb66227269
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex 3224317c92..37d5313f94 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -270,6 +270,75 @@ describe('update_plan tool_use persistence', () => {});});+ it('still seals after a continuation boundary cleared the per-segment maps', async () => {+ // 分段 turn:S1 产出计划 → continuation done(reset 清空 per-segment 映射)+ // → S2 最终 done。计划行的引用按 turnId 存活,最终 done 仍找得到它并盖章;+ // 否则重载后胶囊无章无失败印记 → 走旧版全勾完兜底 → 永久钉住(review P1-1)。+ const persistId = onToolUseEvent(+ SESSION,+ {+ toolUseId: 'plan:turn-seg',+ toolName: 'update_plan',+ input: { plan: [{ step: 'Segmented work', status: 'in_progress' }] },+ },+ null,+ );++ // continuation boundary 上 register 只跑 resetTurnPersistState(不 persist)。+ resetTurnPersistState(SESSION);++ expect(persistCodexPlanOnDone(SESSION, {+ raw: { id: 'turn-seg', status: 'completed' },+ })).toBe(true);++ await flushWrites();+ expect(updateMessageContent).toHaveBeenCalledWith(+ SESSION,+ persistId,+ expect.objectContaining({+ toolUseId: 'plan:turn-seg',+ toolName: 'update_plan',+ terminalPlanSnapshot: true,+ }),+ );+ });++ it('scopes a terminal-error failure stamp to the owning turn', async () => {+ onToolUseEvent(+ SESSION,+ {+ toolUseId: 'plan:turn-old',+ toolName: 'update_plan',+ input: { plan: [{ step: 'Old turn work', status: 'in_progress' }] },+ },+ null,+ );+ const currentPersistId = onToolUseEvent(+ SESSION,+ {+ toolUseId: 'plan:turn-current',+ toolName: 'update_plan',+ input: { plan: [{ step: 'Current work', status: 'in_progress' }] },+ },+ null,+ );++ expect(persistCodexPlanOnTerminalError(SESSION, 'turn-current')).toBe(true);+ await flushWrites();++ expect(updateMessageContent).toHaveBeenCalledWith(+ SESSION,+ currentPersistId,+ expect.objectContaining({ toolUseId: 'plan:turn-current', turnCompleted: false }),+ );+ // 同会话里其它 turn 的计划行不得被顺手盖失败印记。+ expect(updateMessageContent).not.toHaveBeenCalledWith(+ SESSION,+ expect.anything(),+ expect.objectContaining({ toolUseId: 'plan:turn-old' }),+ );+ });+it('stamps an already-completed plan as terminal at the successful done boundary', async () => {const persistId = onToolUseEvent(SESSION,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex ba3ddadba8..09fd9d3698 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -335,6 +335,7 @@ import {onAssistantTextEvent,onInteractionMessage,onInteractionResolved,+ clearCodexPlanRowsForSession,persistCodexPlanOnDone,persistCodexPlanOnTerminalError,onThinkingEvent,@@ -3846,7 +3847,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidevent.type !== 'done' &&isTerminalTurnErrorEvent(event)) {- persistCodexPlanOnTerminalError(session.id);+ const errorTurnId =+ typeof (event.data as { raw?: { id?: unknown } } | null | undefined)?.raw?.id === 'string'+ ? ((event.data as { raw?: { id?: unknown } }).raw!.id as string)+ : null;+ persistCodexPlanOnTerminalError(session.id, errorTurnId);}if (!isContinuationBoundary && event.source === 'codex' && event.type === 'done') {// Renderer applies this terminal snapshot immediately. Persist the@@ -3866,6 +3871,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void}if (!isContinuationBoundary) {markTurnEndedAfterPersistDrain(session.id);+ // 逻辑 turn 结束:跨段存活的计划行引用到此回收(continuation boundary+ // 上必须保留,否则最终 done 找不到计划行 → 无章无失败印记 → 胶囊永久+ // 钉住,review P1-1)。+ clearCodexPlanRowsForSession(session.id);}resetTurnPersistState(session.id);// sidebar-card-mode: 摘要触发挪到本轮 assistant 块 flush 入队之后(原先在diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex 54d5b3269c..e88e642e2f 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -482,6 +482,22 @@ const toolUseCreatedAtBySession = new Map<string, Map<string, number>>();* 每会话 toolUseId → { toolName, input }。媒体 echo 兜底用:flushOrphanToolResults* 需要按 tool_use 的 input.args 去 mediaToolResultFallback 池里认领结果。*/+/**+ * Codex 计划行的持久化引用,按 `plan:<turnId>` 存活到**产品 turn** 结束。+ *+ * 为什么不能复用 toolUseInfoBySession / updatableToolUsePersistIdBySession:+ * 那两张表是 per-SDK-segment 的,每个 continuation boundary 都会被+ * resetTurnPersistState 清空。分段 turn(S1 产出计划 → continuation done →+ * S2 最终 done)在最终 done 时已经查不到计划行,既不写终态章也不写+ * turnCompleted:false,重载后胶囊走旧版全勾完兜底 → 永久钉住(review P1-1)。+ * 计划行的归属键是 turnId,与 SDK 分段无关,所以单独存一张按 turnId 的表,+ * 只在同一 turnId 被新计划覆盖或 finalize 后清理。+ */+const codexPlanRowByTurnToolUseId = new Map<+ string,+ Map<string, { persistId: string; input: unknown }>+>();+const toolUseInfoBySession = new Map<string, Map<string, { toolName: string; input: unknown }>>();const updatableToolUsePersistIdBySession = new Map<string, Map<string, string>>();@@ -580,6 +596,14 @@ export function onToolUseEvent(if (isUpdatableToolUse(toolName) && toolUseId) {rememberUpdatableToolUsePersistId(sessionId, toolUseId, persistId);}+ // 计划行额外记进按 turnId 的表:它要活过 continuation boundary 的 map 清空,+ // 直到产品 turn 真正结束才用得上(review P1-1)。+ if (toolName === 'update_plan' && toolUseId) {+ getOrCreateSessionMap(codexPlanRowByTurnToolUseId, sessionId).set(toolUseId, {+ persistId,+ input: data.input,+ });+ }notePersistedMessage(sessionId, 'tool_use', persistId);return persistId;}@@ -606,13 +630,19 @@ export function persistCodexPlanOnDone(if (!turnId) return false;const toolUseId = `plan:${turnId}`;+ // 归属键是 turnId,与 SDK 分段无关:优先读活过 continuation boundary 的+ // 按-turn 表,per-segment 表仅作兼容兜底(review P1-1)。+ const planRowMap = codexPlanRowByTurnToolUseId.get(sessionId);+ const planRow = planRowMap?.get(toolUseId);const infoMap = toolUseInfoBySession.get(sessionId);const info = infoMap?.get(toolUseId);- const persistId = updatableToolUsePersistIdBySession.get(sessionId)?.get(toolUseId);- if (!info || info.toolName !== 'update_plan' || !persistId) return false;+ const persistId =+ planRow?.persistId ?? updatableToolUsePersistIdBySession.get(sessionId)?.get(toolUseId);+ const rawInput = planRow?.input ?? (info?.toolName === 'update_plan' ? info.input : undefined);+ if (!persistId) return false;- const input = info.input && typeof info.input === 'object' && !Array.isArray(info.input)- ? info.input as Record<string, unknown>+ const input = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)+ ? rawInput as Record<string, unknown>: null;if (!input || !Array.isArray(input.plan)) return false;@@ -627,7 +657,10 @@ export function persistCodexPlanOnDone(// from an older ordinary DB echo that merely happens to look completed.const terminalPlanAtMs = Date.now();const nextInput = { ...input, plan: nextPlan };- infoMap?.set(toolUseId, { ...info, input: nextInput });+ if (info) infoMap?.set(toolUseId, { ...info, input: nextInput });+ // 终态已定,这份计划行不再需要跨段引用;同时保留最新 input 供同 turn 的+ // 重复 done(罕见)幂等复用。+ planRowMap?.set(toolUseId, { persistId, input: nextInput });enqueueWrite(`codex_plan_done:${sessionId}:${persistId}`, async (ownerScope) => {const updated = await updateDbMessageContent(sessionId, persistId, {toolUseId,@@ -655,17 +688,21 @@ export function persistCodexPlanOnDone(* per-turn maps only ever hold rows belonging to the current turn, so the scope* is exact. Never seals, never touches step statuses.*/-export function persistCodexPlanOnTerminalError(sessionId: string): boolean {- const infoMap = toolUseInfoBySession.get(sessionId);- const idMap = updatableToolUsePersistIdBySession.get(sessionId);- if (!infoMap || !idMap) return false;+export function persistCodexPlanOnTerminalError(sessionId: string, turnId?: string | null): boolean {+ // 按-turn 表跨 continuation 存活,是这里的首选来源(同 persistCodexPlanOnDone)。+ const planRowMap = codexPlanRowByTurnToolUseId.get(sessionId);+ if (!planRowMap || planRowMap.size === 0) return false;+ // turn 归属边界:调用方给出 turnId 时只盖该 turn 的计划行,不误伤同会话里+ // 其它 turn 的行(review P2)。拿不到 turnId(Codex 的 terminal error 常不带)+ // 时退回全表——本会话的未收口计划行本就只应有当前 turn 的那一份。+ const expectedToolUseId = typeof turnId === 'string' && turnId ? `plan:${turnId}` : null;let stamped = false;- for (const [toolUseId, info] of infoMap) {- if (info.toolName !== 'update_plan') continue;- const persistId = idMap.get(toolUseId);+ for (const [toolUseId, planRow] of planRowMap) {+ if (expectedToolUseId && toolUseId !== expectedToolUseId) continue;+ const persistId = planRow.persistId;if (!persistId) continue;- const input = info.input && typeof info.input === 'object' && !Array.isArray(info.input)- ? info.input as Record<string, unknown>+ const input = planRow.input && typeof planRow.input === 'object' && !Array.isArray(planRow.input)+ ? planRow.input as Record<string, unknown>: null;if (!input || !Array.isArray(input.plan)) continue;enqueueWrite(`codex_plan_terminal_error:${sessionId}:${persistId}`, async (ownerScope) => {@@ -1115,6 +1152,9 @@ export function resetTurnPersistState(sessionId: string): void {toolUseCreatedAtBySession.delete(sessionId);toolUseInfoBySession.delete(sessionId);updatableToolUsePersistIdBySession.delete(sessionId);+ // 刻意不清 codexPlanRowByTurnToolUseId:它按 turnId 归属,必须活过每个+ // continuation boundary 的 per-segment 清空(review P1-1)。由+ // clearCodexPlanRowsForSession(逻辑 turn 结束 / 会话清理)负责回收。lastAgentMetaBySession.delete(sessionId);_turnStartedAtBySession.delete(sessionId);_turnDedupIdBySession.delete(sessionId);@@ -1401,7 +1441,16 @@ export function onTurnErrorEvent(}/** session 关闭时清掉该会话所有 per-session 持久化状态,避免 Map 泄漏 / 跨会话串状态。 */+/**+ * 回收按-turn 的计划行引用。逻辑 turn 真正结束(非 continuation boundary 的+ * done / 终止 error 之后)与会话清理时调用——只有到那时跨段引用才不再需要。+ */+export function clearCodexPlanRowsForSession(sessionId: string): void {+ codexPlanRowByTurnToolUseId.delete(sessionId);+}+export function clearSessionPersistState(sessionId: string): void {+ clearCodexPlanRowsForSession(sessionId);assistantBlocks.delete(sessionId);lastAgentMetaBySession.delete(sessionId);knownToolUseIdsBySession.delete(sessionId);diff --git a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsxindex 327bbdddd7..9a355f5f7c 100644--- a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx+++ b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx@@ -103,15 +103,20 @@ export function PinnedPlanPanel({persistedCompletionDeadlineMs !== null && fallbackDeadlineMs !== null? Math.max(persistedCompletionDeadlineMs, fallbackDeadlineMs): (persistedCompletionDeadlineMs ?? fallbackDeadlineMs);+ // 地板只在 effect 里写(render 阶段写 ref 在 StrictMode 双渲染 / 并发渲染下+ // 会读到被上一次渲染污染的值,review P2);render 阶段只读。const deadlineFloorRef = useRef<{ identity: string; deadlineMs: number } | null>(null);- let completionDeadlineMs = rawDeadlineMs;- if (completionDeadlineMs !== null && completionIdentity) {- const floor = deadlineFloorRef.current;- if (floor && floor.identity === completionIdentity) {- completionDeadlineMs = Math.max(completionDeadlineMs, floor.deadlineMs);- }+ const floor = deadlineFloorRef.current;+ const completionDeadlineMs =+ rawDeadlineMs !== null && floor && completionIdentity && floor.identity === completionIdentity+ ? Math.max(rawDeadlineMs, floor.deadlineMs)+ : rawDeadlineMs;+ useEffect(() => {+ if (completionDeadlineMs === null || !completionIdentity) return;+ const current = deadlineFloorRef.current;+ if (current?.identity === completionIdentity && current.deadlineMs >= completionDeadlineMs) return;deadlineFloorRef.current = { identity: completionIdentity, deadlineMs: completionDeadlineMs };- }+ }, [completionDeadlineMs, completionIdentity]);const completedPlanExpired = Boolean(completionDeadlineMs !== null && completionDeadlineMs <= Date.now(),);diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.tsindex a99d33a20b..f28e085fff 100644--- a/packages/maker-shared/src/messageRender.ts+++ b/packages/maker-shared/src/messageRender.ts@@ -633,14 +633,18 @@ export function applyCodexPlanSnapshotOnDone<// 'completed'(main 侧 isSuccessfulCodexDoneEventData 同序判定)。渲染端若// 只看 status 会先盖章退场,随后 main 持久化 turnCompleted:false 的 DB 行// 广播到达,计划复活——即时 UI 与落库分叉。- const sealsTurn = terminalStatus === 'completed' && cancelled !== true && Boolean(turnId);- // done 恒为终态:status 非 completed(interrupted / failed),或 cancelled 覆盖- // 了 completed,均为失败终态——后者只拦盖章不落失败印记的话,全勾完的取消- // 计划会被旧数据兜底即时隐藏,再被 main 的 turnCompleted:false 落库行复活。- const stampsFailed =- Boolean(turnId) &&- ((typeof terminalStatus === 'string' && terminalStatus !== 'completed') ||- (cancelled === true && terminalStatus === 'completed'));+ // 成功判据与 main 的 isSuccessfulCodexDoneEventData 逐字同序:未取消 ++ // raw.status === 'completed'。其余一切(status 为别的值、缺失、被 cancelled+ // 覆盖)在归属明确的 turn 上都是失败终态。+ //+ // "缺失也算失败"很关键:main 对缺 status 的 done 同样写 turnCompleted:false,+ // 若这里不落印记,渲染端会按旧数据兜底先退场,随后落库行带失败印记到达又把+ // 计划判活 → 消失再闪回(review P2)。+ const isSuccessfulTerminal = terminalStatus === 'completed' && cancelled !== true;+ const sealsTurn = isSuccessfulTerminal && Boolean(turnId);+ // terminalStatus === undefined = 调用方没在描述终态(仅套用权威快照的调用),+ // 不落任何印记;null / 其它值都来自真实 done,按失败终态处理。+ const stampsFailed = Boolean(turnId) && terminalStatus !== undefined && !isSuccessfulTerminal;if (!authoritativeSnapshot && !sealsTurn && !stampsFailed) {return { messages, changed: false, toolUseId: null };}