Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 复用暂停回复的持久化身份
DavidShen0eb464d0236f
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 354bde1ea4..99b0b2f652 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -205,7 +205,7 @@ describe('maker:event hot path ordering', () => {).toBeGreaterThan(liveIdleStart);expectOrder(reconcileSource,- 'flushAssistantBlock(sessionId, null);',+ 'sealAssistantBlockForLateFinal(sessionId, null);','consumeLastAssistantPersistId(sessionId);',);expectOrder(@@ -758,7 +758,7 @@ describe('maker:event hot path ordering', () => {expect(reconcileSource).toContain('if (!liveSessionIdle) return false;');expect(reconcileSource).not.toContain('if (!trackerStale && !hadZombieInteraction) return false;');expect(reconcileSource).toContain('confirmed live session idle during turn-boundary reconciliation');- expectOrder(reconcileSource, 'flushAssistantBlock(sessionId, null);', 'consumeLastAssistantPersistId(sessionId);');+ expectOrder(reconcileSource, 'sealAssistantBlockForLateFinal(sessionId, null);', 'consumeLastAssistantPersistId(sessionId);');expectOrder(reconcileSource, 'consumeLastAssistantPersistId(sessionId);', 'consumeLastTopLevelAssistantPersistId(sessionId);');expectOrder(reconcileSource, 'consumeLastTopLevelAssistantPersistId(sessionId);', 'markAssistantTurnFailed(sessionId, abortedBoundaryAssistantPersistId)');expectOrder(reconcileSource, 'sealLostTerminalPersistState(sessionId);', 'sessionTurnActivityTracker.deleteSession(sessionId);');diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex cf8b5d279a..27d1ba8686 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -86,6 +86,7 @@ import {onInteractionResolved,onThinkingEvent,flushAssistantBlock,+ sealAssistantBlockForLateFinal,flushOrphanToolResults,isSuccessfulCodexDoneEventData,onTurnErrorEvent,@@ -2025,6 +2026,93 @@ describe('assistant isFinal burst DUP-SKIP(P1:main 对称去重,防重复 isFina});});+describe('stale-idle assistant late final identity', () => {+ it('reuses the sealed row for the same SDK request after per-turn reset', async () => {+ const meta = { requestId: 'req-stale-idle', uuid: 'assistant-stale-idle' };+ const persistId = onAssistantTextEvent(+ SESSION,+ { text: 'Cindy 能够理解多轮对', isFinal: false },+ meta,+ );+ sealAssistantBlockForLateFinal(SESSION, null);+ expect(consumeLastAssistantPersistId(SESSION)).toBe(persistId);+ expect(consumeLastTopLevelAssistantPersistId(SESSION)).toBe(persistId);+ resetTurnPersistState(SESSION);++ const lateFinalId = onAssistantTextEvent(+ SESSION,+ { text: 'Cindy 能够理解多轮对', isFinal: true, isFullText: true },+ { ...meta, uuid: 'assistant-late-snapshot', stopReason: 'stop_sequence' },+ );+ expect(lateFinalId).toBe(persistId);+ // The late final must not restore the consumed turn target: a paired done+ // still belongs to the stale-idle failure seal rather than a new success.+ expect(consumeLastAssistantPersistId(SESSION)).toBeUndefined();+ expect(consumeLastTopLevelAssistantPersistId(SESSION)).toBeUndefined();++ await flushWrites();+ const assistantCreates = (createMessage as unknown as { mock: { calls: unknown[][] } }).mock.calls+ .filter((c) => (c[1] as { role?: string }).role === 'assistant');+ expect(assistantCreates).toHaveLength(1);+ expect(assistantCreates[0]?.[1]).toEqual(+ expect.objectContaining({ clientId: persistId, content: 'Cindy 能够理解多轮对' }),+ );+ expect(updateMessageContent).not.toHaveBeenCalled();+ expect(patchMessageAgentMetaWithResult).not.toHaveBeenCalled();+ });++ it('updates the same row when the matching late final supplies a longer snapshot', async () => {+ const meta = { requestId: 'req-longer-final', uuid: 'assistant-longer-final' };+ const persistId = onAssistantTextEvent(+ SESSION,+ { text: 'partial', isFinal: false },+ meta,+ );+ sealAssistantBlockForLateFinal(SESSION, null);+ consumeLastAssistantPersistId(SESSION);+ consumeLastTopLevelAssistantPersistId(SESSION);+ resetTurnPersistState(SESSION);++ expect(onAssistantTextEvent(+ SESSION,+ { text: 'partial output', isFinal: true, isFullText: true },+ meta,+ )).toBe(persistId);+ await flushWrites();++ const assistantCreates = (createMessage as unknown as { mock: { calls: unknown[][] } }).mock.calls+ .filter((c) => (c[1] as { role?: string }).role === 'assistant');+ expect(assistantCreates).toHaveLength(1);+ expect(updateMessageContent).toHaveBeenCalledWith(SESSION, persistId, 'partial output');+ expect(patchMessageAgentMetaWithResult).not.toHaveBeenCalled();+ expect(broadcastMessageRow).toHaveBeenCalled();+ });++ it('keeps identical text from a different SDK request as a separate message', async () => {+ const firstId = onAssistantTextEvent(+ SESSION,+ { text: 'same text', isFinal: false },+ { requestId: 'req-first', uuid: 'assistant-first' },+ );+ sealAssistantBlockForLateFinal(SESSION, null);+ consumeLastAssistantPersistId(SESSION);+ consumeLastTopLevelAssistantPersistId(SESSION);+ resetTurnPersistState(SESSION);++ const secondId = onAssistantTextEvent(+ SESSION,+ { text: 'same text', isFinal: true },+ { requestId: 'req-second', uuid: 'assistant-second' },+ );+ expect(secondId).not.toBe(firstId);+ await flushWrites();++ const assistantCreates = (createMessage as unknown as { mock: { calls: unknown[][] } }).mock.calls+ .filter((c) => (c[1] as { role?: string }).role === 'assistant');+ expect(assistantCreates).toHaveLength(2);+ });+});+describe('streamed assistant final calibration', () => {it('persists the authoritative final text even when it is shorter than accumulated deltas', async () => {const persistId = onAssistantTextEvent(diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 06cb5a2d07..1bce782559 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -442,6 +442,7 @@ import {onToolResultFullEvent,onToolUseEvent,preserveTurnPersistStateForBackground,+ sealAssistantBlockForLateFinal,markAutoResumeOutcome,onTurnErrorEvent,prepareSyntheticToolEventForBroadcast,@@ -11631,7 +11632,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const sealLostTerminalPersistState = (sessionId: string): void => {// Same persist boundary as a lost-terminal live-idle reconcile. The next// turn on this sessionId must not append to a half-open streaming block.- flushAssistantBlock(sessionId, null);+ sealAssistantBlockForLateFinal(sessionId, null);const abortedAssistantPersistId = consumeLastAssistantPersistId(sessionId);const abortedBoundaryAssistantPersistId = consumeLastTopLevelAssistantPersistId(sessionId);flushOrphanToolResults(sessionId, null);diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex 17569e9448..5d60d81aeb 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -77,6 +77,35 @@ interface AssistantBlock {}const assistantBlocks = new Map<string, AssistantBlock>();+interface SealedAssistantLateFinalCandidate {+ persistId: string;+ text: string;+ requestId?: string;+ uuid?: string;+}++/**+ * A stale-idle reconcile may persist a half-open block before the SDK's final+ * snapshot drains. Keep that exact SDK identity outside per-turn reset state so+ * the late snapshot can update/reuse the same row instead of creating another.+ */+const sealedAssistantLateFinalBySession = new Map<string, SealedAssistantLateFinalCandidate>();++function matchesSealedAssistantIdentity(+ candidate: SealedAssistantLateFinalCandidate,+ agentMeta: AgentMeta | null,+): boolean {+ if (!agentMeta) return false;+ if (candidate.requestId !== undefined && agentMeta.requestId !== undefined) {+ return candidate.requestId === agentMeta.requestId;+ }+ return (+ candidate.uuid !== undefined &&+ agentMeta.uuid !== undefined &&+ candidate.uuid === agentMeta.uuid+ );+}+const clearBoundaryBySession = new Map<string, number>();export function noteSessionClearBoundary(sessionId: string, clearedAt: string | number | null | undefined): void {@@ -89,6 +118,7 @@ export function noteSessionClearBoundary(sessionId: string, clearedAt: string |const current = clearBoundaryBySession.get(sessionId);if (current === undefined || parsed > current) {clearBoundaryBySession.set(sessionId, parsed);+ sealedAssistantLateFinalBySession.delete(sessionId);// A cleared transcript must not be revived by a late terminal update from an// older background task. New tool calls repopulate this linkage after the boundary.clearAgentTaskPersistState(sessionId);@@ -1675,6 +1705,42 @@ export function onAssistantTextEvent(const isFullText = data.isFullText === true;if (isFinal) {+ const visible = stripInternalWebCitations(rawText);+ const lateFinalCandidate = sealedAssistantLateFinalBySession.get(sessionId);+ if (+ lateFinalCandidate &&+ visible.length > 0 &&+ matchesSealedAssistantIdentity(lateFinalCandidate, agentMeta) &&+ (isFullText ||+ visible === lateFinalCandidate.text ||+ visible.startsWith(lateFinalCandidate.text))+ ) {+ const contentChanged = visible !== lateFinalCandidate.text;+ if (contentChanged) {+ const isCandidateCurrent = () =>+ sealedAssistantLateFinalBySession.get(sessionId) === lateFinalCandidate;+ enqueueWrite(+ `assistant_late_final:${sessionId}:${lateFinalCandidate.persistId}`,+ async (ownerScope) => {+ if (!isCandidateCurrent()) return;+ const updated = await updateDbMessageContent(+ sessionId,+ lateFinalCandidate.persistId,+ visible,+ );+ if (updated && isCandidateCurrent()) {+ lateFinalCandidate.text = visible;+ broadcastMessageRow(sessionId, updated, ownerScope);+ }+ },+ );+ }+ // Do not restore the consumed per-turn Assistant ids here. A paired late+ // done must keep the stale-idle failure seal instead of changing it to a+ // successful turn merely because its final text snapshot arrived late.+ return lateFinalCandidate.persistId;+ }+const block = assistantBlocks.get(sessionId);if (block) {// 流式确认:不落库,留给边界 flush。显式 isFullText 表示 SDK 权威全文;@@ -1691,7 +1757,6 @@ export function onAssistantTextEvent(return block.persistId;}// 非流式 isFinal burst(result 兜底补推也走这):无在飞 block,立即落库。- const visible = stripInternalWebCitations(rawText);if (visible) {// DUP-SKIP(对齐 renderer 老 757-762):若紧邻的上一条已落库消息正是内容完全// 相同的 assistant(典型:重复 isFinal / block flush 后又来同内容补推),复用其@@ -1732,15 +1797,46 @@ export function flushAssistantBlock(sessionId: string,agentMetaFallback: AgentMeta | null = null,): void {+ flushAssistantBlockInternal(sessionId, agentMetaFallback);+}++function flushAssistantBlockInternal(+ sessionId: string,+ agentMetaFallback: AgentMeta | null,+): { persistId: string; text: string; agentMeta: AgentMeta | null } | undefined {const block = assistantBlocks.get(sessionId);- if (!block) return;+ if (!block) return undefined;assistantBlocks.delete(sessionId);const visible = stripInternalWebCitations(block.text);- if (!visible) return;+ if (!visible) return undefined;// 三级兜底,对齐 renderer 老逻辑:本 block 自带 meta → 边界事件 meta(tool_use/done// 同属或携带这条 assistant 的 meta)→ 会话最近一次非空 meta(interaction 边界靠这级)。const meta = block.agentMeta ?? agentMetaFallback ?? lastAgentMetaBySession.get(sessionId) ?? null;enqueuePersistAssistant(sessionId, block.persistId, visible, meta, block.createdAt);+ return { persistId: block.persistId, text: visible, agentMeta: meta };+}++/**+ * Flush a lost-terminal streaming block while retaining its SDK identity for a+ * possible late final snapshot. resetTurnPersistState intentionally leaves this+ * candidate intact; /clear and full session cleanup invalidate it.+ */+export function sealAssistantBlockForLateFinal(+ sessionId: string,+ agentMetaFallback: AgentMeta | null = null,+): void {+ const flushed = flushAssistantBlockInternal(sessionId, agentMetaFallback);+ if (!flushed) return;+ sealedAssistantLateFinalBySession.delete(sessionId);+ const requestId = flushed.agentMeta?.requestId;+ const uuid = flushed.agentMeta?.uuid;+ if (!requestId && !uuid) return;+ sealedAssistantLateFinalBySession.set(sessionId, {+ persistId: flushed.persistId,+ text: flushed.text,+ ...(requestId ? { requestId } : {}),+ ...(uuid ? { uuid } : {}),+ });}/**@@ -1947,6 +2043,7 @@ export function clearCodexPlanRowsForSession(sessionId: string): void {export function clearSessionPersistState(sessionId: string): void {clearCodexPlanRowsForSession(sessionId);assistantBlocks.delete(sessionId);+ sealedAssistantLateFinalBySession.delete(sessionId);backgroundTurnPersistStatesBySession.delete(sessionId);lastAgentMetaBySession.delete(sessionId);knownToolUseIdsBySession.delete(sessionId);