Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): close completion notification races
Dash0af37d3ebc8d
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex 53c444c9a4..e27ab1a68f 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -561,6 +561,40 @@ describe('makerChatStore text delta batching', () => {unsubscribe();});+ it('records an unexpected annotation materialization failure as a terminal error', async () => {+ let annotationReads = 0;+ const attachment = {+ id: 'broken-annotation',+ name: 'broken.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: 'xdt-image://source/broken.png',+ get annotationStrokes() {+ annotationReads += 1;+ if (annotationReads === 1) return [{}];+ throw new Error('annotation materialization failed');+ },+ } as AttachedFile;++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'annotated send',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [attachment],+ ),+ ).rejects.toThrow('annotation materialization failed');++ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBe('annotation materialization failed');+ expect(makerChatStore.hasSessionTerminalError(SESSION_ID)).toBe(true);+ });+it('drops stale ghost pushes before they mutate the current owner slice', () => {const staleOwnerStamp = { dataOwnerId: 'owner-b', ownerGeneration: 1 };const currentOwnerStamp = { dataOwnerId: 'owner-a', ownerGeneration: 1 };diff --git a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.tsindex 70fa348617..0745c1847c 100644--- a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts+++ b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts@@ -368,7 +368,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {});expect(vi.mocked(addSessionAttention)).not.toHaveBeenCalledWith('session-running', 'done');- expect(onSessionDone).toHaveBeenCalledWith('session-running');+ expect(onSessionDone).not.toHaveBeenCalled();});it('does not restore done attention while the next turn is starting', async () => {@@ -384,7 +384,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {});expect(vi.mocked(addSessionAttention)).not.toHaveBeenCalledWith('session-starting', 'done');- expect(onSessionDone).toHaveBeenCalledWith('session-starting');+ expect(onSessionDone).not.toHaveBeenCalled();});it('restores deferred done attention when starting clears without a new run', async () => {@@ -435,7 +435,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {'session-terminal-start-failure','done',);- expect(onSessionDone).toHaveBeenCalledTimes(1);+ expect(onSessionDone).not.toHaveBeenCalled();});it('drops deferred done attention when starting becomes a real run', async () => {@@ -454,7 +454,30 @@ describe('useSessionRunningStatus silenced completion handling', () => {await emitSnapshot(new Map([['session-started', status(true)]]));expect(vi.mocked(addSessionAttention)).not.toHaveBeenCalledWith('session-started', 'done');- expect(onSessionDone).toHaveBeenCalledTimes(1);+ expect(onSessionDone).not.toHaveBeenCalled();+ });++ it('does not emit stale done when a failed start has already recorded a terminal error', async () => {+ vi.useFakeTimers();+ const onSessionDone = vi.fn();+ renderHook(() => useSessionRunningStatus(undefined, { onSessionDone }));++ await emitSnapshot(new Map([['session-preparation-error', status(true)]]));+ await emitSnapshot(new Map([['session-preparation-error', status(false)]]));+ storeMock.terminalErrorSessions.add('session-preparation-error');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(500);+ });++ expect(vi.mocked(addSessionAttention)).toHaveBeenCalledWith(+ 'session-preparation-error',+ 'error',+ );+ expect(vi.mocked(addSessionAttention)).not.toHaveBeenCalledWith(+ 'session-preparation-error',+ 'done',+ );+ expect(onSessionDone).not.toHaveBeenCalled();});it('coalesces multiple queue-drain transitions into a single final notification', async () => {diff --git a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.tsindex 6574b89c87..8e17351812 100644--- a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts+++ b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts@@ -76,11 +76,11 @@ function hasPendingInteraction(info: SessionStatusInfo | undefined): boolean {interface UseSessionRunningStatusOptions {/**- * Fired when a session transitions running → done. Filters out errored- * sessions only — does NOT filter out the active session, because the- * "should we actually notify the user" decision (focus state, etc.) is- * the consumer's. The in-app dot still skips active session via its own- * branch; the callback fires for any non-error done.+ * Fired after a session transitions running → done and remains idle through+ * the queue debounce. A next turn that is already running or starting+ * suppresses the stale completion; a failed optimistic start restores it.+ * Active-session focus remains the consumer's decision, while the in-app dot+ * separately skips completions the user already viewed.*/onSessionDone?: (sessionId: string) => void;/**@@ -99,6 +99,13 @@ interface UseSessionRunningStatusOptions {onSessionNeedsReply?: (sessionId: string) => void;}+interface DeferredStartingCompletion {+ /** Whether the in-app done attention was still eligible when debounce expired. */+ restoreAttention: boolean;+ /** Scheduler-owned runs keep their external completion notification suppressed. */+ notify: boolean;+}+/*** @param activeSessionId - The currently viewed session ID (from URL match).* @param options - Optional callbacks for transition side effects.@@ -148,10 +155,12 @@ export function useSessionRunningStatus(new Map<string, ReturnType<typeof setTimeout>>(),);- // debounce 到期时下一轮仍处于 starting,先暂缓上一轮 done 角标。starting- // 若随后失败 / 暂停 / TTL 清除且没有权威运行态,再恢复该角标;成功进入- // running 则丢弃。系统通知 callback 已在 debounce 到期时触发,这里只补角标。- const pendingStartingDoneAttentionRef = useRef(new Set<string>());+ // debounce 到期时下一轮仍处于 starting,把上一轮 done 角标与系统通知一起+ // 暂缓。starting 若随后失败 / 暂停 / TTL 清除且没有权威运行态,再恢复;+ // 成功进入 running 则两者一起丢弃,避免新一轮已经开始后补发旧完成通知。+ const pendingStartingCompletionsRef = useRef(+ new Map<string, DeferredStartingCompletion>(),+ );const notifications = useSessionAttentionSnapshot();@@ -162,7 +171,7 @@ export function useSessionRunningStatus(// starting 是乐观态,可能以失败 / 暂停结束而从未进入 running。若 debounce// 期间因此抑制了上一轮 done,starting 清除后必须按当前权威状态收口。- for (const sessionId of pendingStartingDoneAttentionRef.current) {+ for (const [sessionId, deferred] of pendingStartingCompletionsRef.current) {const cur = statusMap.get(sessionId);const hasError = makerChatStore.hasSessionTerminalError(sessionId);const isActive = sessionId === activeSessionId;@@ -172,17 +181,20 @@ export function useSessionRunningStatus(// deferred done 升级成 error。权威终止错误一旦存在就立即收口为红点,// 也不受 active / starting 抑制(done 才有「正在看就不亮」语义)。if (hasError) {- pendingStartingDoneAttentionRef.current.delete(sessionId);+ pendingStartingCompletionsRef.current.delete(sessionId);addSessionAttention(sessionId, 'error');continue;}- if (isActive || isRunning || stillPending) {- pendingStartingDoneAttentionRef.current.delete(sessionId);+ if (isRunning) {+ pendingStartingCompletionsRef.current.delete(sessionId);continue;}if (startingSessionIds.has(sessionId)) continue;- pendingStartingDoneAttentionRef.current.delete(sessionId);- addSessionAttention(sessionId, 'done');+ pendingStartingCompletionsRef.current.delete(sessionId);+ if (deferred.restoreAttention && !isActive && !stillPending) {+ addSessionAttention(sessionId, 'done');+ }+ if (deferred.notify) onSessionDoneRef.current?.(sessionId);}// --- 1. Detect new turn starts ---@@ -281,13 +293,21 @@ export function useSessionRunningStatus(const isRunning = cur?.isRunning === true;const isStarting = getStartingSessionIds().has(sessionId);const stillPending = hasPendingInteraction(cur);- if (!wasActiveAtCompletion && !isActive && !isRunning && !stillPending) {- if (isStarting) {- pendingStartingDoneAttentionRef.current.add(sessionId);- } else {- addSessionAttention(sessionId, 'done');- }+ const hasError = makerChatStore.hasSessionTerminalError(sessionId);+ if (hasError) {+ addSessionAttention(sessionId, 'error');+ return;+ }+ if (isRunning) return;+ const restoreAttention = !wasActiveAtCompletion && !isActive && !stillPending;+ if (isStarting) {+ pendingStartingCompletionsRef.current.set(sessionId, {+ restoreAttention,+ notify: !notificationOwnedByScheduler,+ });+ return;}+ if (restoreAttention) addSessionAttention(sessionId, 'done');if (!notificationOwnedByScheduler) onSessionDoneRef.current?.(sessionId);}, QUEUE_DEBOUNCE_MS);pendingDoneTimersRef.current.set(sessionId, timer);@@ -355,7 +375,7 @@ export function useSessionRunningStatus(return () => {for (const t of timers.values()) clearTimeout(t);timers.clear();- pendingStartingDoneAttentionRef.current.clear();+ pendingStartingCompletionsRef.current.clear();};}, []);diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex e3051bc4af..6582478bf6 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -12309,6 +12309,19 @@ function isRemoteMediaSession(sessionId: string): boolean {return Boolean(getOrCreateState(sessionId).remoteHostId ?? getStickySessionDeviceId(sessionId));}+/** 发送前准备失败也属于本轮终止错误,供错误横幅与侧栏红点读取。 */+function recordSendPreparationError(sessionId: string, error: unknown): void {+ const message = decodeRemoteErrorMessage(error instanceof Error ? error.message : String(error));+ setState(sessionId, (s) => ({+ ...s,+ error: message,+ usageLimitRecovery: null,+ errorReason: null,+ recoverableError: null,+ errorRetryText: null,+ }));+}+/*** 共享发送边界:同步完成「无切换在途」检查与发送 token 登记,并保证同步抛错和* Promise settle 两条路径都会释放。`task` 仍在当前调用栈内启动,保留 sendMessage@@ -12447,6 +12460,9 @@ function sendMessage(null,materializeAnnotatedAttachmentsForSend(files, sessionId, {stripAnnotationMeta: isRemoteMediaSession(sessionId),+ }).catch((error) => {+ recordSendPreparationError(sessionId, error);+ throw error;}),(prepared) =>sendMessageCore(