Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 静默自动任务的多 turn run 不再漏发系统通知 (#936)
Dash6ef5a3e95d43
diff --git a/apps/desktop/src/main/maker-ipc/schedule.ts b/apps/desktop/src/main/maker-ipc/schedule.tsindex 40da1135ca..16b5ef4db3 100644--- a/apps/desktop/src/main/maker-ipc/schedule.ts+++ b/apps/desktop/src/main/maker-ipc/schedule.ts@@ -484,8 +484,19 @@ export function registerScheduleHandlers(getMaker?: () => Maker | null): void {return withScheduler(({ scheduler }) => scheduler.listRuns(id, lim));});+ // 一并回传引擎的 in-flight runId 快照:renderer 的通知抑制标记要靠它区分「DB 里查不到+ // 这条 run」的两种含义 —— 已结束并被清理,还是自删除场景下行已消失却仍在跑(见+ // scheduler.listInflightRunIds 的注释)。runId 本身不是特权数据(renderer 的标记里就+ // 存着它)。+ //+ // 注意这**不是**原子快照:两次读之间隔着 DB 查询的 await,run 恰好在那个窗口内结束时+ // 会出现「行还是 running、controller 已注销」。消费方(reconcileRunMarkers)能识别这种+ // 不一致并安排一次重查,所以这里不为它忙等重采样。ipcMain.handle(MAKER_INVOKE.SCHEDULE_LIST_SIDEBAR_INDEX_RUNS, async () =>- withScheduler(({ storage }) => storage.listSidebarIndexRuns()),+ withScheduler(async ({ storage, scheduler }) => ({+ runs: await storage.listSidebarIndexRuns(),+ inflightRunIds: scheduler.listInflightRunIds(),+ })),);ipcMain.handle(MAKER_INVOKE.SCHEDULE_LIST_COST_SUMMARIES, async () =>diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 725ba95f81..ca3e3fbca0 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4781,7 +4781,11 @@ contextBridge.exposeInMainWorld('electronAPI', {} | UtilityTextFailure> => ipcRenderer.invoke('maker:schedule:generate-pre-run-hook', params),listRuns: (id: string, limit?: number): Promise<unknown[]> =>ipcRenderer.invoke('maker:schedule:list-runs', id, limit),- listSidebarIndexRuns: (): Promise<unknown[]> =>+ // 回传 { runs, inflightRunIds }:后者是引擎内存里的权威 in-flight 集合,renderer 的+ // 通知抑制标记对账靠它区分「runs 里查不到 = 跑完了」与「= 自删除后行已级联删除、+ // run 仍在跑」。两者不是原子快照,不一致由消费方重查收口(见 main 侧 handler 注释)。+ // runId 不是特权数据(renderer 的标记里就存着它)。+ listSidebarIndexRuns: (): Promise<unknown> =>ipcRenderer.invoke('maker:schedule:list-sidebar-index-runs'),listCostSummaries: (): Promise<unknown[]> =>ipcRenderer.invoke('maker:schedule:list-cost-summaries'),diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.tsindex b96a41cdef..ab996c367e 100644--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts@@ -865,7 +865,10 @@ describe('automation-generated sessions', () => {);const preloadSource = readTextLf(new URL('../../preload/preload.ts', import.meta.url), 'utf8');- expect(scheduleIndexHookSource).toContain('loadScheduleSidebarIndexRuns()');+ // 这个 hook 取 snapshot 变体:除了 run 列表还要引擎的 in-flight 集合,用于通知抑制+ // 标记的对账(见 scheduleSidebarIndexRuns 与 scheduler.listInflightRunIds)。两者是+ // 同一条 sidebar index IPC,本用例要锁的「不走 per-schedule history limit」不变。+ expect(scheduleIndexHookSource).toContain('loadScheduleSidebarIndexSnapshot()');expect(scheduleIndexHookSource).not.toContain('RUNS_PER_SCHEDULE_LIMIT');expect(scheduleIndexHookSource).not.toContain('listRuns(');expect(unreadCountsHookSource).toContain('loadScheduleSidebarIndexRuns()');diff --git a/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts b/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.tsindex baabd4fb27..a11bd4e4cd 100644--- a/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts+++ b/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts@@ -1,5 +1,5 @@// @vitest-environment jsdom-import { act, renderHook } from '@testing-library/react';+import { act, renderHook, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { SchedulerEvent } from '@cindy/maker-scheduler';@@ -10,8 +10,11 @@ import {hasSessionAttention,} from '@/lib/sessionAttentionStore';import {- observeNextSessionTerminalNotificationOwnedByScheduler,- observeNextSessionDoneSilenced,+ isSessionTerminalNotificationOwnedByScheduler,+ isSessionDoneSilenced,+ MARKER_TERMINAL_LINGER_MS,+ markNextSessionDoneSilenced,+ markNextSessionTerminalNotificationOwnedByScheduler,resetSilencedSessionDoneStoreForTests,} from '@/lib/silencedSessionDoneStore';@@ -56,7 +59,7 @@ describe('useAutomationScheduleSessionIndex silence events', () => {});});- expect(observeNextSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);});it('registers silenced runs without clearing older session attention', () => {@@ -86,7 +89,7 @@ describe('useAutomationScheduleSessionIndex silence events', () => {});expect(hasSessionAttention('session-1')).toBe(true);- expect(observeNextSessionDoneSilenced('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(true);});it('clears silenced done suppression when the run requests notification', () => {@@ -113,8 +116,8 @@ describe('useAutomationScheduleSessionIndex silence events', () => {});});- expect(observeNextSessionDoneSilenced('session-1')).toBe(false);- expect(observeNextSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);});it('clears only attention that could have been created by the silenced run fallback', () => {@@ -165,7 +168,7 @@ describe('useAutomationScheduleSessionIndex silence events', () => {});});- expect(observeNextSessionDoneSilenced('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(true);});it('does not clear older attention when completed supplies the first silenced sessionId', () => {@@ -189,6 +192,288 @@ describe('useAutomationScheduleSessionIndex silence events', () => {});expect(hasSessionAttention('session-1')).toBe(true);- expect(observeNextSessionDoneSilenced('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(true);+ });+});++/**+ * 事件丢失的自愈:refresh 拉到的 sidebar run 列表就是 scheduler 落库的权威状态+ * (且包含所有带 sessionId 的 run,没有 history limit),据它对账标记。+ * 刻意不用定时器猜 run 是否还在飞行 —— 三种判据(事件序 / renderer running 快照 /+ * 固定时长)都被证明会误判,见 silencedSessionDoneStore 的文件头注释。+ */+describe('useAutomationScheduleSessionIndex marker reconciliation', () => {+ function stubApiWithRuns(runs: unknown[], inflightRunIds: string[] = []): void {+ vi.stubGlobal('electronAPI', {+ maker: {+ schedule: {+ listSidebarIndexRuns: vi.fn().mockResolvedValue({ runs, inflightRunIds }),+ onEvent: vi.fn(() => () => undefined),+ },+ },+ notificationMarkSessionAttention: vi.fn().mockResolvedValue(undefined),+ notificationClearSessionAttention: vi.fn().mockResolvedValue(undefined),+ });+ }++ function indexRun(overrides: Record<string, unknown>): Record<string, unknown> {+ return {+ runId: 'run-x',+ scheduleId: 'schedule-1',+ scheduleName: '定时任务',+ scheduleStatus: 'active',+ sessionId: 'session-1',+ status: 'running',+ readAt: 1,+ ...overrides,+ };+ }++ it('clears markers whose run already reached a terminal status', async () => {+ vi.useFakeTimers();+ try {+ stubApiWithRuns([+ indexRun({ runId: 'run-lost', status: 'success' }),+ ]);+ // 标记建立后 completed / failed 事件都没送到(广播断链、或事件早于消费方挂载)。+ markNextSessionDoneSilenced('run-lost', 'session-1');+ markNextSessionTerminalNotificationOwnedByScheduler('run-lost', 'session-1');+ expect(isSessionDoneSilenced('session-1')).toBe(true);++ renderHook(() => useAutomationScheduleSessionIndex());+ await act(async () => {+ await Promise.resolve();+ });+ // 对账只排下 linger,窗口内标记仍在 —— 留给可能尚未处理的 done transition。+ expect(isSessionDoneSilenced('session-1')).toBe(true);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(MARKER_TERMINAL_LINGER_MS + 1);+ });++ expect(isSessionDoneSilenced('session-1')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * 回归(greptile review P1):这次拉取同时是标记对账的载体,失败路径原本只 log。+ * 「卸载期间丢终态事件 + 重新挂载时首次拉取 reject(scheduler 未 ready / 临时 IPC 或+ * DB 错误)+ 此后再无任何 scheduler / read-sync 事件」这条链上,标记会永久残留。+ */+ it('retries the reconciliation after a failed refresh', async () => {+ vi.useFakeTimers();+ try {+ const listSidebarIndexRuns = vi+ .fn()+ .mockRejectedValueOnce(new Error('scheduler not ready'))+ .mockResolvedValue({ runs: [indexRun({ runId: 'run-lost', status: 'success' })], inflightRunIds: [] });+ vi.stubGlobal('electronAPI', {+ maker: { schedule: { listSidebarIndexRuns, onEvent: vi.fn(() => () => undefined) } },+ notificationMarkSessionAttention: vi.fn().mockResolvedValue(undefined),+ notificationClearSessionAttention: vi.fn().mockResolvedValue(undefined),+ });+ markNextSessionDoneSilenced('run-lost', 'session-1');++ renderHook(() => useAutomationScheduleSessionIndex());+ // 首次拉取 reject —— 此时标记还留着,且不会再有 scheduler 事件来触发第二次。+ await act(async () => {+ await Promise.resolve();+ });+ expect(isSessionDoneSilenced('session-1')).toBe(true);++ // 退避重试到来,对账排下 linger;再等 linger 到点标记才真正退场。+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_000);+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(MARKER_TERMINAL_LINGER_MS + 1);+ });++ expect(listSidebarIndexRuns).toHaveBeenCalledTimes(2);+ expect(isSessionDoneSilenced('session-1')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * 回归(greptile review P1):退避档位用尽后如果彻底停手,「scheduler / IPC / DB 连续+ * 不可用超过三档窗口 + 此后再无事件」就会让标记永久残留。仍有标记待对账时按最后一档+ * 持续重试。+ */+ it('keeps retrying past the backoff table while markers still await reconciliation', async () => {+ vi.useFakeTimers();+ try {+ const listSidebarIndexRuns = vi+ .fn()+ .mockRejectedValueOnce(new Error('e1'))+ .mockRejectedValueOnce(new Error('e2'))+ .mockRejectedValueOnce(new Error('e3'))+ .mockRejectedValueOnce(new Error('e4'))+ .mockResolvedValue({ runs: [indexRun({ runId: 'run-lost', status: 'success' })], inflightRunIds: [] });+ vi.stubGlobal('electronAPI', {+ maker: { schedule: { listSidebarIndexRuns, onEvent: vi.fn(() => () => undefined) } },+ notificationMarkSessionAttention: vi.fn().mockResolvedValue(undefined),+ notificationClearSessionAttention: vi.fn().mockResolvedValue(undefined),+ });+ markNextSessionDoneSilenced('run-lost', 'session-1');++ renderHook(() => useAutomationScheduleSessionIndex());+ await act(async () => {+ await Promise.resolve();+ });++ // 2s / 8s / 30s 三档全部失败后,第四次失败仍应排下一次(降频持续)。+ for (const delay of [2_000, 8_000, 30_000, 30_000]) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(delay);+ });+ }++ await act(async () => {+ await vi.advanceTimersByTimeAsync(MARKER_TERMINAL_LINGER_MS + 1);+ });++ expect(listSidebarIndexRuns).toHaveBeenCalledTimes(5);+ expect(isSessionDoneSilenced('session-1')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * 回归(codex review P1):自删除 run 的行已随 schedule 级联删除,DB 快照里查不到它,+ * 但引擎的 in-flight 快照说它还在跑 —— 标记必须保住。+ */+ it('keeps markers for a self-deleting run reported in-flight though absent from runs', async () => {+ vi.useFakeTimers();+ try {+ stubApiWithRuns([], ['run-self-delete']);+ markNextSessionDoneSilenced('run-self-delete', 'session-1');++ renderHook(() => useAutomationScheduleSessionIndex());+ await act(async () => {+ await Promise.resolve();+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(MARKER_TERMINAL_LINGER_MS * 3);+ });++ expect(isSessionDoneSilenced('session-1')).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * 回归(codex review P1):DB 说 running、引擎的 in-flight 快照里却没有 —— 两份读之间那个+ * await 窗口里 run 刚好结束了。本轮保守保持标记,但必须自己排一次重查,否则若该 run 的+ * 终态事件正是丢掉的那个就再没信号来清它。下一轮 DB 已落终态,标记正常退场。+ */+ it('rechecks by itself when the two reads disagree, then clears on the next round', async () => {+ vi.useFakeTimers();+ try {+ const listSidebarIndexRuns = vi+ .fn()+ // 第一轮:行还是 running,但 controller 已注销 → 不一致。+ .mockResolvedValueOnce({+ runs: [indexRun({ runId: 'run-racing', status: 'running' })],+ inflightRunIds: [],+ })+ // 重查:DB 已落终态。+ .mockResolvedValue({+ runs: [indexRun({ runId: 'run-racing', status: 'success' })],+ inflightRunIds: [],+ });+ vi.stubGlobal('electronAPI', {+ maker: { schedule: { listSidebarIndexRuns, onEvent: vi.fn(() => () => undefined) } },+ notificationMarkSessionAttention: vi.fn().mockResolvedValue(undefined),+ notificationClearSessionAttention: vi.fn().mockResolvedValue(undefined),+ });+ markNextSessionDoneSilenced('run-racing', 'session-1');++ renderHook(() => useAutomationScheduleSessionIndex());+ await act(async () => {+ await Promise.resolve();+ });+ // 第一轮不清 —— 无法区分它是否真的还在跑。+ expect(isSessionDoneSilenced('session-1')).toBe(true);++ // 重查 + 退场 linger。+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_000);+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(MARKER_TERMINAL_LINGER_MS + 1);+ });++ expect(listSidebarIndexRuns.mock.calls.length).toBeGreaterThanOrEqual(2);+ expect(isSessionDoneSilenced('session-1')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * 回归(codex review P1):卸载时拉取仍 pending,它之后 reject(如撞上 scheduler readiness+ * 的 30s 超时)会走 catch 再排新定时器 —— cleanup 只清得掉「那一刻已存在」的定时器。有+ * 标记时退避耗尽后会每 30s 无限重试,拖着已卸载的 hook 持续发无用 IPC/DB 读。+ */+ it('does not schedule any retry after the hook unmounts', async () => {+ vi.useFakeTimers();+ try {+ let rejectPending!: (err: Error) => void;+ const listSidebarIndexRuns = vi.fn(+ () =>+ new Promise((_resolve, reject) => {+ rejectPending = reject;+ }),+ );+ vi.stubGlobal('electronAPI', {+ maker: { schedule: { listSidebarIndexRuns, onEvent: vi.fn(() => () => undefined) } },+ notificationMarkSessionAttention: vi.fn().mockResolvedValue(undefined),+ notificationClearSessionAttention: vi.fn().mockResolvedValue(undefined),+ });+ // 留一个标记:否则退避耗尽后本来就会停手,测不出问题。+ markNextSessionDoneSilenced('run-x', 'session-1');++ const { unmount } = renderHook(() => useAutomationScheduleSessionIndex());+ unmount();++ // 卸载之后 pending 的那次拉取才失败。+ await act(async () => {+ rejectPending(new Error('scheduler not ready'));+ await Promise.resolve();+ });+ // 远超所有退避档位:不该再有任何一次拉取。+ await act(async () => {+ await vi.advanceTimersByTimeAsync(120_000);+ });++ expect(listSidebarIndexRuns).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps markers whose run is still in flight', async () => {+ stubApiWithRuns([indexRun({ runId: 'run-live', status: 'running' })], ['run-live']);+ markNextSessionDoneSilenced('run-live', 'session-1');++ renderHook(() => useAutomationScheduleSessionIndex());+ // 等 refresh 落地后再断言,否则可能在对账发生前就通过。+ await waitFor(() => {+ expect(+ vi.mocked(window.electronAPI.maker.schedule.listSidebarIndexRuns),+ ).toHaveBeenCalled();+ });+ await act(async () => {+ await Promise.resolve();+ });++ expect(isSessionDoneSilenced('session-1')).toBe(true);});});diff --git a/apps/desktop/src/renderer/__tests__/silencedSessionDoneStore.test.ts b/apps/desktop/src/renderer/__tests__/silencedSessionDoneStore.test.tsindex e993bad28d..2f030e7771 100644--- a/apps/desktop/src/renderer/__tests__/silencedSessionDoneStore.test.ts+++ b/apps/desktop/src/renderer/__tests__/silencedSessionDoneStore.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {clearCompletedSchedulerOwnedRunForNewActivity,@@ -7,10 +7,12 @@ import {clearSilencedRun,getScheduleRunSessionAttentionBaseline,getSilencedRunSessionIdForAttentionFallback,+ isSessionTerminalNotificationOwnedByScheduler,+ isSessionDoneSilenced,markNextSessionTerminalNotificationOwnedByScheduler,markNextSessionDoneSilenced,- observeNextSessionTerminalNotificationOwnedByScheduler,- observeNextSessionDoneSilenced,+ MARKER_TERMINAL_LINGER_MS,+ reconcileRunMarkers,rememberScheduleRunSessionAttentionBaseline,resetSilencedSessionDoneStoreForTests,scheduleClearSchedulerOwnedRun,@@ -22,19 +24,19 @@ describe('silencedSessionDoneStore', () => {resetSilencedSessionDoneStoreForTests();});- it('suppresses exactly one done transition for the marked session', () => {+ it('suppresses every done transition while the run is still in flight', () => {markNextSessionDoneSilenced('run-1', 'session-1');- expect(observeNextSessionDoneSilenced('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(true);clearSilencedRun('run-1');- expect(observeNextSessionDoneSilenced('session-1')).toBe(false);+ expect(isSessionDoneSilenced('session-1')).toBe(false);});it('clears a silenced run after failure/defer without suppressing a later done', () => {markNextSessionDoneSilenced('run-1', 'session-1');expect(clearSilencedRun('run-1')).toBe('session-1');- expect(observeNextSessionDoneSilenced('session-1')).toBe(false);+ expect(isSessionDoneSilenced('session-1')).toBe(false);});it('replaces older pending silence for the same session', () => {@@ -43,17 +45,17 @@ describe('silencedSessionDoneStore', () => {expect(clearSilencedRun('run-1')).toBeUndefined();expect(getSilencedRunSessionIdForAttentionFallback('run-1')).toBeUndefined();- expect(observeNextSessionDoneSilenced('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(true);expect(clearSilencedRun('run-2')).toBe('session-1');});it('lets multiple hook instances observe the same silenced done before cleanup', () => {markNextSessionDoneSilenced('run-1', 'session-1');- expect(observeNextSessionDoneSilenced('session-1')).toBe(true);- expect(observeNextSessionDoneSilenced('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(true);clearSilencedRun('run-1');- expect(observeNextSessionDoneSilenced('session-1')).toBe(false);+ expect(isSessionDoneSilenced('session-1')).toBe(false);});it('allows attention fallback only when the session had no prior attention', () => {@@ -70,7 +72,7 @@ describe('silencedSessionDoneStore', () => {clearCompletedSilencedRunForNewActivity('session-1');- expect(observeNextSessionDoneSilenced('session-1')).toBe(false);+ expect(isSessionDoneSilenced('session-1')).toBe(false);});it('does not clear an in-flight silenced run before completed linger starts', () => {@@ -78,7 +80,7 @@ describe('silencedSessionDoneStore', () => {clearCompletedSilencedRunForNewActivity('session-1');- expect(observeNextSessionDoneSilenced('session-1')).toBe(true);+ expect(isSessionDoneSilenced('session-1')).toBe(true);});it('tracks and clears run attention baselines', () => {@@ -95,10 +97,10 @@ describe('silencedSessionDoneStore', () => {it('tracks scheduler notification ownership separately from full silence', () => {markNextSessionTerminalNotificationOwnedByScheduler('run-owned', 'session-owned');- expect(observeNextSessionDoneSilenced('session-owned')).toBe(false);- expect(observeNextSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(true);+ expect(isSessionDoneSilenced('session-owned')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(true);expect(clearSchedulerOwnedRun('run-owned')).toBe('session-owned');- expect(observeNextSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(false);});it('clears completed scheduler ownership before a later ordinary turn', () => {@@ -107,6 +109,269 @@ describe('silencedSessionDoneStore', () => {clearCompletedSchedulerOwnedRunForNewActivity('session-owned');- expect(observeNextSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(false);+ });++ it('clears the attention baseline of a run replaced by a newer one', () => {+ // 被顶替的 run 之后不会再有人调 clearSilencedRun(scheduleClearSilencedRun 的+ // has 检查会直接 return),baseline 必须在顶替时就清掉,否则随 session 复用无界增长。+ rememberScheduleRunSessionAttentionBaseline('run-1', 'session-1', true);+ markNextSessionDoneSilenced('run-1', 'session-1', true);++ markNextSessionDoneSilenced('run-2', 'session-1', false);++ expect(getScheduleRunSessionAttentionBaseline('run-1')).toBeUndefined();+ });++ /**+ * 回归:一个 run 内 running→done 会翻转多次(后台 subagent 完成后续 turn、+ * silent-stop 守卫自动续跑)。标记以前被第一次中间 done 消费掉,最终那次真 done+ * 就走了普通完成路径,把 macOS toast / 飞书 / 手机推送全发一遍。+ */+ describe('multi-turn run (regression: silenced automation leaked a system push)', () => {+ it('keeps suppressing after an intermediate done and a resumed turn', () => {+ markNextSessionDoneSilenced('run-1', 'session-1');++ // 主 turn done —— 只是中间态,runner 仍在等在途 subagent。+ expect(isSessionDoneSilenced('session-1')).toBe(true);+ // subagent 完成 → SDK 自动续 turn。+ clearCompletedSilencedRunForNewActivity('session-1');+ // 最终 done 必须仍然静默。+ expect(isSessionDoneSilenced('session-1')).toBe(true);+ });++ it('keeps scheduler notification ownership across the same multi-turn shape', () => {+ markNextSessionTerminalNotificationOwnedByScheduler('run-1', 'session-1');++ expect(isSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);+ clearCompletedSchedulerOwnedRunForNewActivity('session-1');+ // 漏了这条会变成 renderer + scheduler notifier 各发一条,用户收到两次通知。+ expect(isSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);+ });+ });++ /**+ * 事件丢失的自愈:靠 scheduler 落库的权威 run 状态对账,而不是任何定时器。+ * 三种「猜 run 还在不在飞行」的判据(事件序 / renderer running 快照 / 固定时长)+ * 都被证明会误判,详见 store 的文件头注释。+ */+ describe('reconciliation against authoritative run status', () => {+ /**+ * 回归(codex review P1):对账清除必须走同一段 linger,不能立即删。终态事件丢了的+ * 标记从未排过 linger,而 DB 可能已报终态、React 却还没处理该 session 的+ * running→done —— 立刻删会让那次 transition 看不到标记、发出不该发的通知。+ */+ it('lets terminal markers linger so a pending done transition still sees them', () => {+ vi.useFakeTimers();+ try {+ markNextSessionDoneSilenced('run-s', 'session-silenced');+ markNextSessionTerminalNotificationOwnedByScheduler('run-o', 'session-owned');++ reconcileRunMarkers(+ new Map([+ ['run-s', 'terminal' as const],+ ['run-o', 'terminal' as const],+ ]),+ new Set(),+ );++ // 对账当拍不删:还在 linger 窗口内,pending 的 done transition 仍看得到标记。+ expect(isSessionDoneSilenced('session-silenced')).toBe(true);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(true);++ vi.advanceTimersByTime(MARKER_TERMINAL_LINGER_MS + 1);++ expect(isSessionDoneSilenced('session-silenced')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * 关键:run 仍在飞行时绝不能清。这覆盖了 renderer running 快照不可信的那些+ * 情形 —— remote_agent / local_bash / 未知 task_type 的后台任务在跑时快照+ * 刻意为 false,device-link 远程会话整体豁免;runner 的 10 分钟兜底也只是事件+ * 静默超时、不是最大 run 时长,所以 run 可以合法飞行任意长。+ */+ it('keeps markers whose run is still in flight, however long it runs', () => {+ markNextSessionDoneSilenced('run-s', 'session-silenced');+ markNextSessionTerminalNotificationOwnedByScheduler('run-o', 'session-owned');++ reconcileRunMarkers(+ new Map([+ ['run-s', 'running' as const],+ ['run-o', 'running' as const],+ ]),+ new Set(['run-s', 'run-o']),+ );++ expect(isSessionDoneSilenced('session-silenced')).toBe(true);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(true);+ });++ /**+ * 回归(codex review P1):run 被删除而不是落终态时,它永远不会出现在权威快照里+ * —— 删除 schedule 会级联删掉 schedule_runs 行,deferred run 也会被显式删除。+ * 若对应的 failed / deferred 事件正好丢了(对账要治的正是事件丢失),「不在快照里+ * 就保持」会让标记永久残留。+ */+ /**+ * 回归(codex review P1):自删除场景 —— agent 在任务 run 内调 schedule_delete 删掉+ * 自己的 schedule,引擎用 exemptRunId 豁免 caller run 不 abort,它的 run 行随 schedule+ * 级联删除后仍继续跑到底(通常还要产出最终回复)。此时「不在 DB 快照里」不等于+ * 「跑完了」,调用方会把引擎的 in-flight 快照覆盖成 running,标记必须保住 —— 否则+ * 最终 done 又会漏出通知。这正是心跳类任务的标准收口路径。+ */+ it('keeps a marker for a self-deleting run that is gone from the DB but still in flight', () => {+ vi.useFakeTimers();+ try {+ markNextSessionDoneSilenced('run-self-delete', 'session-1');++ // DB 里已无此 run(行随 schedule 级联删除),但引擎报它仍 in-flight。+ reconcileRunMarkers(new Map(), new Set(['run-self-delete']));+ vi.advanceTimersByTime(MARKER_TERMINAL_LINGER_MS * 3);++ expect(isSessionDoneSilenced('session-1')).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * 回归(codex review P1):两份读之间隔着 DB 查询的 await,run 恰好在那个窗口内结束时+ * DB 行还是 running、controller 已注销。本轮只能保守保持标记(无法区分它是否真的还在+ * 跑),但必须报告 needsRecheck —— 否则若该 run 的终态事件正是丢掉的那个,就再没有信号+ * 来清这个标记,自愈保证被打破。+ */+ it('reports needsRecheck when the DB says running but the engine does not', () => {+ vi.useFakeTimers();+ try {+ markNextSessionDoneSilenced('run-racing', 'session-1');++ const result = reconcileRunMarkers(+ new Map([['run-racing', 'running' as const]]),+ new Set(),+ );++ expect(result.needsRecheck).toBe(true);+ // 保守保持,不清。+ vi.advanceTimersByTime(MARKER_TERMINAL_LINGER_MS * 3);+ expect(isSessionDoneSilenced('session-1')).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not report needsRecheck when both reads agree', () => {+ markNextSessionDoneSilenced('run-live', 'session-1');+ markNextSessionTerminalNotificationOwnedByScheduler('run-done', 'session-2');++ const result = reconcileRunMarkers(+ new Map([+ ['run-live', 'running' as const],+ ['run-done', 'terminal' as const],+ ]),+ new Set(['run-live']),+ );++ expect(result.needsRecheck).toBe(false);+ });++ it('clears markers whose run no longer exists in the snapshot', () => {+ vi.useFakeTimers();+ try {+ markNextSessionDoneSilenced('run-deleted', 'session-silenced');+ markNextSessionTerminalNotificationOwnedByScheduler('run-gone', 'session-owned');++ // 快照非空,但完全不含这两个 run —— 它们已经被删掉了。+ reconcileRunMarkers(+ new Map([['some-live-run', 'running' as const]]),+ new Set(['some-live-run']),+ );+ vi.advanceTimersByTime(MARKER_TERMINAL_LINGER_MS + 1);++ expect(isSessionDoneSilenced('session-silenced')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * 回归(codex + greptile review P1):权威查询在库里没有匹配行时**合法**返回空数组+ * (删掉最后一个 schedule、或唯一的 run 被 defer 后删除),查询失败走的是 reject ++ * 调用方 catch,不会以空映射到这里。早先那个「空映射当异常整体跳过」的守卫会把这种+ * 情况下的标记永久留住。+ */+ it('reconciles absent runs even when the snapshot is legitimately empty', () => {+ vi.useFakeTimers();+ try {+ markNextSessionDoneSilenced('run-deleted', 'session-silenced');+ markNextSessionTerminalNotificationOwnedByScheduler('run-gone', 'session-owned');++ reconcileRunMarkers(new Map(), new Set());+ vi.advanceTimersByTime(MARKER_TERMINAL_LINGER_MS + 1);++ expect(isSessionDoneSilenced('session-silenced')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ /**+ * completed 已到达并排了 linger 时,对账不能抢在 linger 前面清 —— 那段 linger+ * 正是留给 renderer 的 done transition 消费标记用的,提前清掉这次终态又会走+ * 普通通知路径。+ */+ it('defers to a pending completed linger instead of clearing early', () => {+ vi.useFakeTimers();+ try {+ markNextSessionDoneSilenced('run-s', 'session-silenced');+ markNextSessionTerminalNotificationOwnedByScheduler('run-o', 'session-owned');+ scheduleClearSilencedRun('run-s', 2000);+ scheduleClearSchedulerOwnedRun('run-o', 2000);++ // run 确实已终态,但 linger 在跑 → 本轮对账必须放过。+ reconcileRunMarkers(+ new Map([+ ['run-s', 'terminal' as const],+ ['run-o', 'terminal' as const],+ ]),+ new Set(),+ );+ expect(isSessionDoneSilenced('session-silenced')).toBe(true);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(true);++ vi.advanceTimersByTime(2001);+ expect(isSessionDoneSilenced('session-silenced')).toBe(false);+ expect(isSessionTerminalNotificationOwnedByScheduler('session-owned')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('leaves an unrelated session untouched', () => {+ markNextSessionDoneSilenced('run-a', 'session-a');+ markNextSessionDoneSilenced('run-b', 'session-b');++ vi.useFakeTimers();+ try {+ reconcileRunMarkers(+ new Map([+ ['run-a', 'terminal' as const],+ ['run-b', 'running' as const],+ ]),+ new Set(['run-b']),+ );+ vi.advanceTimersByTime(MARKER_TERMINAL_LINGER_MS + 1);++ expect(isSessionDoneSilenced('session-a')).toBe(false);+ expect(isSessionDoneSilenced('session-b')).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });});});diff --git a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.tsindex 07c5d84ea5..a4a3790426 100644--- a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts+++ b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts@@ -4,9 +4,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { SessionStatusInfo } from '@/lib/makerChatStore';import {+ isSessionDoneSilenced,markNextSessionTerminalNotificationOwnedByScheduler,markNextSessionDoneSilenced,resetSilencedSessionDoneStoreForTests,+ scheduleClearSchedulerOwnedRun,scheduleClearSilencedRun,} from '@/lib/silencedSessionDoneStore';import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';@@ -122,7 +124,14 @@ describe('useSessionRunningStatus silenced completion handling', () => {expect(onSessionDone).not.toHaveBeenCalled();});- it('does not suppress a later ordinary turn in the same scheduler-bound session', async () => {+ it('does not suppress a later ordinary turn once the scheduler run has completed', async () => {+ // run 终态之后同 session 的 turn 属于用户手动对话,照常通知。+ //+ // `completed` 是这条断言的**必要前提**,不是可省略的布景:run 仍在飞行时,+ // 「用户插话的 turn」和「后台 subagent 续 turn」在 renderer 侧是同一个信号+ // (running=true → done),无从区分。标记因此在 run 飞行期间对每次 done 都有效+ // (见文件末尾的 multi-turn 回归),run 终态后才交回普通通知路径 —— 判据就是+ // scheduler 的 completed/failed 事件排下的 linger 定时器。vi.useFakeTimers();const onSessionDone = vi.fn();markNextSessionTerminalNotificationOwnedByScheduler('run-owned', 'session-reused');@@ -136,6 +145,9 @@ describe('useSessionRunningStatus silenced completion handling', () => {});expect(onSessionDone).not.toHaveBeenCalled();+ // scheduler 发出 completed → 排 linger,标记进入「run 已终态」。+ scheduleClearSchedulerOwnedRun('run-owned', 2000);+await emitSnapshot(new Map([['session-reused', status(true)]]));await emitSnapshot(new Map([['session-reused', status(false)]]));await act(async () => {@@ -367,4 +379,94 @@ describe('useSessionRunningStatus silenced completion handling', () => {vi.mocked(getSessionAttentionKind).mockReturnValue(undefined);storeMock.terminalErrorSessions.delete('s-real');});++ // 回归:静默 run 仍在飞行(还没 completed)时,session 的 running→done 会翻转多次+ // —— 主 turn done 只是中间态,runner 还在等在途后台 subagent;subagent 完成后 SDK+ // 自动续 turn,silent-stop 守卫也会在 1.5s 后自动续跑。标记以前被第一次中间 done+ // 消费掉,最终那次真 done 就走了普通完成路径,把 macOS toast / 飞书 / 手机推送全发+ // 一遍。上面那些静默用例都先调了 scheduleClearSilencedRun(即 completed 已到),+ // 正好绕开了这个缝隙,所以长期没被抓到。+ it('never fires the done callback across a multi-turn silenced run', async () => {+ vi.useFakeTimers();+ const onSessionDone = vi.fn();+ // 只有 silenced,没有 scheduleClearSilencedRun —— run 仍在飞行。+ markNextSessionDoneSilenced('run-multi', 'session-multi');++ renderHook(() => useSessionRunningStatus(undefined, { onSessionDone }));++ // 主 turn 跑完(中间态)。+ await emitSnapshot(new Map([['session-multi', status(true)]]));+ await emitSnapshot(new Map([['session-multi', status(false)]]));+ // 推过 debounce:标记若被第一次 done 消费掉,这里还不会响 —— 真正漏出的是下一次。+ await act(async () => {+ await vi.advanceTimersByTimeAsync(600);+ });+ expect(onSessionDone).not.toHaveBeenCalled();++ // 后台 subagent 完成 → 自动续 turn,产出最终 summary 后再次 done。+ await emitSnapshot(new Map([['session-multi', status(true)]]));+ await emitSnapshot(new Map([['session-multi', status(false)]]));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(600);+ });++ expect(onSessionDone).not.toHaveBeenCalled();+ vi.useRealTimers();+ });++ it('keeps scheduler notification ownership across a multi-turn run', async () => {+ // 同根因的第二个症状:标记被中间 done 消费后,最终 done 时 renderer 又发一条,+ // 与 scheduler notifier 自己那条叠成两次通知。+ vi.useFakeTimers();+ const onSessionDone = vi.fn();+ markNextSessionTerminalNotificationOwnedByScheduler('run-owned-multi', 'session-owned-multi');++ renderHook(() => useSessionRunningStatus(undefined, { onSessionDone }));++ await emitSnapshot(new Map([['session-owned-multi', status(true)]]));+ await emitSnapshot(new Map([['session-owned-multi', status(false)]]));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(600);+ });+ await emitSnapshot(new Map([['session-owned-multi', status(true)]]));+ await emitSnapshot(new Map([['session-owned-multi', status(false)]]));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(600);+ });++ // attention 仍照常挂(schedulerOwned 只抑制外发通知,不抑制角标)。+ expect(vi.mocked(addSessionAttention)).toHaveBeenCalledWith('session-owned-multi', 'done');+ expect(onSessionDone).not.toHaveBeenCalled();+ vi.useRealTimers();+ });++ // 回归(codex review P1):agent 在自己 turn 内调 schedule_silence_current_run 时,+ // 标记建立时该 turn 已经 running、renderer 早过了 rising edge —— 任何依赖「事件序」+ // 建立/撤销兜底的方案都会在这条路径上失守。标记的存续不能与时间挂钩。+ it('keeps suppressing when the marker is created mid-turn and that turn runs long', async () => {+ vi.useFakeTimers();+ const onSessionDone = vi.fn();+ renderHook(() => useSessionRunningStatus(undefined, { onSessionDone }));++ // turn 先跑起来,之后 agent 才在 turn 内部请求静默。+ await emitSnapshot(new Map([['session-mid', status(true)]]));+ markNextSessionDoneSilenced('run-mid', 'session-mid');+ // agent 请求静默后继续跑一个很长的工具调用:running 状态毫无变化,也没有任何+ // scheduler 事件。跑多久都不该影响标记 —— run 的存活只由 scheduler 的权威状态+ // 决定,不由挂钟决定。+ await act(async () => {+ await vi.advanceTimersByTimeAsync(30 * 60_000);+ });+ expect(isSessionDoneSilenced('session-mid')).toBe(true);++ // turn 真正结束。+ await emitSnapshot(new Map([['session-mid', status(false)]]));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(600);+ });++ expect(onSessionDone).not.toHaveBeenCalled();+ vi.useRealTimers();+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.tsindex 97491611fc..fdb989dcdb 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts@@ -6,6 +6,7 @@ import {clearSessionAttention,hasSessionAttention,} from '@/lib/sessionAttentionStore';+import type { RunLivenessStatus } from '@/lib/silencedSessionDoneStore';import {clearSchedulerOwnedRun,clearSilencedRun,@@ -14,29 +15,79 @@ import {getSilencedRunSessionIdForAttentionFallback,markNextSessionTerminalNotificationOwnedByScheduler,markNextSessionDoneSilenced,+ hasAnyRunMarker,+ MARKER_TERMINAL_LINGER_MS,+ reconcileRunMarkers,rememberScheduleRunSessionAttentionBaseline,scheduleClearSchedulerOwnedRun,scheduleClearSilencedRun,} from '@/lib/silencedSessionDoneStore';import type { AutomationScheduleSessionInfo } from '../lib/automationSidebarGrouping';import { isUnreadScheduleRun } from '../../scheduler/lib/runUnread';-import { loadScheduleSidebarIndexRuns } from '../../scheduler/lib/scheduleSidebarIndexRuns';+import { loadScheduleSidebarIndexSnapshot } from '../../scheduler/lib/scheduleSidebarIndexRuns';import { subscribeScheduleRunReadSync } from '../../scheduler/lib/scheduleRunReadSync';const log = createLogger('AutomationScheduleSessionIndex');+/**+ * refresh 失败后的退避重试节奏。这次拉取同时承担抑制标记的对账(见 refresh 内注释),+ * 而失败路径原本只 log —— 于是「消费方卸载期间丢了终态事件 + 重新挂载时首次拉取又+ * 因 scheduler 未 ready / 临时 IPC 或 DB 错误 reject + 此后再没有任何 scheduler 或+ * read-sync 事件」这条链上,标记会永久残留,该 session 后续手动对话的完成通知会一直+ * 被静默。有限重试给自愈留出第二次机会;重试耗尽后仍靠后续事件兜。+ */+const REFRESH_RETRY_DELAYS_MS = [2_000, 8_000, 30_000] as const;++/**+ * 快照内部不一致时的重查延迟。见 `ReconcileRunMarkersResult.needsRecheck`:run 恰好在+ * DB 查询的 await 窗口内结束时,DB 行还是 running 而 controller 已注销,本轮只能保守保持+ * 标记;若该 run 的终态事件正是丢掉的那个,就要靠这次重查来清。与失败重试分开计时,也不+ * 占用它的退避配额 —— 这不是失败,只是需要一份更新的快照。+ */+const RECONCILE_RECHECK_DELAY_MS = 1_500;+export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, AutomationScheduleSessionInfo> {const [index, setIndex] = useState<ReadonlyMap<string, AutomationScheduleSessionInfo>>(() => new Map(),);const refreshSeqRef = useRef(0);+ const refreshRef = useRef<() => Promise<void>>(async () => undefined);+ const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const retryAttemptRef = useRef(0);+ const recheckTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ /**+ * 已卸载标记。cleanup 只能清掉「那一刻已存在」的定时器,但卸载时若拉取仍 pending,+ * 它之后 reject(例如撞上 scheduler readiness 的 30s 超时)会走 catch 再排一个新定时器+ * —— 于是退避耗尽后每 30s 无限重试,把已卸载的 hook 一直留着、持续发无用 IPC/DB 读,+ * 重挂载后还会叠加出多条轮询。所有排定时器的地方都必须先看这个标记。+ * StrictMode 下 mount→unmount→mount,所以在 effect 开头重置。+ */+ const cancelledRef = useRef(false);const refresh = useCallback(async () => {const seq = refreshSeqRef.current + 1;refreshSeqRef.current = seq;try {- const runs = await loadScheduleSidebarIndexRuns();- if (refreshSeqRef.current !== seq) return;+ const { runs, inflightRunIds } = await loadScheduleSidebarIndexSnapshot();+ if (refreshSeqRef.current !== seq || cancelledRef.current) return;++ // 抑制标记的事件丢失自愈:这份列表是 scheduler 落库的权威 run 状态(且包含所有+ // 带 sessionId 的 run,没有 history limit),据它清掉「已终态」和「已不存在」的+ // 标记。RunStatus 里只有 'running' 不是终态。刻意不用定时器猜 run 还在不在飞行+ // —— 见 silencedSessionDoneStore 的文件头与 reconcileRunMarkers 注释。+ const dbRunStatus = new Map<string, RunLivenessStatus>();+ for (const run of runs) {+ dbRunStatus.set(run.runId, run.status === 'running' ? 'running' : 'terminal');+ }+ // 两份数据分别传进去 —— 对账内部让 in-flight 优先(自删除场景下 run 行已消失却仍+ // 在跑),并识别「DB 说 running、引擎说没在跑」的不一致,交由下面的重查收口。+ const { needsRecheck } = reconcileRunMarkers(dbRunStatus, new Set(inflightRunIds));+ if (needsRecheck && recheckTimerRef.current === null) {+ recheckTimerRef.current = setTimeout(() => {+ recheckTimerRef.current = null;+ void refreshRef.current();+ }, RECONCILE_RECHECK_DELAY_MS);+ }const next = new Map<string, AutomationScheduleSessionInfo>();for (const run of runs) {@@ -65,14 +116,38 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, Automat});}setIndex(next);+ retryAttemptRef.current = 0;} catch (error) {log.warn('failed to build automation schedule session index', {error: error instanceof Error ? error.message : String(error),});+ // 卸载后到达的 rejection 不再排新定时器,见 cancelledRef。+ if (cancelledRef.current) return;+ // 见 REFRESH_RETRY_DELAYS_MS:这次拉取也是标记对账的载体,失败不能只 log。+ // 退避档位用尽后:仍有标记待对账就按最后一档持续重试(否则 scheduler / IPC / DB+ // 连续不可用超过三档窗口、且此后再无事件时,标记会永久残留);没有标记则停手,+ // 侧栏索引本身是 best-effort,交给后续事件。+ const attempt = retryAttemptRef.current;+ const delayMs =+ REFRESH_RETRY_DELAYS_MS[attempt] ??+ (hasAnyRunMarker()+ ? REFRESH_RETRY_DELAYS_MS[REFRESH_RETRY_DELAYS_MS.length - 1]+ : undefined);+ if (delayMs === undefined) return;++ retryAttemptRef.current = attempt + 1;+ if (retryTimerRef.current !== null) clearTimeout(retryTimerRef.current);+ retryTimerRef.current = setTimeout(() => {+ retryTimerRef.current = null;+ void refreshRef.current();+ }, delayMs);}}, []);+ refreshRef.current = refresh;+useEffect(() => {+ cancelledRef.current = false;void refresh();const off = window.electronAPI.maker.schedule.onEvent((raw) => {const event = raw as SchedulerEvent;@@ -115,7 +190,7 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, AutomatsessionId = getSilencedRunSessionIdForAttentionFallback(event.runId);}if (sessionId) clearSessionAttention(sessionId);- scheduleClearSilencedRun(event.runId, 2000);+ scheduleClearSilencedRun(event.runId, MARKER_TERMINAL_LINGER_MS);} else if (event.type === 'completed') {clearSilencedRun(event.runId);} else if (event.type === 'failed' || event.type === 'deferred') {@@ -124,7 +199,7 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, Automat// completed / failed 可能早于 React transition effect 消费终态,延迟清理;// deferred / skipped 没有可接管的 session 终态,立即释放,避免误伤后续 turn。if (event.type === 'completed' || event.type === 'failed') {- scheduleClearSchedulerOwnedRun(event.runId, 2000);+ scheduleClearSchedulerOwnedRun(event.runId, MARKER_TERMINAL_LINGER_MS);} else if (event.type === 'deferred' || event.type === 'skipped') {clearSchedulerOwnedRun(event.runId);}@@ -144,8 +219,17 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, Automat// (见 scheduleRunReadSync 模块注释)。const offReadSync = subscribeScheduleRunReadSync(() => void refresh());return () => {+ cancelledRef.current = true;off();offReadSync();+ if (retryTimerRef.current !== null) {+ clearTimeout(retryTimerRef.current);+ retryTimerRef.current = null;+ }+ if (recheckTimerRef.current !== null) {+ clearTimeout(recheckTimerRef.current);+ recheckTimerRef.current = null;+ }};}, [refresh]);diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.tsindex 2312829233..a76d182d98 100644--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts@@ -15,6 +15,30 @@ export interface ScheduleSidebarIndexRun {readAt?: number;}+/**+ * 一次 invoke 返回的侧栏索引快照。+ *+ * `inflightRunIds` 是引擎内存里的权威 in-flight 集合,和 `runs` 取自同一次调用、天然+ * 一致。通知抑制标记的对账必须靠它区分「`runs` 里查不到某条 run」的两种含义:已结束并+ * 被清理,还是自删除场景下 run 行已随 schedule 级联删除、run 却仍在跑+ * (见 `scheduler.listInflightRunIds` 的注释)。+ */+export interface ScheduleSidebarIndexSnapshot {+ runs: ScheduleSidebarIndexRun[];+ inflightRunIds: string[];+}++export async function loadScheduleSidebarIndexSnapshot(): Promise<ScheduleSidebarIndexSnapshot> {+ // main 与 renderer 同包发布,不存在版本 skew,所以这里不做跨形态兼容 —— 形态不符就是+ // bug,应该暴露出来而不是静默降级成「没有 in-flight 信息」(那会让对账去误清仍在跑的+ // 自删除 run)。`?? []` 只兜 undefined。+ const raw = (await window.electronAPI.maker.schedule.listSidebarIndexRuns()) as+ | ScheduleSidebarIndexSnapshot+ | undefined;+ return { runs: raw?.runs ?? [], inflightRunIds: raw?.inflightRunIds ?? [] };+}++/** 只要 run 列表的调用方(侧栏卡片、未读计数等)继续用这个。 */export async function loadScheduleSidebarIndexRuns(): Promise<ScheduleSidebarIndexRun[]> {- return (await window.electronAPI.maker.schedule.listSidebarIndexRuns()) as ScheduleSidebarIndexRun[];+ return (await loadScheduleSidebarIndexSnapshot()).runs;}diff --git a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.tsindex b6db92f818..54cc1ee2b0 100644--- a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts+++ b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts@@ -50,8 +50,8 @@ import {import {clearCompletedSchedulerOwnedRunForNewActivity,clearCompletedSilencedRunForNewActivity,- observeNextSessionTerminalNotificationOwnedByScheduler,- observeNextSessionDoneSilenced,+ isSessionTerminalNotificationOwnedByScheduler,+ isSessionDoneSilenced,} from '@/lib/silencedSessionDoneStore';// Codex maker 化后, codex session 也走 makerChatStore;@@ -145,6 +145,9 @@ export function useSessionRunningStatus(// --- 1. Detect new turn starts ---for (const sessionId of currentRunningSet) {if (!prevRunning.has(sessionId)) {+ // 只清「run 已终态」的标记(用户手动起的新对话或下一个 run);run 还在跑时+ // 是 subagent 续 turn / silent-stop 自动续跑,标记必须留着。兜底定时器不在+ // 这里动 —— 统一由本 effect 末尾的对账按当前 running 状态处理。clearCompletedSilencedRunForNewActivity(sessionId);clearCompletedSchedulerOwnedRunForNewActivity(sessionId);// error 红角标与真实错误态同步:新 turn 启动会清掉 store 的终止错误@@ -188,14 +191,16 @@ export function useSessionRunningStatus(// `false` here was the root cause of failed turns being notified as// "done"; always resolve errors against the authoritative store.const hasError = info?.hasError ?? makerChatStore.hasSessionTerminalError(sessionId);- // observeNextSessionDoneSilenced 有副作用(消费一次静默 slot),必须在这里- // 读一次,不能推迟到定时器里 —— 否则 debounce 期间 session 又起新 turn 时- // 静默 slot 会被跳过。- const isSilencedDone = !hasError && observeNextSessionDoneSilenced(sessionId);+ // 两个查询都无副作用、且在 run 存续期间对每次 done 转换都成立:一个静默+ // run 内 running→done 会翻转多次(后台 subagent 续 turn、silent-stop 自动+ // 续跑),标记若被第一次中间 done 消费掉,最终那次真 done 就会当成普通完成+ // 把系统通知发出去。标记的清除只由 scheduler 事件驱动,见+ // silencedSessionDoneStore 的文件头注释。+ const isSilencedDone = !hasError && isSessionDoneSilenced(sessionId);// Scheduler 已按 schedule.notify 接管这次终态的桌面 / 飞书通知。这里只// 抑制 callback,侧栏 / Dock attention 仍按普通 done/error 逻辑保留。const notificationOwnedByScheduler =- observeNextSessionTerminalNotificationOwnedByScheduler(sessionId);+ isSessionTerminalNotificationOwnedByScheduler(sessionId);const isActive = sessionId === activeSessionId;// error 立刻处理:队列会被 abort,不存在"下一条自动接着跑"的场景;红角标 +@@ -211,7 +216,7 @@ export function useSessionRunningStatus(}// 静默完成(scheduled automation 等):既不亮角标也不发系统通知,直接跳过、- // 不进 debounce 调度(静默 slot 副作用已在上面消费完毕)。+ // 不进 debounce 调度。中间 done 与最终 done 都会走到这里。if (isSilencedDone) continue;// 正常 done:走 debounce。QUEUE_DEBOUNCE_MS 内若同 session 又变 runningdiff --git a/apps/desktop/src/renderer/lib/silencedSessionDoneStore.ts b/apps/desktop/src/renderer/lib/silencedSessionDoneStore.tsindex 787b1d4a61..8c14dacaf6 100644--- a/apps/desktop/src/renderer/lib/silencedSessionDoneStore.ts+++ b/apps/desktop/src/renderer/lib/silencedSessionDoneStore.ts@@ -1,9 +1,31 @@+/**+ * 自动任务(scheduler)终态通知的抑制标记。+ *+ * 两组标记语义刻意分开:+ * - silenced:静默运行的成功 run —— 完全不发通知、不亮角标。来源有两条:+ * `Schedule.silentWhenIdle` 预设(run 开始、session-bound 时就静默),以及 agent+ * 在自己 turn 内调 `schedule_silence_current_run`(引擎 `silenceRun`)。两条都走+ * `silenced` 事件,但**建立标记的时机相对 turn 完全不同**(一条在 turn 之前、+ * 一条在 turn 中间),任何依赖「事件序」的判断都会在其中一条上翻车。+ * - schedulerOwned:普通自动任务 —— scheduler notifier 已按 `schedule.notify`+ * 发过这次终态通知,renderer 不能再发第二条;但侧栏 / Dock attention 仍按+ * 普通 done/error 逻辑保留。+ *+ * **标记的生命周期跟随 run,不是「被第一次 done 消费掉」**:一个 run 内 session+ * 的 running→done 会翻转多次(后台 subagent 完成后 SDK 自动续 turn、silent-stop+ * 守卫 1.5s 后自动续跑、队列自动衔接),标记必须活过每一次中间 done,否则最终那+ * 次真 done 会当成普通完成,把 macOS toast / 飞书 / 手机推送全发一遍。+ *+ * 清除只有三条路径:scheduler 的 completed / failed / notified 事件、run 已终态后该+ * session 又起新 turn、以及对账权威 run 状态(`reconcileRunMarkers`,治事件丢失)。前两条+ * 与第三条统一走 `MARKER_TERMINAL_LINGER_MS` 的退场窗口。main 侧灵动岛+ * (`main/agent-island/service.ts` 的 `isCompletionEventSilenced`)是同一套语义,+ * 两边不要再分叉。+ */+const silencedRunSessionIds = new Map<string, string>();const silencedSessionRunIds = new Map<string, string>();const silencedRunHadAttention = new Map<string, boolean>();-// Scheduler 自己按 schedule.notify 发送终态通知时,普通 session transition 仍需-// 保留侧栏 / Dock attention,但不能再走一次 renderer 外发通知。该标记与上面的-// “整次完成静默”语义刻意分开。const schedulerOwnedRunSessionIds = new Map<string, string>();const schedulerOwnedSessionRunIds = new Map<string, string>();const schedulerOwnedClearTimers = new Map<string, ReturnType<typeof setTimeout>>();@@ -13,6 +35,24 @@ const runAttentionBaselines = new Map<>();const clearTimers = new Map<string, ReturnType<typeof setTimeout>>();+/**+ * 事件丢失的自愈**不用定时器**。历史上试过三种「猜 run 还在不在飞行」的判据,+ * 每一种都被证明会误判,不要再往回走:+ *+ * 1. 事件先后顺序(建标记时武装、新 turn 起时撤销):agent 在自己 turn 内调+ * `schedule_silence_current_run` 时,标记建立时该 turn 已经 running,此后再没+ * 有信号能撤销;反过来只在新 turn 起时撤销,消费方随后卸载就永远没有兜底。+ * 2. renderer 的 running 快照:`makerChatStore` 的折算**刻意**把 `remote_agent`、+ * `local_bash`、未知 task_type 排除在 `WAKE_AGENT_TASK_TYPES` 之外,device-link+ * 远程会话整体豁免 —— run 仍在飞行而快照为 false 是设计内行为。+ * 3. 固定时长上限:runner 的 `BG_TASK_IDLE_FALLBACK_MS` 是**事件静默**超时,每个+ * 事件都会重新武装,不是最大 run 时长。持续产出事件的后台任务可以合法飞行+ * 任意长,任何固定窗口都必然误清。+ *+ * 现在改为向权威来源对账:scheduler 落库的 run 状态(见+ * `reconcileRunMarkers`)。不猜,只问。+ */+export function rememberScheduleRunSessionAttentionBaseline(runId: string,sessionId: string,@@ -38,6 +78,10 @@ export function markNextSessionDoneSilenced(if (previousRunId) {silencedRunSessionIds.delete(previousRunId);silencedRunHadAttention.delete(previousRunId);+ // 被顶替的 run 不会再有人调 clearSilencedRun(它已不在 silencedRunSessionIds+ // 里,scheduleClearSilencedRun 会直接 return),baseline 必须在这里一起清,+ // 否则 runAttentionBaselines 会随 session 复用无界增长。+ runAttentionBaselines.delete(previousRunId);}clearPendingTimer(previousRunId);clearPendingTimer(runId);@@ -46,11 +90,9 @@ export function markNextSessionDoneSilenced(silencedRunHadAttention.set(runId, hadSessionAttention);}-export function observeNextSessionDoneSilenced(sessionId: string): boolean {- const runId = silencedSessionRunIds.get(sessionId);- if (!runId) return false;- scheduleClearSilencedRun(runId, 0);- return true;+/** 纯查询:同一个 run 内每次 done 转换都要得到 true(见文件头注释)。 */+export function isSessionDoneSilenced(sessionId: string): boolean {+ return silencedSessionRunIds.has(sessionId);}export function markNextSessionTerminalNotificationOwnedByScheduler(@@ -66,17 +108,105 @@ export function markNextSessionTerminalNotificationOwnedByScheduler(schedulerOwnedSessionRunIds.set(sessionId, runId);}-/**- * 多个 useSessionRunningStatus 实例可能在同一轮 effect 中观察同一 transition,- * 因此不立即 delete;排到下一个 task 清理,让所有同步 observer 得到一致结果。- */-export function observeNextSessionTerminalNotificationOwnedByScheduler(+/** 与 `isSessionDoneSilenced` 同款语义:纯查询,run 内多次 done 都命中。 */+export function isSessionTerminalNotificationOwnedByScheduler(sessionId: string,): boolean {- const runId = schedulerOwnedSessionRunIds.get(sessionId);- if (!runId) return false;- scheduleClearSchedulerOwnedRun(runId, 0);- return true;+ return schedulerOwnedSessionRunIds.has(sessionId);+}++/** 对账用的 run 存活态:只关心「还在飞行」与「不再飞行」。 */+export type RunLivenessStatus = 'running' | 'terminal';++/**+ * 标记从「run 已终态」到真正删除之间的退场窗口。+ *+ * 这段延迟是留给 renderer 的 done transition 的:scheduler 的终态事件可能早于 React+ * 处理该 session 的 running→done,立刻删标记会让那次 transition 看不到标记、于是发出+ * 不该发的(或重复的)通知。事件路径与对账路径都必须走这段 linger —— 对账遇到的恰恰是+ * 「终态事件丢了、从未排过 linger」的标记,直接清就会踩到同一个坑。+ *+ * 于是全模块只有一个统一语义:**linger 定时器存在 = run 已终态、标记进入退场倒计时**,+ * 不论这个判定来自事件还是来自对账。`clearCompleted*ForNewActivity` 正是拿它当终态判据。+ */+export const MARKER_TERMINAL_LINGER_MS = 2000;++/** 是否还有任何标记等待对账。消费方据此决定要不要继续重试拉取快照。 */+export function hasAnyRunMarker(): boolean {+ return silencedRunSessionIds.size > 0 || schedulerOwnedRunSessionIds.size > 0;+}++export interface ReconcileRunMarkersResult {+ /**+ * 本轮出现了「DB 说还在跑、引擎的 in-flight 快照里却没有」的持标记 run,说明这两份读+ * 拿到的不是同一时刻的状态。+ *+ * 它们由同一次 IPC 取回,但中间隔着 DB 查询的 `await`:run 恰好在那个窗口内结束时,+ * SQLite 返回的行还是 `running`,而 controller 已被注销 —— 于是本轮只能保守保持标记+ * (它也可能真的还在跑,无法区分)。问题在于:**如果该 run 的终态事件正是丢掉的那个,+ * 就再没有任何信号来清这个标记**,自愈保证被打破。+ *+ * 所以消费方拿到 true 时必须安排一次快速重新对账 —— 下一轮 DB 已落到终态,不一致自然+ * 消解。这是 review 指出的竞态的收口方式(race-safe 快照需要在 main 侧忙等重采样,+ * 代价更大;这里用一次重查换同样的正确性)。+ */+ needsRecheck: boolean;+}++/**+ * 用 scheduler 落库的**权威** run 状态对账标记 —— 事件丢失(广播断链、事件早于消费方+ * 挂载等)的唯一自愈路径。不猜时间、也不看 renderer 的 running 快照,那几种判据都会+ * 误判,见上方「事件丢失的自愈不用定时器」注释。+ *+ * **两份数据缺一不可**,且**引擎的 in-flight 快照优先级更高**:+ * - `inflightRunIds` 有 → 保持。仍在飞行,飞多久都不清。「行不在库里」并不等于+ * 「跑完了」——agent 在任务 run 内调 `schedule_delete` 删自己的 schedule 时,引擎用+ * `exemptRunId` 豁免 caller run 不 abort,它的行随 schedule 级联删除后仍继续跑到底。+ * 引擎内存态是这件事唯一的权威来源。+ * - `dbRunStatus` 是 `terminal` → 排 linger 退场。它的 completed / failed 事件没送到。+ * - 两份都没有 → 同样排 linger 退场。该 run 已经不存在了:删除 schedule 会级联删掉+ * 它的 `schedule_runs` 行,deferred run 也会被显式删除,这两种情况永远等不到一个终态+ * 状态。这里不可能是「标记建好但 run 还没落库」的极早期 —— 引擎先 `updateRun` 写+ * sessionId、再 emit `session-bound` / `silenced`,而权威快照包含所有带 sessionId 的+ * run,所以标记存在就意味着该 run 当时已进入快照范围。异步拉取的过期结果由调用方的+ * seq 守卫挡掉,不会走到这里。+ *+ * **空的 dbRunStatus 不是异常,一样要对账**:权威查询在库里没有匹配行时合法返回空数组+ * (删掉了最后一个 schedule、或唯一的 run 被 defer 后删除),而查询失败是 reject、走调用方+ * 的 catch 与重试,根本不会以空映射的形式到这里。+ *+ * 清除统一走 `MARKER_TERMINAL_LINGER_MS` 的 linger,不立即删 —— 对账面对的正是「终态+ * 事件丢了、从未排过 linger」的标记,而 DB 可能已报终态、React 却还没处理该 session 的+ * running→done。已排 linger 的标记跳过,避免重置它的倒计时。+ *+ * 返回 `needsRecheck`:见 `ReconcileRunMarkersResult`。+ */+export function reconcileRunMarkers(+ dbRunStatus: ReadonlyMap<string, RunLivenessStatus>,+ inflightRunIds: ReadonlySet<string>,+): ReconcileRunMarkersResult {+ let needsRecheck = false;+ const resolve = (runId: string): 'running' | 'terminal' | 'inconsistent' => {+ if (inflightRunIds.has(runId)) return 'running';+ // DB 说还在跑、引擎却说没在跑 —— 两份读之间那个 await 窗口里 run 刚好结束了。+ if (dbRunStatus.get(runId) === 'running') return 'inconsistent';+ return 'terminal';+ };+ for (const runId of [...silencedRunSessionIds.keys()]) {+ if (clearTimers.has(runId)) continue;+ const state = resolve(runId);+ if (state === 'inconsistent') needsRecheck = true;+ if (state !== 'terminal') continue;+ scheduleClearSilencedRun(runId, MARKER_TERMINAL_LINGER_MS);+ }+ for (const runId of [...schedulerOwnedRunSessionIds.keys()]) {+ if (schedulerOwnedClearTimers.has(runId)) continue;+ const state = resolve(runId);+ if (state === 'inconsistent') needsRecheck = true;+ if (state !== 'terminal') continue;+ scheduleClearSchedulerOwnedRun(runId, MARKER_TERMINAL_LINGER_MS);+ }+ return { needsRecheck };}export function scheduleClearSchedulerOwnedRun(runId: string, delayMs: number): void {@@ -100,6 +230,11 @@ export function clearSchedulerOwnedRun(runId: string): string | undefined {return sessionId;}+/**+ * run 已终态(completed/failed 排了 linger)后该 session 又起新 turn:那是用户手动+ * 对话或下一个 run,立刻交回普通通知路径。run 还在跑时不清 —— 判据是+ * `schedulerOwnedClearTimers` 有没有 linger 定时器,而不是任何时间或 running 推断。+ */export function clearCompletedSchedulerOwnedRunForNewActivity(sessionId: string): void {const runId = schedulerOwnedSessionRunIds.get(sessionId);if (!runId || !schedulerOwnedClearTimers.has(runId)) return;@@ -116,6 +251,7 @@ export function scheduleClearSilencedRun(runId: string, delayMs: number): void {clearTimers.set(runId, timer);}+/** 与 `clearCompletedSchedulerOwnedRunForNewActivity` 对称。 */export function clearCompletedSilencedRunForNewActivity(sessionId: string): void {const runId = silencedSessionRunIds.get(sessionId);if (!runId || !clearTimers.has(runId)) return;@@ -175,3 +311,7 @@ function clearSchedulerOwnedTimer(runId: string | undefined): void {clearTimeout(timer);schedulerOwnedClearTimers.delete(runId);}++++diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex b6b54069fa..f0b7cae1a0 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4565,7 +4565,8 @@ interface ElectronAPI {};} | UtilityTextFailure>;listRuns: (id: string, limit?: number) => Promise<unknown[]>;- listSidebarIndexRuns: () => Promise<unknown[]>;+ /** { runs, inflightRunIds } —— 形态见 features/scheduler/lib/scheduleSidebarIndexRuns。 */+ listSidebarIndexRuns: () => Promise<unknown>;listCostSummaries: () => Promise<unknown[]>;deleteRun: (runId: string) => Promise<void>;getInflightCount: (id: string) => Promise<number>;diff --git a/packages/maker-scheduler/src/__tests__/scheduler.test.ts b/packages/maker-scheduler/src/__tests__/scheduler.test.tsindex 67faf02ed4..1eb381b89d 100644--- a/packages/maker-scheduler/src/__tests__/scheduler.test.ts+++ b/packages/maker-scheduler/src/__tests__/scheduler.test.ts@@ -1119,11 +1119,15 @@ describe('Scheduler', () => {expect(await local.storage.get(sch.id)).toBeNull();// caller run 仍在 in-flight(fireOne 还没走完 finally)expect(local.scheduler.getInflightCount(sch.id)).toBe(1);+ // run 行已随 schedule 级联删除,但引擎内存仍报它在跑 —— renderer 的通知抑制标记+ // 对账靠这份快照区分「查不到 = 跑完了」与「查不到 = 自删除后仍在跑」。+ expect(local.scheduler.listInflightRunIds()).toContain(callerRunId);// caller run 自然跑完:fireOne 收尾不抛错,run 走 success 分支resolveRunner({ sessionId: 'sess-caller' });await tickPromise;expect(local.scheduler.getInflightCount(sch.id)).toBe(0);+ expect(local.scheduler.listInflightRunIds()).not.toContain(callerRunId);const run = local.storage.runs.get(callerRunId);expect(run?.status).toBe('success');// schedule 行已删,fireOne 尾部重排的 storage.update 是 no-op,不会复活 schedulediff --git a/packages/maker-scheduler/src/engine/scheduler.ts b/packages/maker-scheduler/src/engine/scheduler.tsindex f1a4c8557e..fb07bdaa7b 100644--- a/packages/maker-scheduler/src/engine/scheduler.ts+++ b/packages/maker-scheduler/src/engine/scheduler.ts@@ -1205,6 +1205,21 @@ export class Scheduler extends EventEmitter {return this.inflightByschedule.get(id)?.size ?? 0;}+ /**+ * 当前所有 in-flight run 的 runId(跨 schedule)。这是「某个 run 还在不在跑」的**权威+ * 来源** —— 引擎内存态,不依赖 run 行是否还在库里。+ *+ * 为什么需要它:自删除场景下 run 行会先消失、run 却仍在跑。agent 在任务 run 内调+ * `schedule_delete` 删自己的 schedule 时,`deleteUnlocked` 用 `exemptRunId` 豁免 caller+ * run 不 abort,该 run 的行随 schedule 级联删除后它继续跑到底(见那里的注释与+ * `delete with exemptRunId leaves caller run running` 用例)。因此「DB 里查不到这条+ * run」既可能是「已结束并被清理」,也可能是「正在跑的自删除 run」,只有这份 in-flight+ * 快照能区分。消费方(renderer 的抑制标记对账)据此决定能不能清标记。+ */+ listInflightRunIds(): string[] {+ return [...this.inflightControllers.keys()];+ }+/*** 把**指定的单条 in-flight run** 标记为"静默":任务内 agent 确认本轮无需用户* 关注(如 PR 巡检无新动态)时,经 MCP 工具传自己这一轮的 runId 调用本方法。