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(scheduler): 静默自动任务不再误亮绿点与岛提醒 (#3612)

Dash1b4f9f42bf3a
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
index 50d7dc04bb..b1c32bfcb1 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -3506,6 +3506,57 @@ describe('AgentIslandService native publishing', () => {
}
});
+ it('keeps a silenced run quiet across intermediate agent dones without scheduler completed', async () => {
+ vi.useFakeTimers();
+ try {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
+ void frameOrFrames;
+ return state.visible;
+ });
+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, playSound },
+ });
+ syncEnabledForTest(service, publish);
+ service.setSoundSettings({
+ enabled: true,
+ sounds: {
+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,
+ start: customSound('start.wav'),
+ complete: customSound('complete.wav'),
+ },
+ });
+ playSound.mockClear();
+
+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'silent run');
+ service.handleScheduleEvent({
+ type: 'silenced',
+ scheduleId: 'schedule-1',
+ runId: 'run-1',
+ sessionId: 's1',
+ });
+ service.handleAgentEvent({ sessionId: 's1', agentKind: 'codex' }, doneEvent());
+ expect(playSound).not.toHaveBeenCalledWith(customSound('complete.wav'));
+ expect(publish.mock.calls.at(-1)?.[0].displayPolicy).toBe('closed');
+ playSound.mockClear();
+
+ // 续 turn / 后台 subagent 完成后再起一轮。没有 scheduler completed,
+ // 不能因为中间那次 done 就把静默当成已经收口。
+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'continued work');
+ service.handleAgentEvent({ sessionId: 's1', agentKind: 'codex' }, doneEvent());
+
+ expect(playSound).not.toHaveBeenCalledWith(customSound('complete.wav'));
+ const lastState = publish.mock.calls.at(-1)?.[0];
+ expect(lastState?.pillSnapshot.unreadCompletedCount).toBe(0);
+ expect(lastState?.displayPolicy).toBe('closed');
+ vi.runOnlyPendingTimers();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('suppresses a silenced scheduler completion even when the early silenced event was missed', async () => {
vi.useFakeTimers();
try {
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 2c309f8372..f62b70644f 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -430,7 +430,6 @@ export class AgentIslandService {
});
if (!changed) return;
this.mutedCompletionSoundSessionIds.add(sessionId);
- this.scheduleSilencedRunClearForSession(sessionId, SILENCED_COMPLETION_CLEAR_MS);
this.ensureMetadata(sessionId);
this.clearStreamingPreviewPublishTimer();
this.publish();
@@ -751,10 +750,9 @@ export class AgentIslandService {
this.shouldDeferCompletion?.(hydrated.sessionId) === true &&
// Thread 2 fix: silenced completions carry no attention/sound regardless of
// queue state, so there is no need to defer them — apply with no-attention
- // immediately. Deferring a silenced event risks silencedSessionRunIds being
- // cleared (after SILENCED_COMPLETION_CLEAR_MS) before notifyQueueEmptied
- // fires, which would cause the replayed event to be treated as normal and
- // show attention / play sound for a run that was explicitly silenced.
+ // immediately. Linger 只挂 scheduler 的 completed && silenced;中间 agent done
+ // 不得开 linger,否则续 turn 会清掉标记。这里仍跳过 defer,免得 completed 先到
+ // 排了 linger 后,队列排空重放时标记已退场、被当成普通完成。
!this.isCompletionEventSilenced(hydrated.sessionId, event)
) {
if (event.type === 'done') {
@@ -792,7 +790,6 @@ export class AgentIslandService {
});
if (suppressCompletionAttention) {
this.mutedCompletionSoundSessionIds.add(hydrated.sessionId);
- this.scheduleSilencedRunClearForSession(hydrated.sessionId, SILENCED_COMPLETION_CLEAR_MS);
}
if (!changed) return;
this.ensureMetadata(hydrated.sessionId);
@@ -1387,12 +1384,6 @@ export class AgentIslandService {
return this.silencedSessionRunIds.has(sessionId);
}
- private scheduleSilencedRunClearForSession(sessionId: string, delayMs: number): void {
- const runId = this.silencedSessionRunIds.get(sessionId);
- if (!runId) return;
- this.scheduleSilencedRunClear(runId, delayMs);
- }
-
private hadAttentionBeforeSilencedRun(sessionId: string): boolean {
const runId = this.silencedSessionRunIds.get(sessionId);
return runId ? this.silencedRunHadAttention.get(runId) === true : false;
@@ -1409,7 +1400,7 @@ export class AgentIslandService {
private scheduleSilencedRunClear(runId: string, delayMs: number): void {
if (!this.silencedRunSessionIds.has(runId)) return;
- this.clearSilencedRunTimer(runId);
+ if (this.silencedRunClearTimers.has(runId)) return;
const timer = setTimeout(() => {
this.silencedRunClearTimers.delete(runId);
this.clearSilencedScheduleRun(runId);
diff --git a/apps/desktop/src/main/maker-ipc/schedule.ts b/apps/desktop/src/main/maker-ipc/schedule.ts
index 64294cf158..10f317edd5 100644
--- a/apps/desktop/src/main/maker-ipc/schedule.ts
+++ b/apps/desktop/src/main/maker-ipc/schedule.ts
@@ -557,6 +557,7 @@ export function registerScheduleHandlers(getMaker?: () => Maker | null): void {
withScheduler(async ({ storage, scheduler }) => ({
runs: await storage.listSidebarIndexRuns(),
inflightRunIds: scheduler.listInflightRunIds(),
+ inflightPolicies: scheduler.listInflightRunPolicies(),
})),
);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b2483b5b04..ffcf4d3e98 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -6874,10 +6874,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
> => ipcRenderer.invoke('maker:schedule:generate-pre-run-hook', params),
listRuns: (id: string, limit?: number): Promise<unknown[]> =>
ipcRenderer.invoke('maker:schedule:list-runs', id, limit),
- // 回传 { runs, inflightRunIds }:后者是引擎内存里的权威 in-flight 集合,renderer 的
- // 通知抑制标记对账靠它区分「runs 里查不到 = 跑完了」与「= 自删除后行已级联删除、
- // run 仍在跑」。两者不是原子快照,不一致由消费方重查收口(见 main 侧 handler 注释)。
- // runId 不是特权数据(renderer 的标记里就存着它)。
+ // 回传 { runs, inflightRunIds, inflightPolicies }:inflightRunIds 是引擎内存里的
+ // 权威 in-flight 集合,renderer 的通知抑制标记对账靠它区分「runs 里查不到 = 跑完了」
+ // 与「= 自删除后行已级联删除、run 仍在跑」。inflightPolicies 带每条 in-flight 的
+ // silenced / sessionId,用来重建从未建成的抑制标记。两者不是原子快照,不一致由
+ // 消费方重查收口(见 main 侧 handler 注释)。runId 不是特权数据。
listSidebarIndexRuns: (): Promise<unknown> =>
ipcRenderer.invoke('maker:schedule:list-sidebar-index-runs'),
deleteRun: (runId: string): Promise<void> =>
@@ -6904,7 +6905,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
* 订阅 Scheduler 事件。payload 形态:
* { type: 'fired', scheduleId, runId, silent? }
* { type: 'completed', scheduleId, runId, sessionId }
- * { type: 'failed', scheduleId, runId, error }
+ * { type: 'failed', scheduleId, runId, error, sessionId? }
* { type: 'changed', scheduleId }
* { type: 'read', scheduleId } // 主进程在 markRunsRead 后广播
*/
diff --git a/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts b/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts
index c57440b66d..1cd6ba5f24 100644
--- a/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts
@@ -3,7 +3,10 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { SchedulerEvent } from '@cindy/maker-scheduler';
-import { useAutomationScheduleSessionIndex } from '@/features/cc-agent/hooks/useAutomationScheduleSessionIndex';
+import {
+ resetAutomationScheduleOptimisticUnreadForTests,
+ useAutomationScheduleSessionIndex,
+} from '@/features/cc-agent/hooks/useAutomationScheduleSessionIndex';
import {
addSessionAttention,
clearSessionAttentionMany,
@@ -23,6 +26,7 @@ let scheduleEventListener: ((event: SchedulerEvent) => void) | null = null;
beforeEach(() => {
scheduleEventListener = null;
resetSilencedSessionDoneStoreForTests();
+ resetAutomationScheduleOptimisticUnreadForTests();
vi.stubGlobal('electronAPI', {
maker: {
schedule: {
@@ -43,6 +47,7 @@ beforeEach(() => {
afterEach(() => {
clearSessionAttentionMany(['session-1']);
resetSilencedSessionDoneStoreForTests();
+ resetAutomationScheduleOptimisticUnreadForTests();
vi.unstubAllGlobals();
});
@@ -203,12 +208,25 @@ describe('useAutomationScheduleSessionIndex silence events', () => {
* 固定时长)都被证明会误判,见 silencedSessionDoneStore 的文件头注释。
*/
describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
- function stubApiWithRuns(runs: unknown[], inflightRunIds: string[] = []): void {
+ function stubApiWithRuns(
+ runs: unknown[],
+ inflightRunIds: string[] = [],
+ inflightPolicies: unknown[] = [],
+ ): void {
vi.stubGlobal('electronAPI', {
maker: {
schedule: {
- listSidebarIndexRuns: vi.fn().mockResolvedValue({ runs, inflightRunIds }),
- onEvent: vi.fn(() => () => undefined),
+ listSidebarIndexRuns: vi.fn().mockResolvedValue({
+ runs,
+ inflightRunIds,
+ inflightPolicies,
+ }),
+ onEvent: vi.fn((listener: (event: SchedulerEvent) => void) => {
+ scheduleEventListener = listener;
+ return () => {
+ scheduleEventListener = null;
+ };
+ }),
},
},
notificationMarkSessionAttention: vi.fn().mockResolvedValue(undefined),
@@ -264,9 +282,7 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
it('clears markers whose run already reached a terminal status', async () => {
vi.useFakeTimers();
try {
- stubApiWithRuns([
- indexRun({ runId: 'run-lost', status: 'success' }),
- ]);
+ stubApiWithRuns([indexRun({ runId: 'run-lost', status: 'success' })]);
// 标记建立后 completed / failed 事件都没送到(广播断链、或事件早于消费方挂载)。
markNextSessionDoneSilenced('run-lost', 'session-1');
markNextSessionTerminalNotificationOwnedByScheduler('run-lost', 'session-1');
@@ -301,7 +317,10 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
const listSidebarIndexRuns = vi
.fn()
.mockRejectedValueOnce(new Error('scheduler not ready'))
- .mockResolvedValue({ runs: [indexRun({ runId: 'run-lost', status: 'success' })], inflightRunIds: [] });
+ .mockResolvedValue({
+ runs: [indexRun({ runId: 'run-lost', status: 'success' })],
+ inflightRunIds: [],
+ });
vi.stubGlobal('electronAPI', {
maker: { schedule: { listSidebarIndexRuns, onEvent: vi.fn(() => () => undefined) } },
notificationMarkSessionAttention: vi.fn().mockResolvedValue(undefined),
@@ -345,7 +364,10 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
.mockRejectedValueOnce(new Error('e2'))
.mockRejectedValueOnce(new Error('e3'))
.mockRejectedValueOnce(new Error('e4'))
- .mockResolvedValue({ runs: [indexRun({ runId: 'run-lost', status: 'success' })], inflightRunIds: [] });
+ .mockResolvedValue({
+ runs: [indexRun({ runId: 'run-lost', status: 'success' })],
+ inflightRunIds: [],
+ });
vi.stubGlobal('electronAPI', {
maker: { schedule: { listSidebarIndexRuns, onEvent: vi.fn(() => () => undefined) } },
notificationMarkSessionAttention: vi.fn().mockResolvedValue(undefined),
@@ -498,9 +520,7 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
renderHook(() => useAutomationScheduleSessionIndex());
// 等 refresh 落地后再断言,否则可能在对账发生前就通过。
await waitFor(() => {
- expect(
- vi.mocked(window.electronAPI.maker.schedule.listSidebarIndexRuns),
- ).toHaveBeenCalled();
+ expect(vi.mocked(window.electronAPI.maker.schedule.listSidebarIndexRuns)).toHaveBeenCalled();
});
await act(async () => {
await Promise.resolve();
@@ -508,4 +528,200 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
expect(isSessionDoneSilenced('session-1')).toBe(true);
});
+
+ it('rebuilds never-built silenced markers from inflight policies', async () => {
+ stubApiWithRuns(
+ [],
+ ['run-live'],
+ [{ runId: 'run-live', sessionId: 'session-1', silenced: true }],
+ );
+
+ renderHook(() => useAutomationScheduleSessionIndex());
+ await waitFor(() => {
+ expect(isSessionDoneSilenced('session-1')).toBe(true);
+ });
+ expect(isSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);
+ });
+
+ it('restores recently-read silent success from the sidebar snapshot', async () => {
+ stubApiWithRuns([
+ indexRun({
+ runId: 'run-fresh',
+ status: 'success',
+ readAt: Date.now() - 500,
+ }),
+ ]);
+
+ renderHook(() => useAutomationScheduleSessionIndex());
+ await waitFor(() => {
+ expect(isSessionDoneSilenced('session-1')).toBe(true);
+ });
+ });
+
+ it('overlays optimistic unread and points done attention on a visible success', async () => {
+ const oldRun = indexRun({
+ runId: 'run-old',
+ status: 'success',
+ readAt: 20,
+ });
+ stubApiWithRuns([oldRun], [], []);
+ vi.mocked(window.electronAPI.maker.schedule.listSidebarIndexRuns)
+ .mockResolvedValueOnce({
+ runs: [oldRun],
+ inflightRunIds: [],
+ inflightPolicies: [],
+ })
+ .mockResolvedValue({
+ runs: [
+ oldRun,
+ indexRun({
+ runId: 'run-new',
+ status: 'success',
+ readAt: undefined,
+ firedAt: 30,
+ }),
+ ],
+ inflightRunIds: [],
+ inflightPolicies: [],
+ });
+
+ const { result } = renderHook(() => useAutomationScheduleSessionIndex());
+ await waitFor(() => {
+ expect(result.current.get('session-1')).toBeTruthy();
+ });
+
+ act(() => {
+ scheduleEventListener?.({
+ type: 'completed',
+ scheduleId: 'schedule-1',
+ runId: 'run-new',
+ sessionId: 'session-1',
+ });
+ });
+
+ await waitFor(() => {
+ expect(result.current.get('session-1')?.unreadRunIds).toContain('run-new');
+ });
+ expect(hasSessionAttention('session-1')).toBe(true);
+ });
+
+ it('drops optimistic unread when the snapshot no longer has that run and it is not in-flight', async () => {
+ stubApiWithRuns([
+ indexRun({
+ runId: 'run-old',
+ status: 'success',
+ readAt: 20,
+ }),
+ ]);
+
+ const { result } = renderHook(() => useAutomationScheduleSessionIndex());
+ await waitFor(() => {
+ expect(result.current.get('session-1')).toBeTruthy();
+ });
+
+ act(() => {
+ scheduleEventListener?.({
+ type: 'completed',
+ scheduleId: 'schedule-1',
+ runId: 'run-gone',
+ sessionId: 'session-1',
+ });
+ });
+
+ await waitFor(() => {
+ expect(result.current.get('session-1')?.unreadRunIds ?? []).not.toContain('run-gone');
+ });
+ });
+
+ it('does not point done attention for the session currently being viewed', async () => {
+ stubApiWithRuns([
+ indexRun({
+ runId: 'run-old',
+ status: 'success',
+ readAt: 20,
+ }),
+ ]);
+
+ const { result } = renderHook(() => useAutomationScheduleSessionIndex('session-1'));
+ await waitFor(() => {
+ expect(result.current.get('session-1')).toBeTruthy();
+ });
+
+ act(() => {
+ scheduleEventListener?.({
+ type: 'completed',
+ scheduleId: 'schedule-1',
+ runId: 'run-new',
+ sessionId: 'session-1',
+ });
+ });
+
+ expect(hasSessionAttention('session-1')).toBe(false);
+ });
+
+ it('overlays failed unread without pointing done, and ignores aborted', async () => {
+ const oldRun = indexRun({
+ runId: 'run-old',
+ status: 'success',
+ readAt: 20,
+ });
+ const failedRun = indexRun({
+ runId: 'run-failed',
+ status: 'failed',
+ readAt: undefined,
+ firedAt: 40,
+ });
+ stubApiWithRuns([oldRun]);
+ vi.mocked(window.electronAPI.maker.schedule.listSidebarIndexRuns)
+ .mockResolvedValueOnce({
+ runs: [oldRun],
+ inflightRunIds: [],
+ inflightPolicies: [],
+ })
+ .mockResolvedValueOnce({
+ runs: [oldRun],
+ inflightRunIds: [],
+ inflightPolicies: [],
+ })
+ .mockResolvedValue({
+ runs: [oldRun, failedRun],
+ inflightRunIds: [],
+ inflightPolicies: [],
+ });
+
+ const { result } = renderHook(() => useAutomationScheduleSessionIndex());
+ await waitFor(() => {
+ expect(result.current.get('session-1')).toBeTruthy();
+ });
+
+ act(() => {
+ scheduleEventListener?.({
+ type: 'failed',
+ scheduleId: 'schedule-1',
+ runId: 'run-aborted',
+ sessionId: 'session-1',
+ error: 'aborted',
+ });
+ });
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(result.current.get('session-1')?.unreadFailedRunIds ?? []).not.toContain('run-aborted');
+ expect(hasSessionAttention('session-1')).toBe(false);
+
+ act(() => {
+ scheduleEventListener?.({
+ type: 'failed',
+ scheduleId: 'schedule-1',
+ runId: 'run-failed',
+ sessionId: 'session-1',
+ error: 'boom',
+ });
+ });
+
+ await waitFor(() => {
+ expect(result.current.get('session-1')?.unreadFailedRunIds).toContain('run-failed');
+ });
+ expect(hasSessionAttention('session-1')).toBe(false);
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/silencedSessionDoneStore.test.ts b/apps/desktop/src/renderer/__tests__/silencedSessionDoneStore.test.ts
index 2f030e7771..f6d5618025 100644
--- a/apps/desktop/src/renderer/__tests__/silencedSessionDoneStore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/silencedSessionDoneStore.test.ts
@@ -15,6 +15,8 @@ import {
reconcileRunMarkers,
rememberScheduleRunSessionAttentionBaseline,
resetSilencedSessionDoneStoreForTests,
+ restoreInflightRunMarkers,
+ restoreRecentlyReadSilentMarkers,
scheduleClearSchedulerOwnedRun,
scheduleClearSilencedRun,
} from '@/lib/silencedSessionDoneStore';
@@ -352,6 +354,82 @@ describe('silencedSessionDoneStore', () => {
}
});
+ it('does not reset an existing linger countdown', () => {
+ vi.useFakeTimers();
+ try {
+ markNextSessionDoneSilenced('run-1', 'session-1');
+ scheduleClearSilencedRun('run-1', 2000);
+ vi.advanceTimersByTime(1500);
+ scheduleClearSilencedRun('run-1', 2000);
+ vi.advanceTimersByTime(501);
+ expect(isSessionDoneSilenced('session-1')).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('restores never-built silenced markers from inflight policies', () => {
+ restoreInflightRunMarkers(
+ [{ runId: 'run-live', sessionId: 'session-1', silenced: true }],
+ () => false,
+ );
+
+ expect(isSessionDoneSilenced('session-1')).toBe(true);
+ expect(isSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);
+ });
+
+ it('drops a stale silenced marker when inflight policy says the run is no longer silent', () => {
+ markNextSessionDoneSilenced('run-1', 'session-1');
+ markNextSessionTerminalNotificationOwnedByScheduler('run-1', 'session-1');
+
+ restoreInflightRunMarkers(
+ [{ runId: 'run-1', sessionId: 'session-1', silenced: false }],
+ () => false,
+ );
+
+ expect(isSessionDoneSilenced('session-1')).toBe(false);
+ expect(isSessionTerminalNotificationOwnedByScheduler('session-1')).toBe(true);
+ });
+
+ it('cancels a mis-scheduled linger when the run is still in flight', () => {
+ vi.useFakeTimers();
+ try {
+ markNextSessionDoneSilenced('run-1', 'session-1');
+ scheduleClearSilencedRun('run-1', 2000);
+ restoreInflightRunMarkers(
+ [{ runId: 'run-1', sessionId: 'session-1', silenced: true }],
+ () => false,
+ );
+ vi.advanceTimersByTime(MARKER_TERMINAL_LINGER_MS + 1);
+ expect(isSessionDoneSilenced('session-1')).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('restores recently-read silent success only inside the linger window', () => {
+ vi.useFakeTimers();
+ try {
+ const now = 10_000;
+ restoreRecentlyReadSilentMarkers(
+ [
+ { runId: 'run-fresh', sessionId: 'session-fresh', status: 'success', readAt: now - 500 },
+ { runId: 'run-old', sessionId: 'session-old', status: 'success', readAt: 1 },
+ ],
+ now,
+ () => false,
+ );
+
+ expect(isSessionDoneSilenced('session-fresh')).toBe(true);
+ expect(isSessionDoneSilenced('session-old')).toBe(false);
+
+ vi.advanceTimersByTime(MARKER_TERMINAL_LINGER_MS + 1);
+ expect(isSessionDoneSilenced('session-fresh')).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('leaves an unrelated session untouched', () => {
markNextSessionDoneSilenced('run-a', 'session-a');
markNextSessionDoneSilenced('run-b', 'session-b');
diff --git a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts
index 640c56bb5a..4d78d01ddd 100644
--- a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts
+++ b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts
@@ -118,7 +118,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {
expect(onSessionError).toHaveBeenCalledWith('session-err');
});
- it('keeps done attention but suppresses a scheduler-owned completion callback', async () => {
+ it('suppresses scheduler-owned success attention and completion callback', async () => {
vi.useFakeTimers();
const onSessionDone = vi.fn();
markNextSessionTerminalNotificationOwnedByScheduler('run-owned', 'session-owned');
@@ -131,7 +131,23 @@ describe('useSessionRunningStatus silenced completion handling', () => {
await vi.advanceTimersByTimeAsync(500);
});
- expect(vi.mocked(addSessionAttention)).toHaveBeenCalledWith('session-owned', 'done');
+ expect(vi.mocked(addSessionAttention)).not.toHaveBeenCalledWith('session-owned', 'done');
+ expect(onSessionDone).not.toHaveBeenCalled();
+ });
+
+ it('rereads silence when it arrives during the done debounce window', async () => {
+ vi.useFakeTimers();
+ const onSessionDone = vi.fn();
+ renderHook(() => useSessionRunningStatus(undefined, { onSessionDone }));
+
+ await emitSnapshot(new Map([['session-late', status(true)]]));
+ await emitSnapshot(new Map([['session-late', status(false)]]));
+ markNextSessionDoneSilenced('run-late', 'session-late');
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+
+ expect(vi.mocked(addSessionAttention)).not.toHaveBeenCalledWith('session-late', 'done');
expect(onSessionDone).not.toHaveBeenCalled();
});
@@ -561,8 +577,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {
await vi.advanceTimersByTimeAsync(600);
});
- // attention 仍照常挂(schedulerOwned 只抑制外发通知,不抑制角标)。
- expect(vi.mocked(addSessionAttention)).toHaveBeenCalledWith('session-owned-multi', 'done');
+ expect(vi.mocked(addSessionAttention)).not.toHaveBeenCalledWith('session-owned-multi', 'done');
expect(onSessionDone).not.toHaveBeenCalled();
vi.useRealTimers();
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 108a128354..9f958c2dee 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -473,7 +473,16 @@ export function CCAgentSidebarUpper() {
[searchProjectSessions, hiddenProjectKeys, localPlatform],
);
const attentionNotifications = useSessionAttentionSnapshot();
- const scheduleSessionIndex = useAutomationScheduleSessionIndex();
+ // Sidebar is rendered outside the :sessionId route, so useParams won't work.
+ // Use useMatch to extract the active session id from the URL.
+ const match = useMatch('/cc-agent/:sessionId');
+ const orcaMatch = useMatch('/cc-agent/orca/:sessionId');
+ const filesMatch = useMatch('/cc-agent/files/:sessionId');
+ const activeSessionId = orcaMatch?.params.sessionId ?? match?.params.sessionId;
+ const filesSessionId = filesMatch?.params.sessionId;
+ // files 路由下用户注视的就是该会话(ExpandedView 的 viewedSessionId 同一口径),
+ // 可见成功同样不该给它点 done 角标。
+ const scheduleSessionIndex = useAutomationScheduleSessionIndex(activeSessionId ?? filesSessionId);
// 侧栏右侧 urgent 红点的"额外"来源:定时任务未读且失败(status != 'success')。
// sessionAttentionStore 只跟踪 chat 内 attention;schedule 未读通过 sidebarNotifications
// 合并进 hasAttentionNotification,但 attentionKind 缺失导致默认走绿(见 SessionItem
@@ -488,17 +497,9 @@ export function CCAgentSidebarUpper() {
}, [scheduleSessionIndex]);
const navigate = useNavigate();
- // Sidebar is rendered outside the :sessionId route, so useParams won't work.
- // Use useMatch to extract the active session id from the URL.
- const match = useMatch('/cc-agent/:sessionId');
- const orcaMatch = useMatch('/cc-agent/orca/:sessionId');
- const activeSessionId = orcaMatch?.params.sessionId ?? match?.params.sessionId;
-
// Workdir-browse mode (skillhub Market sidebar pattern). When the user
// clicked the file-text button on a Project, we swap sidebar contents to
// the lazy file tree of that session's workdir.
- const filesMatch = useMatch('/cc-agent/files/:sessionId');
- const filesSessionId = filesMatch?.params.sessionId;
const filesSession = useMemo(
() => resolveDocModeFilesSession(allSessionsForAttention, filesSessionId),
[allSessionsForAttention, filesSessionId],
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts
index fba7569e04..0ca480f978 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts
@@ -4,7 +4,9 @@ import type { SchedulerEvent } from '@cindy/maker-scheduler';
import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
import { createLogger } from '@/lib/logger';
import {
+ addSessionAttention,
clearSessionAttention,
+ getSessionAttentionKind,
hasSessionAttention,
} from '@/lib/sessionAttentionStore';
import type { RunLivenessStatus } from '@/lib/silencedSessionDoneStore';
@@ -20,6 +22,8 @@ import {
MARKER_TERMINAL_LINGER_MS,
reconcileRunMarkers,
rememberScheduleRunSessionAttentionBaseline,
+ restoreInflightRunMarkers,
+ restoreRecentlyReadSilentMarkers,
scheduleClearSchedulerOwnedRun,
scheduleClearSilencedRun,
} from '@/lib/silencedSessionDoneStore';
@@ -34,6 +38,66 @@ const log = createLogger('AutomationScheduleSessionIndex');
let publishedIndex: ReadonlyMap<string, AutomationScheduleSessionInfo> = new Map();
const publishedIndexListeners = new Set<() => void>();
+type OptimisticUnreadKind = 'success' | 'failed';
+interface OptimisticUnread {
+ sessionId: string;
+ runId: string;
+ kind: OptimisticUnreadKind;
+}
+
+/**
+ * `completed` / `failed` 到 sidebar 快照落地之间的乐观未读。
+ * 不给尚不在 index 的 session 建空 scheduleName stub —— attention 已经够绿/红。
+ */
+const optimisticUnreads = new Map<string, OptimisticUnread>();
+
+export function resetAutomationScheduleOptimisticUnreadForTests(): void {
+ optimisticUnreads.clear();
+}
+
+function rememberOptimisticUnread(
+ sessionId: string,
+ runId: string,
+ kind: OptimisticUnreadKind,
+): void {
+ if (!sessionId || !runId) return;
+ optimisticUnreads.set(runId, { sessionId, runId, kind });
+}
+
+function forgetStaleOptimisticUnreads(
+ presentRunIds: Iterable<string>,
+ inflightRunIds: ReadonlySet<string>,
+): void {
+ const present = presentRunIds instanceof Set ? presentRunIds : new Set(presentRunIds);
+ for (const runId of [...optimisticUnreads.keys()]) {
+ if (present.has(runId)) {
+ // 快照已有权威行,overlay 完成使命。
+ optimisticUnreads.delete(runId);
+ continue;
+ }
+ if (inflightRunIds.has(runId)) continue;
+ // 权威快照既没有行、也不在飞行:自删除后的终态 overlay 必须丢掉,
+ // 否则会叠到后来绑同一 session 的任务上,且标记已读 IPC 对不存在的行是 no-op。
+ optimisticUnreads.delete(runId);
+ }
+}
+
+function applyOptimisticUnreads(next: Map<string, AutomationScheduleSessionInfo>): void {
+ for (const overlay of optimisticUnreads.values()) {
+ const existing = next.get(overlay.sessionId);
+ if (!existing) continue;
+ if (!existing.unreadRunIds.includes(overlay.runId)) {
+ existing.unreadRunIds.push(overlay.runId);
+ }
+ if (overlay.kind === 'failed' && !existing.unreadFailedRunIds.includes(overlay.runId)) {
+ existing.unreadFailedRunIds.push(overlay.runId);
+ existing.latestUnreadFailedRunId = overlay.runId;
+ }
+ existing.hasUnreadRun = existing.unreadRunIds.length > 0;
+ existing.hasUnreadFailedRun = existing.unreadFailedRunIds.length > 0;
+ }
+}
+
function publishIndex(next: ReadonlyMap<string, AutomationScheduleSessionInfo>): void {
publishedIndex = next;
for (const listener of publishedIndexListeners) listener();
@@ -73,10 +137,14 @@ const REFRESH_RETRY_DELAYS_MS = [2_000, 8_000, 30_000] as const;
*/
const RECONCILE_RECHECK_DELAY_MS = 1_500;
-export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, AutomationScheduleSessionInfo> {
+export function useAutomationScheduleSessionIndex(
+ activeSessionId?: string,
+): ReadonlyMap<string, AutomationScheduleSessionInfo> {
const [index, setIndex] = useState<ReadonlyMap<string, AutomationScheduleSessionInfo>>(
() => new Map(),
);
+ const activeSessionIdRef = useRef(activeSessionId);
+ activeSessionIdRef.current = activeSessionId;
const refreshSeqRef = useRef(0);
const refreshRef = useRef<() => Promise<void>>(async () => undefined);
const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -95,9 +163,17 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, Automat
const seq = refreshSeqRef.current + 1;
refreshSeqRef.current = seq;
try {
- const { runs, inflightRunIds } = await loadScheduleSidebarIndexSnapshot();
+ const { runs, inflightRunIds, inflightPolicies } = await loadScheduleSidebarIndexSnapshot();
if (refreshSeqRef.current !== seq || cancelledRef.current) return;
+ const inflightSet = new Set(inflightRunIds);
+ forgetStaleOptimisticUnreads(
+ runs.map((run) => run.runId),
+ inflightSet,
+ );
+ restoreInflightRunMarkers(inflightPolicies, hasSessionAttention);
+ restoreRecentlyReadSilentMarkers(runs, Date.now(), hasSessionAttention, inflightSet);
+
// 抑制标记的事件丢失自愈:这份列表包含所有 running run,以及每个 session 的最新
// 映射和未读终态 run,据它清掉「已终态」和「已不存在」的
// 标记。RunStatus 里只有 'running' 不是终态。刻意不用定时器猜 run 还在不在飞行
@@ -108,7 +184,7 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, Automat
}
// 两份数据分别传进去 —— 对账内部让 in-flight 优先(自删除场景下 run 行已消失却仍
// 在跑),并识别「DB 说 running、引擎说没在跑」的不一致,交由下面的重查收口。
- const { needsRecheck } = reconcileRunMarkers(dbRunStatus, new Set(inflightRunIds));
+ const { needsRecheck } = reconcileRunMarkers(dbRunStatus, inflightSet);
if (needsRecheck && recheckTimerRef.current === null) {
recheckTimerRef.current = setTimeout(() => {
recheckTimerRef.current = null;
@@ -153,6 +229,7 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, Automat
hasUnreadFailedRun: unreadFailedRunIds.length > 0,
});
}
+ applyOptimisticUnreads(next);
setIndex(next);
publishIndex(next);
retryAttemptRef.current = 0;
@@ -233,8 +310,24 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, Automat
scheduleClearSilencedRun(event.runId, MARKER_TERMINAL_LINGER_MS);
} else if (event.type === 'completed') {
clearSilencedRun(event.runId);
+ if (event.sessionId) {
+ rememberOptimisticUnread(event.sessionId, event.runId, 'success');
+ const kind = getSessionAttentionKind(event.sessionId);
+ // 正在看的会话不要补 done:running→done 路径已经跳过,这里再点会留下
+ // 切走才清得掉的角标(clear 只在 activeSessionId 变化时跑)。
+ if (
+ kind !== 'error' &&
+ kind !== 'awaiting' &&
+ event.sessionId !== activeSessionIdRef.current
+ ) {
+ addSessionAttention(event.sessionId, 'done');
+ }
+ }
} else if (event.type === 'failed' || event.type === 'deferred') {
clearSilencedRun(event.runId);
+ if (event.type === 'failed' && event.sessionId && event.error !== 'aborted') {
+ rememberOptimisticUnread(event.sessionId, event.runId, 'failed');
+ }
}
// completed / failed 可能早于 React transition effect 消费终态,延迟清理;
// deferred / skipped 没有可接管的 session 终态,立即释放,避免误伤后续 turn。
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
index 2fa351790d..e264437a48 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
@@ -1,4 +1,4 @@
-import type { Schedule, ScheduleRun } from '@cindy/maker-scheduler';
+import type { Schedule, ScheduleRun, SchedulerInflightRunPolicy } from '@cindy/maker-scheduler';
/** Sidebar 聚合索引用的轻量 run wire 形态,由 main 侧 SQLite 查询直接返回。 */
export interface ScheduleSidebarIndexRun {
@@ -23,10 +23,14 @@ export interface ScheduleSidebarIndexRun {
* 一致。通知抑制标记的对账必须靠它区分「`runs` 里查不到某条 run」的两种含义:已结束并
* 被清理,还是自删除场景下 run 行已随 schedule 级联删除、run 却仍在跑
* (见 `scheduler.listInflightRunIds` 的注释)。
+ *
+ * `inflightPolicies` 是同一批 in-flight run 的展示策略(是否静默、绑了哪个 session)。
+ * hook 晚挂或事件丢失时用它重建从未建成的 silenced / schedulerOwned 标记。
*/
export interface ScheduleSidebarIndexSnapshot {
runs: ScheduleSidebarIndexRun[];
inflightRunIds: string[];
+ inflightPolicies: SchedulerInflightRunPolicy[];
}
/**
@@ -60,7 +64,11 @@ export async function loadScheduleSidebarIndexSnapshot(): Promise<ScheduleSideba
const raw = (await window.electronAPI.maker.schedule.listSidebarIndexRuns()) as
| ScheduleSidebarIndexSnapshot
| undefined;
- return { runs: raw?.runs ?? [], inflightRunIds: raw?.inflightRunIds ?? [] };
+ return {
+ runs: raw?.runs ?? [],
+ inflightRunIds: raw?.inflightRunIds ?? [],
+ inflightPolicies: raw?.inflightPolicies ?? [],
+ };
}
/** 只要 run 列表的调用方(侧栏卡片、未读计数等)继续用这个。 */
diff --git a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts
index 0a92eb91a6..20a2d77181 100644
--- a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts
+++ b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts
@@ -203,7 +203,9 @@ export function useSessionRunningStatus(
// silencedSessionDoneStore 的文件头注释。
const isSilencedDone = !hasError && isSessionDoneSilenced(sessionId);
// Scheduler 已按 schedule.notify 接管这次终态的桌面 / 飞书通知。这里只
- // 抑制 callback,侧栏 / Dock attention 仍按普通 done/error 逻辑保留。
+ // 抑制 callback。成功绿点改认 schedule 未读,不再从这条 running→done 点
+ // `done` attention;失败红点仍立即挂。debounce 落地还会再读一次标记,
+ // 免得 silenced 落在 500ms 窗口里。
const notificationOwnedByScheduler =
isSessionTerminalNotificationOwnedByScheduler(sessionId);
// error 立刻处理:队列会被 abort,不存在"下一条自动接着跑"的场景;红角标 +
@@ -252,16 +254,20 @@ export function useSessionRunningStatus(
cur.hasPendingPermission ||
cur.hasPendingPlanReview ||
cur.hasPendingPluginSetup);
+ // silenced 可能在 debounce 窗口内才到:转换当时没静默、进了 debounce,落地必须再读。
+ if (!hasTerminalError && isSessionDoneSilenced(sessionId)) return;
+ const ownedNow = isSessionTerminalNotificationOwnedByScheduler(sessionId);
if (
!wasActiveAtCompletion &&
!isActive &&
!isRunning &&
!hasTerminalError &&
- !stillPending
+ !stillPending &&
+ !ownedNow
) {
addSessionAttention(sessionId, 'done');
}
- if (!notificationOwnedByScheduler && !hasTerminalError) {
+ if (!ownedNow && !hasTerminalError) {
onSessionDoneRef.current?.(sessionId);
}
}, QUEUE_DEBOUNCE_MS);
diff --git a/apps/desktop/src/renderer/lib/silencedSessionDoneStore.ts b/apps/desktop/src/renderer/lib/silencedSessionDoneStore.ts
index e7c7ca8ab3..f3fd0906d5 100644
--- a/apps/desktop/src/renderer/lib/silencedSessionDoneStore.ts
+++ b/apps/desktop/src/renderer/lib/silencedSessionDoneStore.ts
@@ -8,8 +8,9 @@
* `silenced` 事件,但**建立标记的时机相对 turn 完全不同**(一条在 turn 之前、
* 一条在 turn 中间),任何依赖「事件序」的判断都会在其中一条上翻车。
* - schedulerOwned:普通自动任务 —— scheduler notifier 已按 `schedule.notify`
- * 发过这次终态通知,renderer 不能再发第二条;但侧栏 / Dock attention 仍按
- * 普通 done/error 逻辑保留。
+ * 发过这次终态通知,renderer 不能再发第二条。成功完成不再从 running→done
+ * 点 `done` attention(绿点改认 schedule 未读 + `completed && !silenced`
+ * 乐观未读);失败仍立即点 `error` 红点。
*
* **标记的生命周期跟随 run,不是「被第一次 done 消费掉」**:一个 run 内 session
* 的 running→done 会翻转多次(后台 subagent 完成后 SDK 自动续 turn、silent-stop
@@ -209,9 +210,71 @@ export function reconcileRunMarkers(
return { needsRecheck };
}
+/** 与 IPC 快照里的 `inflightPolicies` 同形,避免本 store 去依赖 maker-scheduler。 */
+export interface InflightRunPolicySnapshot {
+ runId: string;
+ sessionId?: string;
+ silenced: boolean;
+}
+
+/**
+ * 用引擎的 in-flight 策略快照重建从未建成(或已被误清)的标记。
+ *
+ * hook 晚挂、事件早于订阅时,reconcile 只能清已有标记、不能凭空恢复。本函数补那条腿:
+ * - 已绑定 session 的 in-flight run 一律重建 schedulerOwned;
+ * - `silenced` 才重建静默;非静默则丢掉该 run 上过期的 silenced(可能错过了 notified);
+ * - in-flight 要取消误排的 linger(只清 timer,不删标记)—— `markNext*` 会顺带清 timer。
+ */
+export function restoreInflightRunMarkers(
+ policies: ReadonlyArray<InflightRunPolicySnapshot>,
+ hadAttention: (sessionId: string) => boolean,
+): void {
+ for (const policy of policies) {
+ if (!policy.runId || !policy.sessionId) continue;
+ markNextSessionTerminalNotificationOwnedByScheduler(policy.runId, policy.sessionId);
+ if (policy.silenced) {
+ markNextSessionDoneSilenced(policy.runId, policy.sessionId, hadAttention(policy.sessionId));
+ } else if (silencedRunSessionIds.has(policy.runId)) {
+ clearSilencedRun(policy.runId);
+ }
+ }
+}
+
+export interface RecentlyReadSilentRunSnapshot {
+ runId: string;
+ sessionId?: string;
+ status: string;
+ readAt?: number;
+}
+
+/**
+ * 刚静默成功落库的 run(`success` + `readAt`)若还在 linger 窗口内,补回标记并排 linger。
+ * 已有 timer 不重置。启发式:用户在 2s 内点已读也可能被当成静默,可接受。
+ */
+export function restoreRecentlyReadSilentMarkers(
+ runs: ReadonlyArray<RecentlyReadSilentRunSnapshot>,
+ now: number,
+ hadAttention: (sessionId: string) => boolean,
+ inflightRunIds: ReadonlySet<string> = new Set(),
+): void {
+ for (const run of runs) {
+ if (inflightRunIds.has(run.runId)) continue;
+ if (run.status !== 'success' || !run.sessionId || run.readAt == null) continue;
+ if (now - run.readAt >= MARKER_TERMINAL_LINGER_MS) continue;
+ if (!silencedRunSessionIds.has(run.runId)) {
+ markNextSessionDoneSilenced(run.runId, run.sessionId, hadAttention(run.sessionId));
+ }
+ if (!schedulerOwnedRunSessionIds.has(run.runId)) {
+ markNextSessionTerminalNotificationOwnedByScheduler(run.runId, run.sessionId);
+ }
+ scheduleClearSilencedRun(run.runId, MARKER_TERMINAL_LINGER_MS);
+ scheduleClearSchedulerOwnedRun(run.runId, MARKER_TERMINAL_LINGER_MS);
+ }
+}
+
export function scheduleClearSchedulerOwnedRun(runId: string, delayMs: number): void {
if (!schedulerOwnedRunSessionIds.has(runId)) return;
- clearSchedulerOwnedTimer(runId);
+ if (schedulerOwnedClearTimers.has(runId)) return;
const timer = setTimeout(() => {
schedulerOwnedClearTimers.delete(runId);
clearSchedulerOwnedRun(runId);
@@ -243,7 +306,7 @@ export function clearCompletedSchedulerOwnedRunForNewActivity(sessionId: string)
export function scheduleClearSilencedRun(runId: string, delayMs: number): void {
if (!silencedRunSessionIds.has(runId)) return;
- clearPendingTimer(runId);
+ if (clearTimers.has(runId)) return;
const timer = setTimeout(() => {
clearTimers.delete(runId);
clearSilencedRun(runId);
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index b631691b39..210642ee4a 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -6211,7 +6211,7 @@ interface ElectronAPI {
| UtilityTextFailure
>;
listRuns: (id: string, limit?: number) => Promise<unknown[]>;
- /** { runs, inflightRunIds } —— 形态见 features/scheduler/lib/scheduleSidebarIndexRuns。 */
+ /** { runs, inflightRunIds, inflightPolicies } —— 形态见 features/scheduler/lib/scheduleSidebarIndexRuns。 */
listSidebarIndexRuns: () => 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.ts
index ac065e5d62..116a0c2125 100644
--- a/packages/maker-scheduler/src/__tests__/scheduler.test.ts
+++ b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
@@ -634,6 +634,58 @@ describe('Scheduler', () => {
expect(h.fireCalls[0].schedule.targetSessionId).toBe('sess-existing');
});
+ it('pre-bind fire failure persists targetSessionId and emits it on failed (runNow)', async () => {
+ h = makeHarness({
+ validateTargetSession: async (_id, op) => {
+ if (op === 'fire') throw new Error('target session rejected');
+ },
+ });
+ const sch = await h.scheduler.create({
+ ...baseInput,
+ targetSessionId: 'session-bound',
+ });
+ const failedEvents: Array<{ type: string; sessionId?: string; error: string }> = [];
+ h.scheduler.on('failed', (e) => failedEvents.push(e));
+
+ const { runId } = await h.scheduler.runNow(sch.id);
+ const run = (await h.scheduler.listRuns(sch.id)).find((item) => item.id === runId);
+
+ expect(h.fireCalls).toHaveLength(0);
+ expect(run?.status).toBe('failed');
+ expect(run?.sessionId).toBe('session-bound');
+ expect(failedEvents).toEqual([
+ {
+ type: 'failed',
+ scheduleId: sch.id,
+ runId,
+ error: 'target session rejected',
+ sessionId: 'session-bound',
+ },
+ ]);
+ });
+
+ it('pre-bind fire failure persists targetSessionId on the cron path too', async () => {
+ h = makeHarness({
+ validateTargetSession: async (_id, op) => {
+ if (op === 'fire') throw new Error('target session rejected');
+ },
+ });
+ const sch = await h.scheduler.create({
+ ...baseInput,
+ targetSessionId: 'session-bound',
+ });
+ const failedEvents: Array<{ sessionId?: string }> = [];
+ h.scheduler.on('failed', (e) => failedEvents.push(e));
+ h.clock.setTo(Date.UTC(2026, 0, 1, 0, 1, 5));
+ await h.scheduler.tick();
+
+ const runs = await h.scheduler.listRuns(sch.id);
+ expect(runs).toHaveLength(1);
+ expect(runs[0].status).toBe('failed');
+ expect(runs[0].sessionId).toBe('session-bound');
+ expect(failedEvents[0]?.sessionId).toBe('session-bound');
+ });
+
it('emits fired/completed/changed events', async () => {
const events: Array<{ type: string; scheduleId: string }> = [];
h.scheduler.on('fired', (e) => events.push({ type: e.type, scheduleId: e.scheduleId }));
diff --git a/packages/maker-scheduler/src/engine/scheduler.ts b/packages/maker-scheduler/src/engine/scheduler.ts
index d64fc2932f..98bebaaf68 100644
--- a/packages/maker-scheduler/src/engine/scheduler.ts
+++ b/packages/maker-scheduler/src/engine/scheduler.ts
@@ -8,6 +8,7 @@ import type {
SchedulerEvent,
ScheduleFireSource,
SchedulerInflightRun,
+ SchedulerInflightRunPolicy,
SchedulerRuntimeSnapshot,
SchedulerWaitingSchedule,
ScheduleRunPhase,
@@ -765,6 +766,8 @@ export class Scheduler extends EventEmitter {
let deferred = false;
let deferRetryMs: number | undefined;
let skipped = false;
+ // unregisterInflight 会清掉 session 映射,终态 emit 必须用 finally 之前捕获的值。
+ let knownSessionId: string | undefined;
this.updateInflightAttempt(runId, 'running');
try {
if (schedule.targetSessionId) {
@@ -792,6 +795,7 @@ export class Scheduler extends EventEmitter {
runError = err instanceof Error ? err.message : String(err);
this.logger?.warn?.('schedule fire failed', { scheduleId: schedule.id, runId, error: runError });
} finally {
+ knownSessionId = this.resolveTerminalSessionId(runId, sessionId, schedule.targetSessionId);
this.unregisterInflight(schedule.id, runId);
this.updateInflightAttempt(runId, 'finalizing');
}
@@ -852,8 +856,13 @@ export class Scheduler extends EventEmitter {
// 恰恰是最需要补发的场景,用户配了桌面/飞书通知却什么都收不到(第十八轮 P1)。
// 通知权认领与终态落库是两件独立的事,不能让前者依赖后者成功。
try {
- await this.storage.updateRun(runId, { status: 'failed', finishedAt, errorMsg });
- this.emitEvent({ type: 'failed', scheduleId: schedule.id, runId, error: errorMsg });
+ await this.storage.updateRun(runId, {
+ status: 'failed',
+ finishedAt,
+ errorMsg,
+ ...(knownSessionId ? { sessionId: knownSessionId } : {}),
+ });
+ this.emitFailed(schedule.id, runId, errorMsg, knownSessionId);
} finally {
// 补发判据只看 runner 有没有真的投过**失败**通知(onRunnerNotified),不再用
// "有没有 runError"推断:守卫的 abort 可能落在前置检查 / 会话创建这类 setup
@@ -872,20 +881,17 @@ export class Scheduler extends EventEmitter {
errorMsg: 'cancelled by user (schedule deleted or paused)',
// 系统/用户主动收口,不是要处理的失败;生而已读,侧栏不涂红。
readAt: finishedAt,
+ ...(knownSessionId ? { sessionId: knownSessionId } : {}),
});
- this.emitEvent({
- type: 'failed',
- scheduleId: schedule.id,
- runId,
- error: 'aborted',
- });
+ this.emitFailed(schedule.id, runId, 'aborted', knownSessionId);
} else if (runError !== undefined) {
await this.storage.updateRun(runId, {
status: 'failed',
finishedAt,
errorMsg: runError,
+ ...(knownSessionId ? { sessionId: knownSessionId } : {}),
});
- this.emitEvent({ type: 'failed', scheduleId: schedule.id, runId, error: runError });
+ this.emitFailed(schedule.id, runId, runError, knownSessionId);
} else if (skipped) {
// 前置检查拦截(preRunHook exit 2):run 记录保留为 'skipped'(与 deferred 的
// "撤销不留痕"不同——跳过是本轮的最终结果,用户要能在历史里看到"这几轮是
@@ -1067,6 +1073,8 @@ export class Scheduler extends EventEmitter {
let deferred = false;
let deferRetryMs: number | undefined;
let skipped = false;
+ // unregisterInflight 会清掉 session 映射,终态 emit 必须用 finally 之前捕获的值。
+ let knownSessionId: string | undefined;
this.updateInflightAttempt(runId, 'running');
try {
if (schedule.targetSessionId) {
@@ -1093,6 +1101,7 @@ export class Scheduler extends EventEmitter {
} catch (err) {
runError = err instanceof Error ? err.message : String(err);
} finally {
+ knownSessionId = this.resolveTerminalSessionId(runId, runSessionId, schedule.targetSessionId);
this.unregisterInflight(schedule.id, runId);
this.updateInflightAttempt(runId, 'finalizing');
}
@@ -1143,8 +1152,13 @@ export class Scheduler extends EventEmitter {
// try/finally 的理由同 fireOneInner:落库失败不能把唯一的失败提醒一起吞掉。
// 这里刻意不 catch —— runNow 是用户主动触发,落库失败照旧向调用方冒泡。
try {
- await this.storage.updateRun(runId, { status: 'failed', finishedAt, errorMsg });
- this.emitEvent({ type: 'failed', scheduleId: schedule.id, runId, error: errorMsg });
+ await this.storage.updateRun(runId, {
+ status: 'failed',
+ finishedAt,
+ errorMsg,
+ ...(knownSessionId ? { sessionId: knownSessionId } : {}),
+ });
+ this.emitFailed(schedule.id, runId, errorMsg, knownSessionId);
} finally {
if (this.needsForcedFailureNotification(runId)) {
void this.notifyForcedFailure(schedule.id, runId, errorMsg);
@@ -1156,15 +1170,17 @@ export class Scheduler extends EventEmitter {
finishedAt,
errorMsg: 'cancelled by user (schedule deleted or paused)',
readAt: finishedAt,
+ ...(knownSessionId ? { sessionId: knownSessionId } : {}),
});
- this.emitEvent({ type: 'failed', scheduleId: schedule.id, runId, error: 'aborted' });
+ this.emitFailed(schedule.id, runId, 'aborted', knownSessionId);
} else if (runError !== undefined) {
await this.storage.updateRun(runId, {
status: 'failed',
finishedAt,
errorMsg: runError,
+ ...(knownSessionId ? { sessionId: knownSessionId } : {}),
});
- this.emitEvent({ type: 'failed', scheduleId: schedule.id, runId, error: runError });
+ this.emitFailed(schedule.id, runId, runError, knownSessionId);
} else if (skipped) {
// 前置检查拦截:语义同 fireOne 的 skipped 分支(run 保留为 'skipped'、生而
// 已读、不通知)。手动触发被 hook 拦下同样留痕,让用户点"立即运行"后能看到
@@ -1623,6 +1639,18 @@ export class Scheduler extends EventEmitter {
return [...this.inflightControllers.keys()];
}
+ /**
+ * 当前 in-flight run 的展示 / 通知策略快照。消费方在 hook 晚挂或事件丢失时用它
+ * 重建 silenced / schedulerOwned 标记;sessionId 尚未绑定时可为空。
+ */
+ listInflightRunPolicies(): SchedulerInflightRunPolicy[] {
+ return [...this.inflightControllers.keys()].map((runId) => ({
+ runId,
+ sessionId: this.runIdToSessionId.get(runId) ?? this.runIdToBoundSessionId.get(runId),
+ silenced: this.silencedRuns.has(runId),
+ }));
+ }
+
/**
* 把**指定的单条 in-flight run** 标记为"静默":任务内 agent 确认本轮无需用户
* 关注(如 PR 巡检无新动态)时,经 MCP 工具传自己这一轮的 runId 调用本方法。
@@ -2181,6 +2209,35 @@ export class Scheduler extends EventEmitter {
this.emit(e.type, e);
}
+ /**
+ * 终态归因用的 session。runner 回报优先,其次运行/绑定映射,最后才是 schedule
+ * 上的目标会话 —— 绑定前失败(目标会话校验拒绝等)没有映射,仍要把红点落到
+ * 用户绑定的那条任务上。空字符串视为没有回报,继续往下找。
+ */
+ private resolveTerminalSessionId(
+ runId: string,
+ resultSessionId?: string,
+ targetSessionId?: string,
+ ): string | undefined {
+ return (
+ resultSessionId ||
+ this.runIdToSessionId.get(runId) ||
+ this.runIdToBoundSessionId.get(runId) ||
+ targetSessionId ||
+ undefined
+ );
+ }
+
+ private emitFailed(scheduleId: string, runId: string, error: string, sessionId?: string): void {
+ this.emitEvent({
+ type: 'failed',
+ scheduleId,
+ runId,
+ error,
+ ...(sessionId ? { sessionId } : {}),
+ });
+ }
+
private findInflightScheduleId(runId: string): string | undefined {
for (const [scheduleId, runIds] of this.inflightByschedule) {
if (runIds.has(runId)) return scheduleId;
@@ -2578,7 +2635,11 @@ export class Scheduler extends EventEmitter {
set.delete(runId);
if (set.size === 0) this.inflightByschedule.delete(scheduleId);
}
- const sessionId = this.runIdToSessionId.get(runId);
+ const sessionId = this.resolveTerminalSessionId(
+ runId,
+ undefined,
+ this.activeSchedules.get(scheduleId)?.targetSessionId,
+ );
if (sessionId !== undefined) {
if (this.sessionIdToRunId.get(sessionId) === runId) this.sessionIdToRunId.delete(sessionId);
this.runIdToSessionId.delete(runId);
@@ -2605,7 +2666,7 @@ export class Scheduler extends EventEmitter {
// nextFireAt 也没人补,而新任务照常放行(review #944 第十三轮 P1)。
attempt.forceReleaseOwnsCleanup = true;
try {
- await this.finishForceReleasedRun(attempt, now, noProgressMs);
+ await this.finishForceReleasedRun(attempt, now, noProgressMs, sessionId);
} finally {
// 唯一的槽位释放出口(收口成功 / 落库失败 / 抛错都要走到)。
attempt.forceReleaseOwnsCleanup = false;
@@ -2618,6 +2679,7 @@ export class Scheduler extends EventEmitter {
attempt: InflightAttempt,
now: number,
noProgressMs: number,
+ sessionId?: string,
): Promise<void> {
const { runId, scheduleId } = attempt;
const errorMsg =
@@ -2632,6 +2694,7 @@ export class Scheduler extends EventEmitter {
status: 'failed',
finishedAt: now,
errorMsg,
+ ...(sessionId ? { sessionId } : {}),
})) !== null;
} catch (err) {
this.logger?.warn?.('scheduler: stalled run updateRun failed', { runId, error: String(err) });
@@ -2660,7 +2723,7 @@ export class Scheduler extends EventEmitter {
}
return;
}
- this.emitEvent({ type: 'failed', scheduleId, runId, error: errorMsg });
+ this.emitFailed(scheduleId, runId, errorMsg, sessionId);
// 迟到 settle 的 runner 可能已经先投过失败通知(第十三轮起 attempt 在收口期间保留,
// 所以 onRunnerNotified 的记录此刻是可读的)。两侧都自查才能做到"恰好一条":
// runner 先投 → 这里跳过;这里先投 → runner 经 isRunAbandoned 跳过
diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.ts
index 67af2e1546..9d880d8753 100644
--- a/packages/maker-scheduler/src/types.ts
+++ b/packages/maker-scheduler/src/types.ts
@@ -86,6 +86,16 @@ export interface SchedulerRuntimeSnapshot {
waitingSchedules: SchedulerWaitingSchedule[];
}
+/**
+ * 一条 in-flight run 的展示 / 通知策略快照。给 renderer 在事件丢失或 hook 晚挂时
+ * 重建 silenced / schedulerOwned 标记。sessionId 在绑定之前可能为空。
+ */
+export interface SchedulerInflightRunPolicy {
+ runId: string;
+ sessionId?: string;
+ silenced: boolean;
+}
+
/**
* script 模式可授予的全量能力目录(单一来源):引擎校验白名单与 UI 能力选择器
* 都从这里枚举——host 侧新增能力时只改这一处,选择器自动出现新项。
@@ -378,7 +388,7 @@ export interface ListFilter {
export type SchedulerEvent =
| { type: 'fired'; scheduleId: string; runId: string; silent?: boolean }
| { type: 'completed'; scheduleId: string; runId: string; sessionId: string; silenced?: boolean }
- | { type: 'failed'; scheduleId: string; runId: string; error: string }
+ | { type: 'failed'; scheduleId: string; runId: string; error: string; sessionId?: string }
/**
* In-flight run 已被标记静默。该事件早于后续 agent done/completed 收口,
* 消费方用它抑制普通 session completion attention;completed.silenced
diff --git a/packages/maker-shared/src/__tests__/scheduleEvents.test.ts b/packages/maker-shared/src/__tests__/scheduleEvents.test.ts
index 6148b4fae5..25ef37db1f 100644
--- a/packages/maker-shared/src/__tests__/scheduleEvents.test.ts
+++ b/packages/maker-shared/src/__tests__/scheduleEvents.test.ts
@@ -69,6 +69,46 @@ describe('shared scheduler event projection', () => {
expect(projectScheduleEvent({ type: 'deferred', scheduleId: 'sched-1', runId: 'run-1' }).runPatch.status).toBe('deferred');
});
+ it('projects optional failed sessionId without requiring it', () => {
+ expect(normalizeSchedulerEvent({
+ type: 'failed',
+ scheduleId: 's1',
+ runId: 'r1',
+ error: 'boom',
+ })).toEqual({
+ type: 'failed',
+ scheduleId: 's1',
+ runId: 'r1',
+ error: 'boom',
+ });
+ expect(normalizeSchedulerEvent({
+ type: 'failed',
+ scheduleId: 's1',
+ runId: 'r1',
+ error: 'boom',
+ sessionId: 'chat-1',
+ })).toEqual({
+ type: 'failed',
+ scheduleId: 's1',
+ runId: 'r1',
+ error: 'boom',
+ sessionId: 'chat-1',
+ });
+ expect(projectScheduleEvent({
+ type: 'failed',
+ scheduleId: 'sched-1',
+ runId: 'run-1',
+ error: 'boom',
+ sessionId: 'chat-1',
+ }).runPatch.sessionId).toBe('chat-1');
+ expect(projectScheduleEvent({
+ type: 'failed',
+ scheduleId: 'sched-1',
+ runId: 'run-1',
+ error: 'boom',
+ }).runPatch.sessionId).toBeNull();
+ });
+
it('routes skipped (pre-run hook) events without touching unread badges', () => {
expect(normalizeSchedulerEvent({ type: 'skipped', scheduleId: 's1', runId: 'r1', sessionId: 'trace-1' })).toEqual({
type: 'skipped',
diff --git a/packages/maker-shared/src/scheduleEvents.ts b/packages/maker-shared/src/scheduleEvents.ts
index 35f052ab63..52b1fe3194 100644
--- a/packages/maker-shared/src/scheduleEvents.ts
+++ b/packages/maker-shared/src/scheduleEvents.ts
@@ -1,7 +1,7 @@
export type SchedulerEvent =
| { type: 'fired'; scheduleId: string; runId: string }
| { type: 'completed'; scheduleId: string; runId: string; sessionId: string }
- | { type: 'failed'; scheduleId: string; runId: string; error: string }
+ | { type: 'failed'; scheduleId: string; runId: string; error: string; sessionId?: string }
| { type: 'deferred'; scheduleId: string; runId: string }
/** 前置检查脚本(preRunHook)exit 2 拦截:run 记 'skipped' 生而已读;sessionId 为留痕会话 id,可为空串(留痕失败时)。 */
| { type: 'skipped'; scheduleId: string; runId: string; sessionId: string }
@@ -62,7 +62,10 @@ export function normalizeSchedulerEvent(value: unknown): NormalizedSchedulerEven
const scheduleId = readString(value.scheduleId);
const runId = readString(value.runId);
if (!scheduleId || !runId) return unknownEvent(type);
- return { type, scheduleId, runId, error: readString(value.error) ?? '' };
+ const sessionId = readString(value.sessionId);
+ return sessionId
+ ? { type, scheduleId, runId, error: readString(value.error) ?? '', sessionId }
+ : { type, scheduleId, runId, error: readString(value.error) ?? '' };
}
case 'skipped': {
// sessionId 与 completed 不同**允许空串**:desktop engine 在留痕会话创建失败时
@@ -141,7 +144,7 @@ export function projectNormalizedScheduleEvent(event: NormalizedSchedulerEvent):
scheduleList: false,
sessionIndex: true,
unreadSummary: true,
- }, 'may-increase', runPatch(event.scheduleId, event.runId, null, 'terminal'));
+ }, 'may-increase', runPatch(event.scheduleId, event.runId, event.sessionId ?? null, 'terminal'));
case 'session-bound':
return projection(event, {
runRefresh: { mode: 'schedule', scheduleId: event.scheduleId },