Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): dedupe pending reply alerts across remounts

guyongee3708b5ee92
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
index 2dcb7b0a46..56beaa72d9 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
@@ -421,6 +421,34 @@ describe('agent_task_update workflowProgress', () => {
});
});
+describe('getRunningSnapshot pending request identity', () => {
+ it('publishes a replacement request even while the session remains pending', () => {
+ const sessionId = 'pending-request-identity';
+ const ask = (requestId: string): void => {
+ makerChatStore.__applyStreamEventForTest(sessionId, {
+ sessionId,
+ type: 'ask_user_question',
+ source: 'codex',
+ data: { requestId, questions: [] },
+ } as CCAgentStreamEvent);
+ };
+ try {
+ ask('first');
+ const first = makerChatStore.getRunningSnapshot();
+ expect(first.get(sessionId)?.pendingRequestKeys).toEqual(['ask:first']);
+ expect(makerChatStore.getRunningSnapshot()).toBe(first);
+
+ ask('second');
+ const second = makerChatStore.getRunningSnapshot();
+ expect(second).not.toBe(first);
+ expect(second.get(sessionId)?.pendingRequestKeys).toEqual(['ask:second']);
+ expect(second.get(sessionId)?.hasPendingAskUser).toBe(true);
+ } finally {
+ makerChatStore.purgeSession(sessionId);
+ }
+ });
+});
+
describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
const statusUpdate = (
sessionId: string,
@@ -1060,7 +1088,6 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
window?: { electronAPI?: unknown };
};
const previousWindow = globalWindow.window;
- const previousElectronApi = previousWindow?.electronAPI;
try {
setDataOwnerGeneration('account-a', 1);
makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, true));
diff --git a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts
index 80fb3c0285..0e84ddd17e 100644
--- a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts
+++ b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts
@@ -13,6 +13,7 @@ import {
} from '@/lib/silencedSessionDoneStore';
import { markSessionStarting, resetSessionStartingStoreForTests } from '@/lib/sessionStartingStore';
import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import { noteSessionTurnStartedForAlerts, refreshPendingAlerts } from '@/hooks/usePendingAlertAttention';
import {
addSessionAttention,
@@ -104,6 +105,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {
storeMock.pausedQueueSessions.clear();
resetSilencedSessionDoneStoreForTests();
resetSessionStartingStoreForTests();
+ setDataOwnerGeneration(null);
vi.clearAllMocks();
vi.restoreAllMocks();
vi.useRealTimers();
@@ -642,6 +644,60 @@ describe('useSessionRunningStatus silenced completion handling', () => {
expect(onSessionNeedsReply).toHaveBeenCalledWith('s-setup');
});
+ it('does not repeat an already cleared pending reminder after the sidebar remounts', async () => {
+ setDataOwnerGeneration('remount-owner');
+ const onSessionNeedsReply = vi.fn();
+ const first = renderHook(() => useSessionRunningStatus(undefined, { onSessionNeedsReply }));
+ await emitSnapshot(new Map([['s-remount', {
+ ...status(false), hasPendingAskUser: true, pendingRequestKeys: ['ask:request-1'],
+ }]]));
+ expect(onSessionNeedsReply).toHaveBeenCalledTimes(1);
+ first.result.current.clearNotification('s-remount');
+ first.unmount();
+ vi.mocked(addSessionAttention).mockClear();
+
+ setDataOwnerGeneration('remount-owner', 2);
+ renderHook(() => useSessionRunningStatus(undefined, { onSessionNeedsReply }));
+ expect(onSessionNeedsReply).toHaveBeenCalledTimes(1);
+ expect(addSessionAttention).not.toHaveBeenCalledWith('s-remount', 'awaiting');
+ });
+
+ it('alerts for a different request while the sidebar is hidden, then again for a new owner', async () => {
+ setDataOwnerGeneration('first-owner');
+ const onSessionNeedsReply = vi.fn();
+ const first = renderHook(() => useSessionRunningStatus(undefined, { onSessionNeedsReply }));
+ await emitSnapshot(new Map([['s-pending', {
+ ...status(false), hasPendingPermission: true, pendingRequestKeys: ['permission:request-1'],
+ }]]));
+ first.unmount();
+ await emitSnapshot(new Map([['s-pending', {
+ ...status(false), hasPendingPermission: true, pendingRequestKeys: ['permission:request-2'],
+ }]]));
+ renderHook(() => useSessionRunningStatus(undefined, { onSessionNeedsReply }));
+ expect(onSessionNeedsReply).toHaveBeenCalledTimes(2);
+ await emitSnapshot(new Map([['s-pending', {
+ ...status(false), hasPendingPermission: true, pendingRequestKeys: ['permission:request-2'],
+ }]]));
+ expect(onSessionNeedsReply).toHaveBeenCalledTimes(2);
+ await emitSnapshot(new Map([['s-pending', {
+ ...status(false), hasPendingPermission: true, pendingRequestKeys: ['permission:request-3'],
+ }]]));
+ expect(onSessionNeedsReply).toHaveBeenCalledTimes(3);
+ await emitSnapshot(new Map([
+ ['s-pending', {
+ ...status(false), hasPendingPermission: true, pendingRequestKeys: ['permission:request-3'],
+ }],
+ ['new-task', {
+ ...status(false), hasPendingAskUser: true, pendingRequestKeys: ['ask:new-task-request'],
+ }],
+ ]));
+ expect(onSessionNeedsReply).toHaveBeenCalledTimes(4);
+
+ setDataOwnerGeneration('second-owner');
+ renderHook(() => useSessionRunningStatus(undefined, { onSessionNeedsReply }));
+ expect(onSessionNeedsReply).toHaveBeenCalledTimes(6);
+ });
+
it('clears awaiting attention when resolving a card immediately starts a continuation', async () => {
vi.mocked(getSessionAttentionKind).mockReturnValue('awaiting');
vi.mocked(hasSessionAttention).mockReturnValue(true);
diff --git a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts
index ea5a202263..fb9518a9a7 100644
--- a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts
+++ b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts
@@ -41,6 +41,7 @@
import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
import { makerChatStore } from '@/lib/makerChatStore';
+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import type { SessionStatusInfo } from '@/lib/makerChatStore';
import {
addSessionAttention,
@@ -74,6 +75,12 @@ import {
*/
const QUEUE_DEBOUNCE_MS = 500;
+// Keep only currently pending request IDs across Sidebar remounts. A cleared dot
+// stays cleared for the same request, while a new request can alert immediately.
+// Account switches discard the ledger; settled/deleted tasks are pruned below.
+let pendingReminderOwnerId: string | null = null;
+const notifiedPendingRequests = new Map<string, Set<string>>();
+
interface UseSessionRunningStatusOptions {
/**
* Fired when a session transitions running → done. Filters out errored
@@ -93,7 +100,7 @@ interface UseSessionRunningStatusOptions {
* Fired when a session enters a pending state needing user input
* (`pendingAskUser` / `pendingPermission` / `pendingPlanReview` /
* `pendingPluginSetup`). Rising
- * edge only — re-fires only after the pending state clears and re-enters.
+ * edge fires for a new request (or new input-handoff step) in the session.
* Like onSessionDone, no active-session filter; the consumer decides.
*/
onSessionNeedsReply?: (sessionId: string) => void;
@@ -138,6 +145,8 @@ export function useSessionRunningStatus(
// Track which sessions had pending states last cycle, so we can detect
// when pending states disappear and auto-clear notifications.
const prevPendingRef = useRef(new Set<string>());
+ const prevPendingKeysRef = useRef(new Map<string, Set<string>>());
+ const prevPendingOwnerRef = useRef(getDataOwnerGeneration().dataOwnerId);
/** 本 hook 因 turn 以错误结束而点的红点(新一轮正常结束时据此收掉过期的那颗)。 */
const liveErrorMarkedRef = useRef(new Set<string>());
@@ -332,7 +341,22 @@ export function useSessionRunningStatus(
}
// --- 3. Detect pending ask-user / permission / plan-review / plugin-setup ---
+ const ownerId = getDataOwnerGeneration().dataOwnerId;
+ if (pendingReminderOwnerId !== ownerId) {
+ pendingReminderOwnerId = ownerId;
+ notifiedPendingRequests.clear();
+ }
+ if (prevPendingOwnerRef.current !== ownerId) {
+ prevPendingOwnerRef.current = ownerId;
+ prevPendingRef.current.clear();
+ prevPendingKeysRef.current.clear();
+ }
const currentPendingSet = new Set<string>();
+ const currentPendingKeys = new Map<string, Set<string>>();
+ const previouslyPending = new Set([
+ ...prevPendingRef.current,
+ ...notifiedPendingRequests.keys(),
+ ]);
for (const [id, info] of statusMap) {
if (
info.hasPendingAskUser ||
@@ -343,26 +367,41 @@ export function useSessionRunningStatus(
) {
currentPendingSet.add(id);
const isActive = id === activeSessionId;
- const wasAlreadyPending = prevPendingRef.current.has(id);
- // In-app dot + dock badge: RISING edge only (mirror onSessionNeedsReply
- // below), NOT a per-tick re-derive. A backgrounded session keeps
- // hasPendingX=true until the prompt is answered, so the old
- // `!hasSessionAttention(id)` guard re-added it on every snapshot tick:
- // the moment the user cleared the badge (clicked the session / focused
- // the window → clearAllSessionAttention), the next tick resurrected it,
- // leaving the macOS Dock red dot impossible to clear. Edge-triggering
- // means a cleared badge stays cleared until pending clears and re-enters.
+ const keys = info.pendingRequestKeys;
+ const wasAlreadyPending = keys?.length
+ ? !keys.some((key) =>
+ !notifiedPendingRequests.get(id)?.has(key)
+ && !prevPendingKeysRef.current.get(id)?.has(key))
+ : prevPendingRef.current.has(id);
+ if (keys?.length) currentPendingKeys.set(id, new Set(keys));
+ // A cleared dot stays cleared for the same request across status ticks
+ // and Sidebar remounts, but a new request raises it immediately.
if (!isActive && !wasAlreadyPending) {
- addSessionAttention(id, 'awaiting'); // 待用户回复/选择 → 黄(V5)
+ addSessionAttention(id, 'awaiting');
}
- // System notification callback: rising edge only, no active filter.
- // Same reasoning as onSessionDone — focus state is the consumer's
- // call. Re-firing for the same session requires the pending state
- // to clear and re-enter (prevents repeat-pings).
if (!wasAlreadyPending) {
onSessionNeedsReplyRef.current?.(id);
}
+ // Other hook consumers only read running status. They may add the
+ // in-app dot, but must not consume the system notification owner's edge.
+ if (keys?.length && onSessionNeedsReplyRef.current) {
+ notifiedPendingRequests.set(id, new Set(keys));
+ }
+ }
+ }
+
+ // Keep memory bounded to requests still pending. A request resolved while
+ // Sidebar was unmounted is removed on the next snapshot.
+ for (const [id, seen] of notifiedPendingRequests) {
+ const current = currentPendingKeys.get(id);
+ if (!current) {
+ notifiedPendingRequests.delete(id);
+ continue;
+ }
+ for (const key of seen) {
+ if (!current.has(key)) seen.delete(key);
}
+ if (seen.size === 0) notifiedPendingRequests.delete(id);
}
// --- 4. Auto-clear notifications when pending state disappears ---
@@ -371,7 +410,7 @@ export function useSessionRunningStatus(
// immediately starts a continuation: otherwise the pending falling edge is
// consumed while running, and no later snapshot can clear the stale badge.
// Done/error notifications have separate owners and remain sticky.
- for (const sessionId of prevPendingRef.current) {
+ for (const sessionId of previouslyPending) {
if (
!currentPendingSet.has(sessionId) &&
hasSessionAttention(sessionId) &&
@@ -385,6 +424,7 @@ export function useSessionRunningStatus(
prevRunningRef.current = new Set(currentRunningSet);
prevPendingRef.current = currentPendingSet;
+ prevPendingKeysRef.current = currentPendingKeys;
}, [statusMap, activeSessionId]);
// Unmount cleanup:清掉所有还没 fire 的 done debounce 定时器,避免 hook 卸载后
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 8f0c942846..4978578dc4 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -10129,6 +10129,8 @@ export interface SessionStatusInfo {
hasPendingPluginSetup: boolean;
/** 代输入: owner input requested for an on-screen step (survives the turn). */
hasPendingInputHandoff?: boolean;
+ /** Stable identities for pending interactions; changes even when pending booleans stay true. */
+ pendingRequestKeys?: readonly string[];
}
/**
@@ -10181,6 +10183,30 @@ function scheduleStopTransitionClear(): void {
}, 0);
}
+function pendingRequestKeys(state: SessionChatState): string[] {
+ const keys: string[] = [];
+ if (state.pendingAskUser) keys.push(`ask:${state.pendingAskUser.requestId}`);
+ if (state.pendingPermission) keys.push(`permission:${state.pendingPermission.requestId}`);
+ if (state.pendingPlanReview) keys.push(`plan:${state.pendingPlanReview.requestId}`);
+ const visibleSetup = state.pendingPluginSetup && !state.pendingPluginSetup.terminal
+ ? state.pendingPluginSetup
+ : state.pendingPluginSetupQueue.find((setup) => !setup.terminal);
+ if (visibleSetup) keys.push(`plugin:${visibleSetup.requestId}`);
+ if (isInputHandoffAwaitingOwner(state.pendingInputHandoff)) {
+ const handoff = state.pendingInputHandoff!;
+ keys.push(`handoff:${handoff.requestId}:${handoff.stepNumber}`);
+ }
+ return keys.sort();
+}
+
+function samePendingRequestKeys(
+ left: readonly string[] | undefined,
+ right: readonly string[] | undefined,
+): boolean {
+ if ((left?.length ?? 0) !== (right?.length ?? 0)) return false;
+ return !right?.some((key, index) => left?.[index] !== key);
+}
+
function computeRunningSnapshot(): Map<string, SessionStatusInfo> {
const next = new Map<string, SessionStatusInfo>();
for (const [id, state] of sessions) {
@@ -10192,6 +10218,7 @@ function computeRunningSnapshot(): Map<string, SessionStatusInfo> {
state.pendingPluginSetupQueue,
);
const hasPendingInputHandoff = isInputHandoffAwaitingOwner(state.pendingInputHandoff);
+ const requestKeys = pendingRequestKeys(state);
// 后台 subagent 折算:主 turn 已结束但 wake 型后台任务(local_agent /
// local_workflow)还在跑,或正处于「任务终态 → wake turn 启动」的桥接空窗
@@ -10214,6 +10241,7 @@ function computeRunningSnapshot(): Map<string, SessionStatusInfo> {
hasPendingPlanReview,
hasPendingPluginSetup,
hasPendingInputHandoff,
+ pendingRequestKeys: requestKeys,
});
} else if (
hasPendingAskUser ||
@@ -10232,6 +10260,7 @@ function computeRunningSnapshot(): Map<string, SessionStatusInfo> {
hasPendingPlanReview,
hasPendingPluginSetup,
hasPendingInputHandoff,
+ pendingRequestKeys: requestKeys,
});
}
}
@@ -10256,6 +10285,7 @@ function computeRunningSnapshot(): Map<string, SessionStatusInfo> {
state.pendingPluginSetupQueue,
),
hasPendingInputHandoff: isInputHandoffAwaitingOwner(state.pendingInputHandoff),
+ pendingRequestKeys: pendingRequestKeys(state),
});
}
@@ -10294,7 +10324,8 @@ function getRunningSnapshot(): ReadonlyMap<string, SessionStatusInfo> {
prev.hasPendingPermission !== info.hasPendingPermission ||
prev.hasPendingPlanReview !== info.hasPendingPlanReview ||
prev.hasPendingPluginSetup !== info.hasPendingPluginSetup ||
- !!prev.hasPendingInputHandoff !== !!info.hasPendingInputHandoff
+ !!prev.hasPendingInputHandoff !== !!info.hasPendingInputHandoff ||
+ !samePendingRequestKeys(prev.pendingRequestKeys, info.pendingRequestKeys)
) {
same = false;
break;