Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): await source ownership across completion notification paths
zqchrisa64f86a58891
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex cd52e6bbb8..6b6c4f0d2c 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -530,6 +530,64 @@ describe('AgentIslandService native publishing', () => {await import('../service.js');});+ it.each([true, false])('waits across status Done → native done for the shared local/remote completion decision (%s)', async handled => {+ const { AgentIslandService } = await import('../service.js');+ const remoteEvents: string[] = [];+ const controller = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, headless: true, publish: () => true, suspend: () => undefined },+ onDeviceSessionEvent: event => remoteEvents.push(event.kind),+ });+ controller.setEnabled(false);+ mocks.tapWindowBroadcast.mockImplementation((channel, payload) => {+ if (channel !== SESSION_ACTIVITY_CHANNEL) return;+ controller.setDeviceSessions([{+ ...payload,+ deviceId: 'execution-host',+ deviceName: 'Host',+ title: 'Delegated task',+ detail: payload.compactDetail,+ }]);+ });+ let settlement: Promise<boolean> | undefined;+ let resolve!: (handled: boolean) => void;+ const check = vi.fn(async () => await settlement ?? false);+ const source = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, headless: true, publish: () => true, suspend: () => undefined },+ isCompletionHandledByTeammate: check,+ });+ source.setEnabled(false);+ const meta = { sessionId: 'delegated-status-done', agentKind: 'codex' as const };+ source.handleUserPrompt(meta, 'run task');+ source.handleAgentEvent(meta, textEvent('Final result', true));+ source.handleAgentEvent(meta, { type: 'status', source: 'codex', data: { status: 'Done', isRunning: false } });+ // Native events cross separate iterator awaits. A microtask delay at status+ // Done alone must never decide ownership before the later done boundary.+ for (let i = 0; i < 5; i++) await Promise.resolve();+ expect(check).not.toHaveBeenCalled();+ expect(remoteEvents).toEqual([]);+ const localDecision = source.waitForCompletionNotification(meta.sessionId);+ expect(localDecision).toBeDefined();+ expect(source.getSessionActivitySnapshot(meta.sessionId)).toMatchObject({ phase: 'completed', attention: true });+ source.handleAgentEvent(meta, doneEvent());+ // The synchronous terminal adapter registers settlement after island delivery.+ settlement = new Promise<boolean>(r => { resolve = r; });+ await Promise.resolve();+ expect(check).toHaveBeenCalledOnce();+ expect(remoteEvents).toEqual([]);+ resolve(handled);+ await expect(localDecision).resolves.toBe(handled);+ expect(remoteEvents).toEqual(handled ? [] : ['done']);+ source.handleAgentEvent(meta, doneEvent());+ source.replaySessionActivity();+ expect(check).toHaveBeenCalledOnce();+ expect(remoteEvents).toEqual(handled ? [] : ['done']);+ expect(source.getSessionActivitySnapshot(meta.sessionId)).toMatchObject({ phase: 'completed', attention: true });+ source.resetRuntimeState(); controller.resetRuntimeState();+ mocks.tapWindowBroadcast.mockReset();+ });+it('keeps compact activity broadcasting alive in headless mode', async () => {const { AgentIslandService } = await import('../service.js');const service = new AgentIslandService({diff --git a/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts b/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.tsindex a3ac07111a..d0e7115671 100644--- a/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts@@ -43,12 +43,14 @@ describe('SessionActivityRelay', () => {relay.publish([done]);expect(emit).toHaveBeenLastCalledWith(expect.objectContaining({ phase: 'completed', attention: true, compactDetail: 'Final result', completionNotification: 'pending' }));relay.publish([done]);+ await Promise.resolve();expect(check).toHaveBeenCalledOnce();const replay = vi.fn();relay.replay([done], replay);expect(replay).toHaveBeenLastCalledWith(emit.mock.calls[0][0]);resolve(handled);- await Promise.resolve(); await Promise.resolve();+ await check.mock.results[0].value;+ await vi.advanceTimersByTimeAsync(0);expect(emit).toHaveBeenLastCalledWith(expect.objectContaining({ phase: 'completed', attention: true, completionNotification: handled ? 'teammate' : undefined }));relay.publish([done]);expect(emit).toHaveBeenCalledTimes(2);@@ -61,13 +63,16 @@ describe('SessionActivityRelay', () => {const emit = vi.fn();const relay = new SessionActivityRelay(emit, { isCompletionHandledByTeammate: () => new Promise<boolean>(r => { resolve = r; }) });relay.publish([activity('s1', 'Done', { phase: 'completed', attention: true })]);+ await Promise.resolve();+ const decision = relay.waitForCompletionNotification('s1');if (boundary === 'running') relay.publish([activity('s1', 'New turn', { startedAtMs: 2 })]);if (boundary === 'read') relay.publish([]);if (boundary === 'reset') relay.reset();if (boundary === 'dispose') relay.dispose();+ await expect(decision).resolves.toBe(true);const count = emit.mock.calls.length;resolve(true);- await Promise.resolve(); await Promise.resolve();+ await vi.advanceTimersByTimeAsync(0);expect(emit).toHaveBeenCalledTimes(count);});diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex 8149bd408f..f65bfdec65 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -683,6 +683,10 @@ export class AgentIslandService {}}+ waitForCompletionNotification(sessionId: string): Promise<boolean> | undefined {+ return this.sessionActivityRelay.waitForCompletionNotification(sessionId);+ }+resetRuntimeState(): void {this.clearPublishTimer();this.clearStreamingPreviewPublishTimer();@@ -841,6 +845,9 @@ export class AgentIslandService {}}const suppressCompletionAttention = this.isCompletionEventSilenced(hydrated.sessionId, event);+ if (isCompletionDoneEvent(event) && event.type === 'status') {+ this.sessionActivityRelay.awaitCompletionTerminal(hydrated.sessionId);+ }const changed = applyAgentIslandEvent(this.state, hydrated, event, now, {suppressCompletionAttention,// Direct IM sends bypass handleUserPrompt. Running preserves unread in the@@ -857,6 +864,9 @@ export class AgentIslandService {if (suppressCompletionAttention) {this.mutedCompletionSoundSessionIds.add(hydrated.sessionId);}+ if (isCompletionDoneEvent(event) && event.type === 'done') {+ this.sessionActivityRelay.completeTerminal(hydrated.sessionId);+ }if (!changed) return;this.ensureMetadata(hydrated.sessionId);if (!suppressCompletionAttention) {diff --git a/apps/desktop/src/main/agent-island/sessionActivityRelay.ts b/apps/desktop/src/main/agent-island/sessionActivityRelay.tsindex 05318cc649..9a11b56bac 100644--- a/apps/desktop/src/main/agent-island/sessionActivityRelay.ts+++ b/apps/desktop/src/main/agent-island/sessionActivityRelay.ts@@ -21,6 +21,14 @@ interface SessionActivityRelayEntry {timer: Timer | null;}+interface CompletionCheck {+ startedAtMs: number | null;+ payload: SessionActivityPayload;+ checking: boolean;+ decision: Promise<boolean>;+ resolve: (handled: boolean) => void;+}+/*** Per-session throttle for list-level Agent Island activity pushes.* It keeps the `sessions` topic low-frequency while still sending terminal@@ -33,9 +41,8 @@ export class SessionActivityRelay {private readonly clearTimer: (timer: Timer) => void;private readonly entries = new Map<string, SessionActivityRelayEntry>();private readonly terminalReplayPayloads = new Map<string, SessionActivityPayload>();- private readonly completionChecks = new Map<string, {- startedAtMs: number | null; payload: SessionActivityPayload;- }>();+ private readonly completionChecks = new Map<string, CompletionCheck>();+ private readonly awaitingTerminal = new Set<string>();private readonly checkCompletion?: (sessionId: string) => Promise<boolean>;constructor(@@ -58,7 +65,8 @@ export class SessionActivityRelay {if (this.checkCompletion && payload.phase === 'completed' && payload.attention) {this.publishCompletion(activity, payload);} else {- this.completionChecks.delete(activity.sessionId);+ this.awaitingTerminal.delete(activity.sessionId);+ this.cancelCompletionCheck(activity.sessionId);this.publishOne(payload);}}@@ -73,7 +81,8 @@ export class SessionActivityRelay {for (const entry of this.entries.values()) {if (entry.timer) this.clearTimer(entry.timer);}- this.completionChecks.clear();+ for (const sessionId of this.completionChecks.keys()) this.cancelCompletionCheck(sessionId);+ this.awaitingTerminal.clear();this.entries.clear();this.terminalReplayPayloads.clear();}@@ -83,12 +92,35 @@ export class SessionActivityRelay {* Runtime reset should not leave remote lists showing stale running rows.*/reset(): void {- this.completionChecks.clear();+ for (const sessionId of this.completionChecks.keys()) this.cancelCompletionCheck(sessionId);+ this.awaitingTerminal.clear();for (const sessionId of [...this.entries.keys()]) {this.clear(sessionId);}}+ /** A status completion precedes the native done/result handoff boundary. */+ awaitCompletionTerminal(sessionId: string): void {+ if (this.checkCompletion && !this.completionChecks.has(sessionId)) this.awaitingTerminal.add(sessionId);+ }++ completeTerminal(sessionId: string): void {+ this.awaitingTerminal.delete(sessionId);+ const check = this.completionChecks.get(sessionId);+ if (check) this.checkCompletionOwnership(sessionId, check);+ }++ /** Local notification channels share the source relay's same terminal decision. */+ waitForCompletionNotification(sessionId: string): Promise<boolean> | undefined {+ return this.completionChecks.get(sessionId)?.decision;+ }++ private cancelCompletionCheck(sessionId: string): void {+ // A new turn/read/reset supersedes this event; never release its stale notice.+ this.completionChecks.get(sessionId)?.resolve(true);+ this.completionChecks.delete(sessionId);+ }+/*** 已读回执的收尾包兜底:entries 里**没有**该会话条目时,补发一帧收尾包(幂等,* 远端删除不存在的条目是 no-op)并记入 terminal replay(重连 replay 时补发,@@ -143,13 +175,31 @@ export class SessionActivityRelay {this.publishOne(previous.payload);return;}- const check = { startedAtMs: activity.startedAtMs, payload: { ...payload, completionNotification: 'pending' as const } as SessionActivityPayload };+ this.cancelCompletionCheck(activity.sessionId);+ let resolve!: (handled: boolean) => void;+ const check: CompletionCheck = {+ startedAtMs: activity.startedAtMs,+ payload: { ...payload, completionNotification: 'pending' },+ checking: false,+ decision: new Promise<boolean>(r => { resolve = r; }),+ resolve: handled => resolve(handled),+ };this.completionChecks.set(activity.sessionId, check);this.publishOne(check.payload);- void this.checkCompletion!(activity.sessionId).catch(() => false).then((handled) => {+ if (!this.awaitingTerminal.has(activity.sessionId)) this.checkCompletionOwnership(activity.sessionId, check);+ }++ private checkCompletionOwnership(sessionId: string, check: CompletionCheck): void {+ if (check.checking) return;+ check.checking = true;+ // The event adapter registers settlement later in the same synchronous done+ // delivery. No status event or timer can decide ownership before that point.+ void Promise.resolve().then(() => this.completionChecks.get(sessionId) === check+ ? this.checkCompletion!(sessionId) : true).catch(() => false).then((handled) => {// A new turn, read acknowledgement, reset or disposal invalidates the old check.- if (this.completionChecks.get(activity.sessionId) !== check) return;+ if (this.completionChecks.get(sessionId) !== check) return;check.payload = { ...check.payload, completionNotification: handled ? 'teammate' : undefined };+ check.resolve(handled);this.publishOne(check.payload);});}@@ -200,7 +250,8 @@ export class SessionActivityRelay {}private clear(sessionId: string): void {- this.completionChecks.delete(sessionId);+ this.awaitingTerminal.delete(sessionId);+ this.cancelCompletionCheck(sessionId);const entry = this.entries.get(sessionId);if (!entry) return;if (entry.timer) this.clearTimer(entry.timer);diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex f2e9c816cb..8a81700c36 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -4315,15 +4315,15 @@ const registerIpcHandlers = () => {const isCompletionHandledByTeammate = (sessionId: string): Promise<boolean> =>tryGetBotDelegationService()?.isCompletionHandledByTeammate(sessionId) ?? Promise.resolve(false);initNotificationService({- isCompletionHandledByTeammate,+ isCompletionHandledByTeammate: (sessionId) => getAgentIslandService()?.waitForCompletionNotification(sessionId)+ ?? isCompletionHandledByTeammate(sessionId),getWindow: () => getWindow() ?? null,feishuIm,});initWecomGroupNotificationIpc();initAgentIslandService({- // Activity is published before the synchronous terminal adapter registers- // settlement. Defer the lookup until that adapter has run, without polling.- isCompletionHandledByTeammate: (sessionId) => Promise.resolve().then(() => isCompletionHandledByTeammate(sessionId)),+ // The relay waits for native done before checking the durable result handoff.+ isCompletionHandledByTeammate,getMainWindow: () => getWindow() ?? null,isPlannedRemoteDaemonClose: isCcMgrUpgradeInFlight,onSessionActivityChange: (activity) => {diff --git a/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts b/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.tsindex 9e5ac1a20b..5c98b26255 100644--- a/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts@@ -6,6 +6,8 @@ import {findSessionNotificationSession,sendSessionEventNotification,} from '@/lib/sessionEventNotification';+import { applyRemoteSessionActivity, clearRemoteSessionActivity, getRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';+import { SessionActivityRelay } from '../../main/agent-island/sessionActivityRelay';const gates = vi.hoisted(() => ({desktop: true,@@ -30,6 +32,7 @@ const showSessionEvent = vi.fn(() => Promise.resolve());describe('shared session event notifications', () => {beforeEach(() => {+ clearRemoteSessionActivity();gates.desktop = true;gates.feishu = false;gates.islandEnabled = false;@@ -44,6 +47,7 @@ describe('shared session event notifications', () => {});afterEach(() => {+ clearRemoteSessionActivity();vi.restoreAllMocks();});@@ -90,6 +94,64 @@ describe('shared session event notifications', () => {);});+ it.each([true, false])('uses the execution host decision for remote mobile/Feishu completion calls (%s)', async handled => {+ gates.feishu = true;+ let resolve!: (handled: boolean) => void;+ const relay = new SessionActivityRelay(payload => applyRemoteSessionActivity('host', payload), {+ isCompletionHandledByTeammate: () => new Promise<boolean>(r => { resolve = r; }),+ });+ const running = { sessionId: 'remote-task', phase: 'running', recordStatus: 'active', compactDetail: 'Working', startedAtMs: 1, lastActivityAtMs: 1, currentActionSummary: 'Working', attention: false, workflow: null, turnGeneration: null, gracefulStopState: 'none', source: 'live' } as const;+ relay.publish([running]);+ // The native renderer transition can precede the activity relay frame.+ sendSessionEventNotification('remote-task', 'Task', 'done', { remoteDevice: true, remoteDeviceId: 'host' });+ expect(showSessionEvent).not.toHaveBeenCalled();+ relay.awaitCompletionTerminal('remote-task');+ const completed = { ...running, phase: 'completed' as const, attention: true, compactDetail: 'Final result' };+ relay.publish([completed]);+ sendSessionEventNotification('remote-task', 'Task', 'done', { remoteDevice: true, remoteDeviceId: 'host' });+ expect(showSessionEvent).not.toHaveBeenCalled();+ relay.completeTerminal('remote-task');+ await Promise.resolve();+ resolve(handled);+ await relay.waitForCompletionNotification('remote-task');+ expect(showSessionEvent).toHaveBeenCalledTimes(handled ? 0 : 1);+ if (!handled) expect(showSessionEvent).toHaveBeenCalledWith({ sessionId: 'remote-task', title: 'Task', kind: 'done', markAttention: false, channels: { desktop: false, feishu: true, mobile: true } });+ expect(markAttention).not.toHaveBeenCalled();+ expect(getRemoteSessionActivity('remote-task', 'host')).toMatchObject({ phase: 'completed', attention: true, compactDetail: 'Final result' });+ relay.replay([completed]);+ expect(showSessionEvent).toHaveBeenCalledTimes(handled ? 0 : 1);+ relay.dispose();+ });++ it.each(['running', 'read', 'error', 'needs-interaction'])('discards a pending remote completion on %s without losing action/error reminders', boundary => {+ gates.feishu = true;+ applyRemoteSessionActivity('host', { sessionId: 'remote-task', phase: 'completed', attention: true, completionNotification: 'pending' });+ sendSessionEventNotification('remote-task', 'Task', 'done', { remoteDevice: true, remoteDeviceId: 'host' });+ applyRemoteSessionActivity('host', { sessionId: 'remote-task', phase: boundary === 'read' ? 'completed' : boundary, attention: boundary !== 'read' });+ expect(showSessionEvent).not.toHaveBeenCalled();+ if (boundary === 'error' || boundary === 'needs-interaction') {+ sendSessionEventNotification('remote-task', 'Task', boundary === 'error' ? 'error' : 'needs-reply', { remoteDevice: true, remoteDeviceId: 'host' });+ expect(showSessionEvent).toHaveBeenCalledWith(expect.objectContaining({ kind: boundary === 'error' ? 'error' : 'needs-reply', channels: { desktop: false, feishu: true, mobile: true } }));+ }+ });++ it.each(['focus', 'preferences'])('rechecks %s when remote handoff releases an ordinary completion', boundary => {+ gates.feishu = true;+ applyRemoteSessionActivity('host', { sessionId: 'remote-task', phase: 'completed', attention: true, completionNotification: 'pending' });+ sendSessionEventNotification('remote-task', 'Task', 'done', { remoteDevice: true, remoteDeviceId: 'host' });+ if (boundary === 'focus') vi.mocked(document.hasFocus).mockReturnValue(true);+ else gates.feishu = false;+ applyRemoteSessionActivity('host', { sessionId: 'remote-task', phase: 'completed', attention: true });+ if (boundary === 'focus') expect(showSessionEvent).not.toHaveBeenCalled();+ else expect(showSessionEvent).toHaveBeenCalledWith(expect.objectContaining({ channels: { desktop: false, feishu: false, mobile: true } }));+ });++ it('keeps old-host remote completion calls unchanged', () => {+ applyRemoteSessionActivity('old-host', { sessionId: 'legacy', phase: 'completed', attention: true });+ sendSessionEventNotification('legacy', 'Task', 'done', { remoteDevice: true, remoteDeviceId: 'old-host' });+ expect(showSessionEvent).toHaveBeenCalledWith(expect.objectContaining({ kind: 'done', channels: { desktop: false, feishu: false, mobile: true } }));+ });+it('does not send external notifications while the user is already looking at Cindy', () => {vi.mocked(document.hasFocus).mockReturnValue(true);diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex bd31c31dd6..61c423edd7 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -1148,6 +1148,7 @@ function ExpandedView({const title = projectDraftSessionTitle(session.title, unnamedLabelRef.current);sendSessionEventNotification(sessionId, title, kind, {remoteDevice: !!session.deviceLinkDeviceId,+ remoteDeviceId: session.deviceLinkDeviceId,});return;}diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts b/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.tsindex 4d45925252..3ef25d3cad 100644--- a/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts+++ b/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts@@ -71,10 +71,11 @@ describe('buildAgentIslandRemoteSessionInputs', () => {const activity = { sessionId: 'a-1', phase: 'running' as const, recordStatus: 'active', compactDetail: 'Working', startedAtMs: 1, lastActivityAtMs: 1, currentActionSummary: 'Working', attention: false, workflow: null, turnGeneration: null, gracefulStopState: 'none', source: 'live' } as const;relay.publish([activity]);relay.publish([{ ...activity, phase: 'completed', attention: true, compactDetail: 'Final result' }]);+ await Promise.resolve();expect(events).toEqual([]);expect(getRemoteSessionActivity('a-1', 'device-a')).toMatchObject({ phase: 'completed', attention: true, compactDetail: 'Final result' });resolve(handled);- await Promise.resolve(); await Promise.resolve();+ await relay.waitForCompletionNotification('a-1');expect(events).toEqual(handled ? [] : ['done']);relay.replay([{ ...activity, phase: 'completed', attention: true }]);expect(events).toEqual(handled ? [] : ['done']);diff --git a/apps/desktop/src/renderer/lib/sessionEventNotification.ts b/apps/desktop/src/renderer/lib/sessionEventNotification.tsindex ef7e0bac89..44375c2008 100644--- a/apps/desktop/src/renderer/lib/sessionEventNotification.ts+++ b/apps/desktop/src/renderer/lib/sessionEventNotification.ts@@ -2,6 +2,7 @@ import { getAgentIslandEnabled, isAgentIslandSupported } from '@/hooks/useAgentIimport { getFeishuNotificationsEnabled } from '@/hooks/useFeishuNotificationSettings';import { getNotificationsEnabled } from '@/hooks/useNotificationSettings';import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';+import { getRemoteSessionActivity, subscribeRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';export type SessionEventNotificationKind = 'done' | 'error' | 'needs-reply';@@ -77,14 +78,59 @@ export function sendSessionEventNotification(* (agentIslandRemoteSessions),这里不再弹;未读归属那台设备,不记本机 Dock 角标。*/remoteDevice?: boolean;+ remoteDeviceId?: string | null;} = {},): void {// The user is already looking at Cindy. In-app attention remains available,// but an OS/external notification would be duplicate noise.if (typeof document !== 'undefined' && document.hasFocus()) return;+ if (kind === 'done' && options.remoteDeviceId) {+ sendRemoteCompletionNotification(sessionId, options.remoteDeviceId, () =>+ deliverSessionEventNotification(sessionId, title, kind, true));+ return;+ }++ deliverSessionEventNotification(sessionId, title, kind, options.remoteDevice === true);+}++const pendingRemoteCompletions = new Map<string, () => void>();++/** The execution host owns this decision; the controller has no delegation DB row. */+function sendRemoteCompletionNotification(sessionId: string, deviceId: string, deliver: () => void): void {+ const key = JSON.stringify([deviceId, sessionId]);+ if (pendingRemoteCompletions.has(key)) return;+ const activity = getRemoteSessionActivity(sessionId, deviceId);+ if (activity?.phase === 'completed' && activity.completionNotification === 'teammate') return;+ if (activity?.phase === 'error' || activity?.phase === 'needs-interaction') return;+ if (!activity || (activity.phase === 'completed' && activity.completionNotification !== 'pending')) {+ deliver(); // Older hosts retain their original notification behavior.+ return;+ }+ let sawPendingCompletion = activity.phase === 'completed';+ const cancel = subscribeRemoteSessionActivity((changedDeviceId, changedSessionId) => {+ if (changedDeviceId && changedDeviceId !== deviceId) return;+ if (changedSessionId && changedSessionId !== sessionId) return;+ const latest = getRemoteSessionActivity(sessionId, deviceId);+ if (latest?.phase === 'completed' && latest.completionNotification === 'pending') {+ sawPendingCompletion = true;+ return;+ }+ if (latest?.phase === 'running' && !sawPendingCompletion) return;+ cancel();+ pendingRemoteCompletions.delete(key);+ // Read, disconnect, error, interaction or a replacement turn supersedes this+ // completion request. Only the source's resolved ordinary completion sends.+ if (latest?.phase === 'completed' && latest.completionNotification !== 'teammate') deliver();+ });+ pendingRemoteCompletions.set(key, cancel);+}++function deliverSessionEventNotification(sessionId: string, title: string, kind: SessionEventNotificationKind, remoteDevice: boolean): void {+ // A handoff can finish after the user has opened Cindy or changed preferences.+ if (typeof document !== 'undefined' && document.hasFocus()) return;+const islandActive = isAgentIslandSupported() && getAgentIslandEnabled();- const remoteDevice = options.remoteDevice === true;if (!remoteDevice) void window.electronAPI.notificationMarkSessionAttention(sessionId);void window.electronAPI.notificationShowSessionEvent({sessionId,diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 1e7e880532..6e73f75361 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1020,12 +1020,16 @@ Mobile 据此区分已关闭与已删除的旧选择:保留任务或草稿原## 委派任务的完成通知归属-既有 `SessionActivityPayload` 可选字段 `completionNotification` 只影响远端桌面完成通知:+既有 `SessionActivityPayload` 可选字段 `completionNotification` 影响远端桌面、手机与飞书完成通知:`pending` 表示该轮终态回传正在判定,`teammate` 表示同一委派执行结果已成功交回伙伴;缺省或未知值按普通任务完成通知处理。完成 phase、摘要和 attention 在 pending 阶段照常发送,-回传决定通过同一活动通道更新;控制端仅对已观察运行的任务补发必要 fallback 一次,重连的+回传决定通过同一活动通道更新;执行宿主等到真实 `done` 的回传边界再决定,前置+`status: Done` 不能提前消费归属。本机外部通知共用这一决定;控制端的手机/飞书调用+在活动仍运行或 `pending` 时等待同一活动通道更新,已回传伙伴则取消调用。已读、断开、+新一轮运行、报错或待交互使旧完成调用失效,不延迟错误与待答通知,也不更改任何未读。+控制端桌面仅对已观察运行的任务补发必要 fallback 一次,重连的基线终态不补发历史提醒。错误与待交互不受此字段影响。-新控制端连接旧执行端沿用原通知;旧控制端忽略该字段,仍可能发独立完成桌面通知,完整远端-去重需要两端更新。手机外部推送在执行端通知出口完成去重,手机无需新增协议处理;+新控制端连接旧执行端沿用原通知;旧控制端忽略该字段,仍可能发独立完成外部通知,完整远端+去重需要两端更新。手机外部推送在执行端及远控 Desktop 的通知出口完成去重,手机无需新增协议处理;移动列表继续原 phase/attention 语义。无需服务端、数据库 migration 或 Mobile fingerprint 改动。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 795d5f9fc6..4c8677ddbd 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -431,8 +431,10 @@ Session 任务遵守同一套机制与呈现契约:不另存一套 Bot 专用通知开关。- 已有委派执行回执的后台 Session 任务,只有同一原生执行轮次的结果已持久化并成功交回活跃发起伙伴时,才停止该执行任务独立的完成外部通知;随后由伙伴正常最终回复复用现有通知。- 回传失败、发起伙伴暂停/归档、审批、待答和错误保留原任务提醒。完成通知等待该轮已启动的- 终态回传尝试,不等待重试定时器;重复事件沿原通知去重账本消费,后续直接执行轮次恢复原语义。+ 回传失败、发起伙伴暂停/归档、审批、待答和错误保留原任务提醒。完成通知等待真实 `done`+ 边界及该轮已启动的终态回传尝试;前置 `status: Done` 仍同步状态和未读,但不提前决定通知归属。+ 本机各外部通道与活动中继共用该轮决定,远控 Desktop 的手机/飞书出口也消费执行宿主决定。+ 不等待重试定时器;重复事件沿原通知去重账本消费,后续直接执行轮次恢复原语义。普通任务不因目录上的伙伴头像静音;任务正文、结果回执、状态、未读与 Dock 不变。- 用户正在看对应任务时不发外部通知;后台时仍按全局桌面、飞书、移动端与灵动岛去重规则投递。- 伙伴私聊的结构化入口不触发通知;接收伙伴随后产出的正常回复才有提醒价值。