Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): deduplicate delegated task completion notifications
zqchris9fc1b0ebc1a8
diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.tsindex bd6b9a967b..1f01fd0bd3 100644--- a/apps/desktop/src/main/__tests__/notificationService.test.ts+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts@@ -198,6 +198,91 @@ describe('notificationService — channels 分发', () => {vi.useRealTimers();});+ it('hands off delegated completion on every external channel while preserving task attention and consuming retries', async () => {+ const { initNotificationService } = await freshService();+ const feishuIm = makeFeishuIm('owner');+ const check = vi.fn().mockResolvedValue(true);+ initNotificationService({ ...baseDeps(feishuIm), isCompletionHandledByTeammate: check });+ getSessionNotificationTurnSignal.mockReturnValue({ id: 'turn:100:200', fallbackEventId: 'turn:100:200', ended: true });+ const payload = { sessionId: 's1', title: 'Delegated', kind: 'done', channels: { desktop: true, feishu: true, mobile: true } };+ await invokeHandler(payload);+ expect(markSessionNeedsAttention).toHaveBeenCalledWith('s1');+ expect(notificationCtor).not.toHaveBeenCalled();+ expect(sendMobileSessionNotify).not.toHaveBeenCalled();+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ // Removing the relation cannot resurrect a previously consumed event.+ check.mockResolvedValue(false);+ getMobileNotifyGeneration.mockReturnValueOnce(8);+ await invokeHandler(payload);+ expect(notificationCtor).not.toHaveBeenCalled();+ expect(sendMobileSessionNotify).not.toHaveBeenCalled();+ getSessionNotificationTurnSignal.mockReturnValue({ id: 'turn:300:400', fallbackEventId: 'turn:300:400', ended: true });+ await invokeHandler(payload);+ expect(notificationCtor).toHaveBeenCalledOnce();+ expect(sendMobileSessionNotify).toHaveBeenCalledOnce();+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledOnce();+ });++ it('does not send an old completion when handoff resolution crosses a newer turn', async () => {+ const { initNotificationService } = await freshService();+ const feishuIm = makeFeishuIm('owner');+ let resolve!: (handled: boolean) => void;+ const check = vi.fn(() => new Promise<boolean>(r => { resolve = r; }));+ initNotificationService({ ...baseDeps(feishuIm), isCompletionHandledByTeammate: check });+ getSessionNotificationTurnSignal.mockReturnValue({ id: 'turn:100:200', fallbackEventId: 'turn:100:200', ended: true });+ await invokeHandler({ sessionId: 's1', title: 'Delegated', kind: 'done', channels: { desktop: true, feishu: true, mobile: true } });+ expect(check).toHaveBeenCalledOnce();+ getSessionNotificationTurnSignal.mockReturnValue({ id: 'turn:300:400', fallbackEventId: 'turn:300:400', ended: true });+ resolve(false); await flushAsync();+ expect(notificationCtor).not.toHaveBeenCalled();+ expect(sendMobileSessionNotify).not.toHaveBeenCalled();+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ expect(markSessionNeedsAttention).toHaveBeenCalledWith('s1');+ });++ it('notifies only the teammate final reply after handing off its child completion', async () => {+ const { initNotificationService } = await freshService();+ const feishuIm = makeFeishuIm('owner');+ initNotificationService({ ...baseDeps(feishuIm), isCompletionHandledByTeammate: async id => id === 'child' });+ readSessionNotificationPreview.mockImplementation(async id => id === 'teammate'+ ? { teammateName: 'Teammate', teammateBotId: 'bot-a', reply: { clientId: 'final', text: '**Final** result' }, eventId: 'final' }+ : { eventId: 'child-result' });+ const channels = { desktop: true, feishu: true, mobile: true };+ await invokeHandler({ sessionId: 'child', title: 'Background task', kind: 'done', channels });+ await invokeHandler({ sessionId: 'child', title: 'Background task', kind: 'done', channels });+ await invokeHandler({ sessionId: 'teammate', title: 'Teammate', kind: 'done', channels });+ await invokeHandler({ sessionId: 'teammate', title: 'Teammate', kind: 'done', channels });+ expect(notificationCtor).toHaveBeenCalledOnce();+ expect(notificationCtor).toHaveBeenCalledWith(expect.objectContaining({ body: 'Final result' }));+ expect(sendMobileSessionNotify).toHaveBeenCalledOnce();+ expect(sendMobileSessionNotify).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'teammate', teammateBotId: 'bot-a' }));+ expect(feishuIm.sendText).toHaveBeenCalledOnce();+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ });++ it.each(['error', 'needs-reply'])('keeps %s immediate even while a teammate completion check is blocked', async kind => {+ const { initNotificationService } = await freshService();+ const feishuIm = makeFeishuIm('owner');+ const check = vi.fn(() => new Promise<boolean>(() => {}));+ initNotificationService({ ...baseDeps(feishuIm), isCompletionHandledByTeammate: check });+ await invokeHandler({ sessionId: 's1', title: 'Delegated', kind, channels: { desktop: true, feishu: true, mobile: true } });+ expect(check).not.toHaveBeenCalled();+ expect(notificationCtor).toHaveBeenCalledOnce();+ expect(sendMobileSessionNotify).toHaveBeenCalledOnce();+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledOnce();+ });++ it.each([false, 'reject'])('retains completion fallback when internal handoff is unavailable (%s)', async outcome => {+ const { initNotificationService } = await freshService();+ const feishuIm = makeFeishuIm('owner');+ const check = outcome === false ? vi.fn().mockResolvedValue(false) : vi.fn().mockRejectedValue(new Error('fixture failure'));+ initNotificationService({ ...baseDeps(feishuIm), isCompletionHandledByTeammate: check });+ await invokeHandler({ sessionId: 's1', title: 'Delegated', kind: 'done', channels: { desktop: true, feishu: true, mobile: true } });+ expect(notificationCtor).toHaveBeenCalledOnce();+ expect(sendMobileSessionNotify).toHaveBeenCalledOnce();+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledOnce();+ });+it('同步并校验 renderer 持久化的桌面通知总开关', async () => {const { getDesktopNotificationsEnabled, initNotificationService } = await freshService();initNotificationService(baseDeps(makeFeishuIm('ou_owner')));diff --git a/apps/desktop/src/main/agent-island/__tests__/deviceSessions.test.ts b/apps/desktop/src/main/agent-island/__tests__/deviceSessions.test.tsindex 5e524e4838..4711cb2a9e 100644--- a/apps/desktop/src/main/agent-island/__tests__/deviceSessions.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/deviceSessions.test.ts@@ -37,6 +37,28 @@ function remote(}describe('Agent Island device sessions', () => {+ it.each(['teammate', undefined] as const)('resolves pending remote completion once without changing task state (%s)', completionNotification => {+ const state = createAgentIslandState();+ syncAgentIslandDeviceSessions(state, [remote('running')], 1_000);+ const pending = syncAgentIslandDeviceSessions(state, [remote('completed', { completionNotification: 'pending', detail: 'Result' })], 2_000);+ expect(pending.events).toEqual([]);+ expect(state.sessions.get('remote-1')).toMatchObject({ phase: 'completed', unread: true });+ const result = syncAgentIslandDeviceSessions(state, [remote('completed', { completionNotification, detail: 'Result' })], 3_000);+ expect(result.events.map(event => event.kind)).toEqual(completionNotification ? [] : ['done']);+ expect(syncAgentIslandDeviceSessions(state, [remote('completed', { completionNotification })], 4_000).events).toEqual([]);+ syncAgentIslandDeviceSessions(state, [remote('running')], 5_000);+ expect(syncAgentIslandDeviceSessions(state, [remote('completed')], 6_000).events.map(event => event.kind)).toEqual(['done']);+ });++ it('does not notify a first-seen pending completion and preserves action/error events', () => {+ const state = createAgentIslandState();+ syncAgentIslandDeviceSessions(state, [remote('completed', { completionNotification: 'pending' })], 1_000);+ expect(syncAgentIslandDeviceSessions(state, [remote('completed')], 2_000).events).toEqual([]);+ syncAgentIslandDeviceSessions(state, [remote('running')], 3_000);+ expect(syncAgentIslandDeviceSessions(state, [remote('needs-interaction', { completionNotification: 'teammate', interactionKind: 'permission' })], 4_000).events.map(event => event.kind)).toEqual(['needs-reply']);+ expect(syncAgentIslandDeviceSessions(state, [remote('error', { completionNotification: 'teammate' })], 5_000).events.map(event => event.kind)).toEqual(['error']);+ });+it('shows a first-seen remote task without revealing it or emitting an event', () => {const state = createAgentIslandState();const result = syncAgentIslandDeviceSessions(state, [remote('completed')], 1_000);diff --git a/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts b/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.tsindex 8d491d2894..a3ac07111a 100644--- a/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts@@ -34,6 +34,43 @@ describe('SessionActivityRelay', () => {vi.useRealTimers();});+ it.each([true, false])('publishes completion and unread immediately, then only resolves notification ownership (%s)', async handled => {+ let resolve!: (handled: boolean) => void;+ const check = vi.fn(() => new Promise<boolean>(r => { resolve = r; }));+ const emit = vi.fn();+ const relay = new SessionActivityRelay(emit, { isCompletionHandledByTeammate: check });+ const done = activity('s1', 'Final result', { phase: 'completed', attention: true });+ relay.publish([done]);+ expect(emit).toHaveBeenLastCalledWith(expect.objectContaining({ phase: 'completed', attention: true, compactDetail: 'Final result', completionNotification: 'pending' }));+ relay.publish([done]);+ 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();+ expect(emit).toHaveBeenLastCalledWith(expect.objectContaining({ phase: 'completed', attention: true, completionNotification: handled ? 'teammate' : undefined }));+ relay.publish([done]);+ expect(emit).toHaveBeenCalledTimes(2);+ relay.replay([done], replay);+ expect(replay).toHaveBeenLastCalledWith(emit.mock.calls[1][0]);+ });++ it.each(['running', 'read', 'reset', 'dispose'])('discards an old completion decision after %s', async boundary => {+ let resolve!: (handled: boolean) => void;+ 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 })]);+ 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();+ const count = emit.mock.calls.length;+ resolve(true);+ await Promise.resolve(); await Promise.resolve();+ expect(emit).toHaveBeenCalledTimes(count);+ });+it('bypasses throttling for unread terminal states arriving inside the window', () => {const emit = vi.fn();const relay = new SessionActivityRelay(emit, { minIntervalMs: 1_500 });diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex ad187eacb1..8149bd408f 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -176,6 +176,7 @@ interface AgentIslandUserPromptDebugMeta {}export interface AgentIslandServiceDeps {+ isCompletionHandledByTeammate?: (sessionId: string) => Promise<boolean>;getMainWindow: () => BrowserWindow | null;nativeHost?: AgentIslandNativeRenderer;/** Main-process upgrade window used to classify remote daemon shutdowns. */@@ -360,15 +361,16 @@ export class AgentIslandService {sessionId: string;request: Extract<InteractionRequest, { kind: 'permission' }>;}>();- private readonly sessionActivityRelay = new SessionActivityRelay((payload) => {- tapWindowBroadcast(SESSION_ACTIVITY_CHANNEL, payload);- });+ private readonly sessionActivityRelay: SessionActivityRelay;private permissionResolver: ((requestId: string, decision: AgentIslandPermissionDecision) => boolean) | null = null;private shouldDeferCompletion: ((sessionId: string) => boolean) | null = null;private layoutPreferenceWriteTimer: ReturnType<typeof setTimeout> | null = null;private streamingPreviewPublishTimer: ReturnType<typeof setTimeout> | null = null;constructor(private readonly deps: AgentIslandServiceDeps) {+ this.sessionActivityRelay = new SessionActivityRelay((payload) => {+ tapWindowBroadcast(SESSION_ACTIVITY_CHANNEL, payload);+ }, { isCompletionHandledByTeammate: deps.isCompletionHandledByTeammate });// lazy t() 闭包跟随 locale 运行时切换,注入一次即可(strings 仍每次 publish 重建)。setAgentIslandToolWording(this.state, createLocalizedToolRowWording());this.layoutPreferencesByDisplayId = readAgentIslandLayoutPreferences();diff --git a/apps/desktop/src/main/agent-island/sessionActivityRelay.ts b/apps/desktop/src/main/agent-island/sessionActivityRelay.tsindex 601efc98ed..05318cc649 100644--- a/apps/desktop/src/main/agent-island/sessionActivityRelay.ts+++ b/apps/desktop/src/main/agent-island/sessionActivityRelay.ts@@ -7,6 +7,7 @@ const MAX_REPLAY_TERMINAL_PAYLOADS = 200;type Timer = ReturnType<typeof setTimeout>;interface SessionActivityRelayOptions {+ isCompletionHandledByTeammate?: (sessionId: string) => Promise<boolean>;minIntervalMs?: number;now?: () => number;setTimer?: (fn: () => void, ms: number) => Timer;@@ -32,11 +33,16 @@ 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 checkCompletion?: (sessionId: string) => Promise<boolean>;constructor(private readonly emit: (payload: SessionActivityPayload) => void,options: SessionActivityRelayOptions = {},) {+ this.checkCompletion = options.isCompletionHandledByTeammate;this.minIntervalMs = Math.max(0, options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS);this.now = options.now ?? (() => Date.now());this.setTimer = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms));@@ -48,7 +54,13 @@ export class SessionActivityRelay {for (const activity of list) {if (!activity.sessionId) continue;activeSessionIds.add(activity.sessionId);- this.publishOne(toSessionActivityPayload(activity));+ const payload = toSessionActivityPayload(activity);+ if (this.checkCompletion && payload.phase === 'completed' && payload.attention) {+ this.publishCompletion(activity, payload);+ } else {+ this.completionChecks.delete(activity.sessionId);+ this.publishOne(payload);+ }}for (const sessionId of [...this.entries.keys()]) {@@ -61,6 +73,7 @@ export class SessionActivityRelay {for (const entry of this.entries.values()) {if (entry.timer) this.clearTimer(entry.timer);}+ this.completionChecks.clear();this.entries.clear();this.terminalReplayPayloads.clear();}@@ -70,6 +83,7 @@ export class SessionActivityRelay {* Runtime reset should not leave remote lists showing stale running rows.*/reset(): void {+ this.completionChecks.clear();for (const sessionId of [...this.entries.keys()]) {this.clear(sessionId);}@@ -112,7 +126,9 @@ export class SessionActivityRelay {for (const activity of list) {if (!activity.sessionId) continue;seenSessionIds.add(activity.sessionId);- const payload = toSessionActivityPayload(activity);+ const check = this.completionChecks.get(activity.sessionId);+ const payload = activity.phase === 'completed' && activity.attention && check?.startedAtMs === activity.startedAtMs+ ? check.payload : toSessionActivityPayload(activity);emit(isPublishableActivity(payload) ? payload : toTerminalActivityPayload(activity.sessionId));}for (const [sessionId, payload] of this.terminalReplayPayloads) {@@ -120,6 +136,24 @@ export class SessionActivityRelay {}}+ private publishCompletion(activity: AgentIslandSessionActivity, payload: SessionActivityPayload): void {+ const previous = this.completionChecks.get(activity.sessionId);+ if (previous && previous.startedAtMs === activity.startedAtMs) {+ previous.payload = { ...payload, completionNotification: previous.payload.completionNotification };+ this.publishOne(previous.payload);+ return;+ }+ const check = { startedAtMs: activity.startedAtMs, payload: { ...payload, completionNotification: 'pending' as const } as SessionActivityPayload };+ this.completionChecks.set(activity.sessionId, check);+ this.publishOne(check.payload);+ void this.checkCompletion!(activity.sessionId).catch(() => false).then((handled) => {+ // A new turn, read acknowledgement, reset or disposal invalidates the old check.+ if (this.completionChecks.get(activity.sessionId) !== check) return;+ check.payload = { ...check.payload, completionNotification: handled ? 'teammate' : undefined };+ this.publishOne(check.payload);+ });+ }+private publishOne(payload: SessionActivityPayload): void {const entry = this.entries.get(payload.sessionId);if (!isPublishableActivity(payload)) {@@ -166,6 +200,7 @@ export class SessionActivityRelay {}private clear(sessionId: string): void {+ this.completionChecks.delete(sessionId);const entry = this.entries.get(sessionId);if (!entry) return;if (entry.timer) this.clearTimer(entry.timer);@@ -248,6 +283,7 @@ function toTerminalActivityPayload(sessionId: string): SessionActivityPayload {function activitySignature(payload: SessionActivityPayload): string {return [payload.phase,+ payload.completionNotification ?? '',payload.compactDetail,payload.workingPhase,payload.interactionKind ?? '',diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.tsindex 3df1b6bf19..3fc6ff798b 100644--- a/apps/desktop/src/main/agent-island/state.ts+++ b/apps/desktop/src/main/agent-island/state.ts@@ -122,6 +122,7 @@ interface ApplyAgentIslandEventOptions {}interface AgentIslandSessionState {+ pendingDeviceCompletionNotification?: boolean;sessionId: string;title: string | null;projectName: string | null;@@ -1125,7 +1126,16 @@ export function syncAgentIslandDeviceSessions(result.changed = true;}if (applyDeviceSessionMeta(session, input)) result.changed = true;+ const waitingForCompletionNotification = session.pendingDeviceCompletionNotification === true;const transition = applyDeviceSessionPhase(state, session, input, previous, now);+ if (input.phase === 'completed') {+ const observedCompletion = transition.event === 'done' || waitingForCompletionNotification;+ session.pendingDeviceCompletionNotification = input.completionNotification === 'pending' && observedCompletion;+ if (input.completionNotification) transition.event = null;+ else if (waitingForCompletionNotification) transition.event = 'done';+ } else {+ session.pendingDeviceCompletionNotification = false;+ }if (transition.changed) result.changed = true;if (transition.event) {result.events.push({diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 09c45d65c4..f2e9c816cb 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -745,6 +745,7 @@ import {createAutomationUserTurnGitBaselineHooks,registerModelVisibilitySyncIpc,registerMakerIpc as registerMakerCoreIpc,+ tryGetBotDelegationService,restoreBotRuntimeForCurrentOwner,isSessionTurnPendingCompletion,isSessionInTurn,@@ -4311,12 +4312,18 @@ const registerIpcHandlers = () => {});// 系统级通知(CC Agent session 完成时弹出 / 可选飞书私聊)+ const isCompletionHandledByTeammate = (sessionId: string): Promise<boolean> =>+ tryGetBotDelegationService()?.isCompletionHandledByTeammate(sessionId) ?? Promise.resolve(false);initNotificationService({+ isCompletionHandledByTeammate,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)),getMainWindow: () => getWindow() ?? null,isPlannedRemoteDaemonClose: isCcMgrUpgradeInFlight,onSessionActivityChange: (activity) => {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 7f5e499c48..3bebdfb534 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -7970,6 +7970,49 @@ describe('Bot Session task end-to-end runtime', () => {}});+ it.each(['accepted', 'rejected', 'paused', 'archived'] as const)('delegated completion notification ownership follows the durable handoff (%s)', async boundary => {+ await seedPair();+ let execution = { instanceId: 'notification-child', generation: 1 };+ let release!: () => void;+ let entered!: () => void;+ const waiting = new Promise<void>(resolve => { entered = resolve; });+ const blocked = new Promise<void>(resolve => { release = resolve; });+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution,+ decorateDispatch: dispatch => async params => {+ if (params.clientId?.startsWith('bot-delegation-completion:')) {+ entered(); await blocked;+ if (boundary === 'rejected') return { ok: false, errorCode: 'NOT_FOUND', message: 'fixture requester unavailable' };+ }+ return dispatch(params);+ },+ });+ try {+ expect(await runtime.delegation.isCompletionHandledByTeammate('session-1')).toBe(false);+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Notification ownership fixture.' });+ if (!task.ok) throw new Error(task.message);+ // Ordinary Session delegated by a teammate: ownership comes from this+ // receipt, not source=bot, an avatar, title, or a Bot Session link.+ expect(h.sqlite!.prepare('SELECT source FROM sessions WHERE id=?').pluck().get(task.childSessionId)).toBe('desktop');+ expect(h.sqlite!.prepare('SELECT count(*) FROM bot_session_links WHERE session_id=?').pluck().get(task.childSessionId)).toBe(0);+ const settlement = runtime.delegation.settleSession({ childSessionId: task.childSessionId, execution, outcome: 'done', resultText: 'Final fixture result' });+ const ownership = runtime.delegation.isCompletionHandledByTeammate(task.childSessionId);+ await waiting;+ let resolved = false;+ void ownership.then(() => { resolved = true; });+ await Promise.resolve();+ expect(resolved).toBe(false);+ release();+ await settlement;+ if (boundary === 'paused' || boundary === 'archived') h.sqlite!.prepare('UPDATE bot_profiles SET status=? WHERE id=?').run(boundary, 'bot-a');+ expect(await ownership).toBe(boundary === 'accepted');+ expect(h.sqlite!.prepare("SELECT content FROM messages WHERE session_id='session-1' AND client_id LIKE 'bot-delegation-result:%'").pluck().get()).toBe('Final fixture result');+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id=?').pluck().get(task.childSessionId)).toBe('active');+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId)).toBe(boundary === 'accepted');+ execution = { ...execution, generation: 2 };+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId)).toBe(false);+ } finally { release(); runtime.dispose(); }+ });+it.each(['delegation-request', 'interjection', 'delegation-result'])('recovers the child answer without promoting a nested %s receipt', async (nestedRole) => {await seedPair();const runtime = createDelegationRuntime();diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex fd3e68a9f3..ec1a866bcd 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -427,6 +427,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const completionRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();/** Serializes a terminal receipt with a user continuing the same task card. */const completionInFlight = new Map<string, Promise<void>>();+ const terminalSettlements = new Map<string, Promise<void>>();const interactionRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();const cleanupRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();const resumeRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();@@ -3958,7 +3959,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return [];};- const settleSession = async (params: Parameters<typeof settleSessionUnserialized>[0]) => {+ const settleSessionSerialized = async (params: Parameters<typeof settleSessionUnserialized>[0]) => {// Publish an awaitable validation before the first database await. Queue drain// is already scheduled by the synchronous event adapter at this point.if (params.execution && params.pendingInputClientIds?.length) {@@ -3990,6 +3991,38 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (row) await withTaskOperation(row.id, () => settleSessionUnserialized({ ...params, expectedRunSequence: row.runSequence }));};+ // Register synchronously: completion notices can arrive while settlement is+ // still reading the DB. Await only this terminal attempt, never retry timers.+ const settleSession = (params: Parameters<typeof settleSessionUnserialized>[0]): Promise<void> => {+ const settlement = settleSessionSerialized(params);+ terminalSettlements.set(params.childSessionId, settlement);+ void settlement.finally(() => {+ if (terminalSettlements.get(params.childSessionId) === settlement) terminalSettlements.delete(params.childSessionId);+ }).catch(() => undefined);+ return settlement;+ };++ const isCompletionHandledByTeammate = async (childSessionId: string): Promise<boolean> => {+ const execution = deps.readSessionExecution?.(childSessionId);+ if (!execution) return false;+ await terminalSettlements.get(childSessionId);+ const [row] = await getDbClient().drizzle.select().from(botDelegations)+ .where(eq(botDelegations.childSessionId, childSessionId)).limit(1);+ if (!row || row.status !== 'completed' || row.completionDeliveredAt == null || row.acceptedAt == null) return false;+ const snapshot = parseRecord(row.permissionSnapshotJson);+ const accepted = snapshot.taskExecution as (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ const terminal = snapshot.taskTerminal as {+ runSequence: number; execution: DelegationExecutionReceipt; outcome: string;+ } | undefined;+ if (accepted?.runSequence !== row.runSequence || terminal?.runSequence !== row.runSequence+ || terminal.outcome !== 'done' || !isSameSessionExecution(accepted, execution)+ || !isSameSessionExecution(terminal.execution, execution) || !sameExecution(childSessionId, execution)) return false;+ // An archived/paused requester cannot produce a new public reply. Preserve+ // the task notice in that case, including delivery failures held for resume.+ const requester = await requesterLiveSessionId(row.requestingBotId, row.parentSessionId);+ return requester !== null && sameExecution(childSessionId, execution);+ };+// Only delegation-owned entries from a validated terminal/resume boundary// can adopt a new receipt. Ordinary direct Session input remains independent.const acceptQueuedSessionInput = async (childSessionId: string, clientId: string, supersedesClientId?: string, restoredFromSnapshot = false, retrySourceClientId?: string): Promise<void> => {@@ -4223,6 +4256,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {cancelDelegationsForParentSession,cancelDelegationsForBot,settleSession,+ isCompletionHandledByTeammate,acceptQueuedSessionInput,confirmQueuedSessionInputDispatched,handleInteractionStart,diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.tsindex f8509ddd33..7dd3bdb788 100644--- a/apps/desktop/src/main/notificationService.ts+++ b/apps/desktop/src/main/notificationService.ts@@ -99,7 +99,7 @@ interface ShowSessionEventPayload {// 时就回收掉,导致 click handler 丢失甚至触发异常事件。用 Set 持引用,等// close/click 后再 release。const liveNotifications = new Set<Notification>();-type NotifiedReply = { eventId: string } | { fallbackSentAt: number };+type NotifiedReply = ({ eventId: string } | { fallbackSentAt: number }) & { handledByTeammate?: true };const notifiedReplies = new Map<string, NotifiedReply>();const pendingFeishuReplies = new Set<string>();const pendingFeishuFallbacks = new Map<string, number>();@@ -119,7 +119,7 @@ function wasReplyNotified(key: string, eventId: string | undefined): boolean {// A turn started afterwards is new, even if it finishes immediately.const startedAt = /^turn:(\d+):\d+$/.exec(eventId)?.[1];if (startedAt && Number(startedAt) < notified.fallbackSentAt) {- notifiedReplies.set(key, { eventId });+ notifiedReplies.set(key, { eventId, ...(notified.handledByTeammate ? { handledByTeammate: true as const } : {}) });return true;}return false;@@ -196,6 +196,7 @@ export function showDeviceSessionDesktopEvent(}export interface NotificationServiceDeps {+ isCompletionHandledByTeammate?: (sessionId: string) => Promise<boolean>;getWindow: () => BrowserWindow | null;/*** 飞书 IM 实例,用于飞书通道发消息。来源与 scheduler-host/notifier.ts 相同@@ -318,6 +319,27 @@ export function initNotificationService(deps: NotificationServiceDeps): void {const desktopKey = replyNotificationKey(ownerKey, sessionId, 'desktop');const mobileKey = replyNotificationKey(generation, sessionId, 'mobile');const feishuKey = replyNotificationKey(ownerKey, sessionId, 'feishu');+ if (kind === 'done' && notifiedReplies.get(desktopKey)?.handledByTeammate && wasReplyNotified(desktopKey, eventId)) return;+ // Decide at the send boundary, after preview enrichment. The native+ // receipt and durable completion handoff are authoritative, never titles.+ const handledByTeammate = kind === 'done' && deps.isCompletionHandledByTeammate+ ? await deps.isCompletionHandledByTeammate(sessionId).catch((error) => {+ log.warn('delegation completion notification check failed', { error: String(error) });+ return false;+ }) : false;+ if (!isDataOwnerBroadcastScopeCurrent(ownerScope)) return;+ if (kind === 'done' && deps.isCompletionHandledByTeammate) {+ const afterHandoffSignal = getSessionNotificationTurnSignal(sessionId);+ if (afterHandoffSignal?.id !== signal?.id || (afterHandoffSignal && !afterHandoffSignal.ended)) return;+ }+ if (kind === 'done' && handledByTeammate) {+ // Consume this event in the existing per-channel ledger. Removing a+ // delegation later must not replay a completion already handed off.+ for (const key of [desktopKey, mobileKey, feishuKey]) {+ notifiedReplies.set(key, eventId ? { eventId, handledByTeammate: true } : { fallbackSentAt: Date.now(), handledByTeammate: true });+ }+ return;+ }const fallbackBody = teammate ? getTeammateNotificationFallback() : undefined;const mobileTeammateBotId = preview?.teammateBotId ?? teammateBotId;if (wantDesktop && kind === 'done' && !wasReplyNotified(desktopKey, eventId)) {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 fbe90d39b9..4d45925252 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@@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest';import type { Session } from '@/lib/ccAgent.types';import { buildAgentIslandRemoteSessionInputs } from '../agentIslandRemoteSessions';-import type { RemoteSessionActivity } from '../remoteSessionActivityStore';+import { applyRemoteSessionActivity, clearRemoteSessionActivity, getRemoteSessionActivity, type RemoteSessionActivity } from '../remoteSessionActivityStore';+import { parseAgentIslandRemoteSessions } from '../../../../shared/agentIsland';+import { createAgentIslandState, syncAgentIslandDeviceSessions } from '../../../../main/agent-island/state';+import { SessionActivityRelay } from '../../../../main/agent-island/sessionActivityRelay';import { MACHINE_ALL, MACHINE_LOCAL } from '../selectedMachineStore';function remoteSession(id: string, deviceId: string, overrides: Partial<Session> = {}): Session {@@ -53,6 +56,32 @@ describe('buildAgentIslandRemoteSessionInputs', () => {remoteSession('b-2', 'device-b', { title: ' ' }),];+ it.each([true, false])('carries host notification ownership through relay, store, IPC parsing and remote events (%s)', async handled => {+ clearRemoteSessionActivity();+ let resolve!: (handled: boolean) => void;+ const state = createAgentIslandState();+ const events: string[] = [];+ const relay = new SessionActivityRelay(payload => {+ applyRemoteSessionActivity('device-a', payload);+ const inputs = buildAgentIslandRemoteSessionInputs([remoteSession('a-1', 'device-a')], MACHINE_ALL, getRemoteSessionActivity);+ const parsed = parseAgentIslandRemoteSessions(inputs);+ expect(parsed).not.toBeNull();+ events.push(...syncAgentIslandDeviceSessions(state, parsed!, 2_000).events.map(event => event.kind));+ }, { isCompletionHandledByTeammate: () => new Promise<boolean>(r => { resolve = r; }) });+ 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' }]);+ 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();+ expect(events).toEqual(handled ? [] : ['done']);+ relay.replay([{ ...activity, phase: 'completed', attention: true }]);+ expect(events).toEqual(handled ? [] : ['done']);+ expect(state.sessions.get('a-1')).toMatchObject({ phase: 'completed', unread: true });+ relay.dispose(); clearRemoteSessionActivity();+ });+it('includes every remote task with live activity under the "all" scope', () => {expect(buildAgentIslandRemoteSessionInputs(sessions, MACHINE_ALL, readActivity)).toEqual([{diff --git a/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.tsindex 93ffdca488..8e91005db3 100644--- a/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts@@ -39,6 +39,7 @@ export function buildAgentIslandRemoteSessionInputs(agentKind: session.agentKind,phase: activity.phase,detail: activity.compactDetail,+ ...(activity.completionNotification ? { completionNotification: activity.completionNotification } : {}),...(activity.workingPhase ? { workingPhase: activity.workingPhase } : {}),...(activity.interactionKind? {diff --git a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.tsindex e2c8a11f75..09e07fff15 100644--- a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts+++ b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts@@ -31,6 +31,7 @@ export interface RemoteSessionActivity {workingPhase?: string;interactionKind?: string;attention: boolean;+ completionNotification?: 'pending' | 'teammate';}/** Active remote turns must win over the persisted "started without ended" heuristic. */@@ -66,6 +67,7 @@ function sameActivity(a: RemoteSessionActivity, b: RemoteSessionActivity): boolea.compactDetail === b.compactDetail &&a.workingPhase === b.workingPhase &&a.interactionKind === b.interactionKind &&+ a.completionNotification === b.completionNotification &&a.attention === b.attention);}@@ -157,6 +159,7 @@ export function applyRemoteSessionActivity(deviceId: string, payload: unknown):workingPhase: typeof p.workingPhase === 'string' ? p.workingPhase : undefined,interactionKind: typeof p.interactionKind === 'string' ? p.interactionKind : undefined,attention,+ completionNotification: p.completionNotification === 'pending' || p.completionNotification === 'teammate' ? p.completionNotification : undefined,};let activityMap = activityByDevice.get(deviceId);if (!activityMap) {diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.tsindex 544fcb39e7..ba291c46ed 100644--- a/apps/desktop/src/shared/agentIsland.ts+++ b/apps/desktop/src/shared/agentIsland.ts@@ -753,6 +753,7 @@ export const AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL = 'agent-island:set-remote* 只含 running / needs-interaction / 未读终态;范围由 renderer 按侧栏「任务范围」裁剪。*/export interface AgentIslandRemoteSessionInput {+ completionNotification?: 'pending' | 'teammate';sessionId: string;deviceId: string;deviceName: string | null;@@ -810,6 +811,8 @@ export function parseAgentIslandRemoteSessions(raw: unknown): AgentIslandRemoteSworkspaceKind: readBoundedString(record.workspaceKind, 64),agentKind: readBoundedString(record.agentKind, 64),phase: phase as AgentIslandSessionPhase,+ ...(record.completionNotification === 'pending' || record.completionNotification === 'teammate'+ ? { completionNotification: record.completionNotification } : {}),detail: readBoundedString(record.detail, AGENT_ISLAND_REMOTE_TEXT_MAX_LENGTH) ?? '',...(workingPhase ? { workingPhase } : {}),...(interactionKind ? { interactionKind } : {}),diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 144a0abd62..1e7e880532 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1017,3 +1017,15 @@ Mobile 据此区分已关闭与已删除的旧选择:保留任务或草稿原这是执行主机的投影修复,旧 Mobile 和远控 Desktop 无需新增能力协商即可接收。不增加分页、客户端重组或重试,不提高传输大小上限;本机 Desktop 设置仍读取完整目录。“关闭后必须重选”的提示与发送前检查随 Mobile 更新;旧版控制端仍沿用各自既有选择处理。++## 委派任务的完成通知归属++既有 `SessionActivityPayload` 可选字段 `completionNotification` 只影响远端桌面完成通知:+`pending` 表示该轮终态回传正在判定,`teammate` 表示同一委派执行结果已成功交回伙伴;+缺省或未知值按普通任务完成通知处理。完成 phase、摘要和 attention 在 pending 阶段照常发送,+回传决定通过同一活动通道更新;控制端仅对已观察运行的任务补发必要 fallback 一次,重连的+基线终态不补发历史提醒。错误与待交互不受此字段影响。++新控制端连接旧执行端沿用原通知;旧控制端忽略该字段,仍可能发独立完成桌面通知,完整远端+去重需要两端更新。手机外部推送在执行端通知出口完成去重,手机无需新增协议处理;+移动列表继续原 phase/attention 语义。无需服务端、数据库 migration 或 Mobile fingerprint 改动。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex d8fc8979d3..795d5f9fc6 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -429,6 +429,11 @@ Session 任务遵守同一套机制与呈现契约:- 伙伴主任务、它启动的 Session 任务和普通 Cindy 任务共用一条完成 / 失败 / 待回复通知链,不另存一套 Bot 专用通知开关。+- 已有委派执行回执的后台 Session 任务,只有同一原生执行轮次的结果已持久化并成功交回+ 活跃发起伙伴时,才停止该执行任务独立的完成外部通知;随后由伙伴正常最终回复复用现有通知。+ 回传失败、发起伙伴暂停/归档、审批、待答和错误保留原任务提醒。完成通知等待该轮已启动的+ 终态回传尝试,不等待重试定时器;重复事件沿原通知去重账本消费,后续直接执行轮次恢复原语义。+ 普通任务不因目录上的伙伴头像静音;任务正文、结果回执、状态、未读与 Dock 不变。- 用户正在看对应任务时不发外部通知;后台时仍按全局桌面、飞书、移动端与灵动岛去重规则投递。- 伙伴私聊的结构化入口不触发通知;接收伙伴随后产出的正常回复才有提醒价值。- 点击伙伴任务的通知必须回到伙伴自己的主任务或历史任务路由,不能把隐藏的 `source=bot`diff --git a/packages/device-link/src/topics.ts b/packages/device-link/src/topics.tsindex 23d24fbfd2..41b1e870a8 100644--- a/packages/device-link/src/topics.ts+++ b/packages/device-link/src/topics.ts@@ -54,6 +54,9 @@ export function parseFsWatchTopic(topic: string): string | null {export type SessionActivityPhase = 'running' | 'needs-interaction' | 'completed' | 'error';export interface SessionActivityPayload {+ /** Completion push ownership only; activity/attention remains unchanged.+ * Absent on older hosts. Unknown values use ordinary completion semantics. */+ completionNotification?: 'pending' | 'teammate';/** Optional public generation category; unknown values must use a generic caption. */workingPhase?: string;sessionId: string;