Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): route handoff notices by request identity
guyong09650d9f13b0
diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.tsindex 9259a80afb..a8c51a1dea 100644--- a/apps/desktop/src/main/__tests__/notificationService.test.ts+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts@@ -24,6 +24,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { Session } from '@cindy/maker-core';+import type { BrowserWindow } from 'electron';type IpcHandler = (event: unknown, payload: unknown) => Promise<void> | void;@@ -103,11 +104,6 @@ vi.mock('../device-link', () => ({getMobileNotifyGeneration,}));-const pendingHandoffSessions = new Set<string>();-vi.mock('../input-handoff/service', () => ({- getInputHandoffService: () => ({ hasPending: (id: string) => pendingHandoffSessions.has(id) }),-}));-// mobile 正文素材:最近一条 assistant 内容(真实实现走 localDb)。默认空 = 无摘要,// 既有用例的调用断言不带 detail;内容用例单独 mockResolvedValueOnce。const latestMessageText = vi.fn<@@ -204,12 +200,70 @@ describe('notificationService — channels 分发', () => {vi.useRealTimers();});+ // #6754 review 4373832302 / unit: a finished handoff's delayed event keeps+ // its host-recorded routing decision; current pending state can already differ.+ it('uses request ownership after a handoff ends and rejects unknown or cross-session request IDs', async () => {+ const { initNotificationService } = await freshService();+ const { notifyInputHandoffOnce, forgetInputHandoffNotice, clearInputHandoffChannelNotices } =+ await import('../im/shared/inputHandoffChannelNotice');+ const feishuIm = makeFeishuIm('owner');+ initNotificationService(baseDeps(feishuIm));+ const notify = (sessionId: string, inputHandoffRequestId: string) => invokeHandler({+ sessionId, inputHandoffRequestId, title: 'Bot', kind: 'needs-reply',+ channels: { desktop: false, feishu: true, mobile: false },+ });+ try {+ await notifyInputHandoffOnce('im-bot', 'settled-request', async () => true);+ await notify('im-bot', 'settled-request');+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ await notify('other-bot', 'settled-request');+ forgetInputHandoffNotice('im-bot', 'settled-request');+ await notify('im-bot', 'settled-request');+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ await notifyInputHandoffOnce('desktop-bot', 'ordinary-request', async () => false);+ await notify('desktop-bot', 'ordinary-request');+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledOnce();+ } finally {+ clearInputHandoffChannelNotices();+ }+ });++ it.each(['owned', 'owner-changed', 'focused'] as const)(+ 'keeps desktop immediate and rechecks delayed handoff ownership (%s)', async outcome => {+ const { initNotificationService } = await freshService();+ const { notifyInputHandoffOnce, forgetInputHandoffNotice, clearInputHandoffChannelNotices } =+ await import('../im/shared/inputHandoffChannelNotice');+ const feishuIm = makeFeishuIm('owner');+ let focused = false;+ initNotificationService({ ...baseDeps(feishuIm), getWindow: () => ({ isFocused: () => focused }) as unknown as BrowserWindow });+ let release!: (handled: boolean) => void;+ const decision = new Promise<boolean>(resolve => { release = resolve; });+ void notifyInputHandoffOnce('bot', 'request', () => decision);+ try {+ const pending = registeredHandlers.get('notification:show-session-event')!({}, {+ sessionId: 'bot', title: 'Bot', kind: 'needs-reply', inputHandoffRequestId: 'request',+ channels: { desktop: true, feishu: true, mobile: false },+ });+ expect(notificationCtor).toHaveBeenCalledOnce();+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ forgetInputHandoffNotice('bot', 'request'); // completion cleanup while resolution is in flight+ if (outcome === 'owner-changed') ownerScopeCurrent = false;+ if (outcome === 'focused') focused = true;+ release(outcome === 'owned');+ await pending;+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ } finally {+ clearInputHandoffChannelNotices();+ }+ },+ );+// #6754 / input-handoff §2.4 / unit: the real notification IPC must not// duplicate Main's channel pointer on successive steps. Both bot tasks have- // the same source; only the live route plus pending request distinguishes them.+ // the same source; only Main's decision for this request distinguishes them.it('deduplicates channel-owned handoff steps while preserving desktop bot fallback and other notices', async () => {const { initNotificationService } = await freshService();- const { bindInputHandoffChannelNotice, clearInputHandoffChannelNotices } =+ const { bindInputHandoffChannelNotice, sendInputHandoffChannelNotice, notifyInputHandoffOnce, clearInputHandoffChannelNotices } =await import('../im/shared/inputHandoffChannelNotice');const feishuIm = makeFeishuIm('owner');initNotificationService(baseDeps(feishuIm));@@ -221,37 +275,39 @@ describe('notificationService — channels 分发', () => {return () => statusListeners.delete(listener);},} as unknown as Session, async () => true);- const notify = (sessionId: string, kind = 'needs-reply') => invokeHandler({- sessionId, title: 'Bot', kind, channels: { desktop: true, feishu: true, mobile: false },+ const notify = (sessionId: string, kind = 'needs-reply', requestId?: string) => invokeHandler({+ sessionId, title: 'Bot', kind, ...(requestId ? { inputHandoffRequestId: requestId } : {}),+ channels: { desktop: true, feishu: true, mobile: false },});+ const claim = (sessionId: string, requestId: string) => notifyInputHandoffOnce(sessionId, requestId,+ async () => sendInputHandoffChannelNotice(sessionId, 'pointer', { warn }));try {- pendingHandoffSessions.add('im-bot');- await notify('im-bot'); // first actionable step- await notify('im-bot'); // next step of the same request+ await claim('im-bot', 'request-1');+ await notify('im-bot', 'needs-reply', 'request-1'); // first actionable step+ await notify('im-bot', 'needs-reply', 'request-1'); // next step of the same requestexpect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();expect(notificationCtor).toHaveBeenCalledTimes(2);expect(markSessionNeedsAttention).toHaveBeenCalledWith('im-bot');expect(sendMobileSessionNotify).not.toHaveBeenCalled();- pendingHandoffSessions.add('desktop-bot');- await notify('desktop-bot'); // ordinary bot: no channel route+ await claim('desktop-bot', 'request-desktop');+ await notify('desktop-bot', 'needs-reply', 'request-desktop'); // ordinary bot: no channel routeexpect(feishuIm.sendMarkdownText).toHaveBeenCalledOnce();- pendingHandoffSessions.delete('im-bot');await notify('im-bot'); // channel route alone must not hide a questionexpect(feishuIm.sendMarkdownText).toHaveBeenCalledTimes(2);- pendingHandoffSessions.add('im-bot'); // a new handoff request is also owned by Main- await notify('im-bot');+ await claim('im-bot', 'request-2'); // a new handoff request is also owned by Main+ await notify('im-bot', 'needs-reply', 'request-2');expect(feishuIm.sendMarkdownText).toHaveBeenCalledTimes(2);await notify('im-bot', 'error');await notify('im-bot', 'done');expect(feishuIm.sendMarkdownText).toHaveBeenCalledTimes(4);statusListeners.forEach(listener => listener('closed'));- await notify('im-bot'); // a removed route cannot suppress a fallback+ await claim('im-bot', 'request-3');+ await notify('im-bot', 'needs-reply', 'request-3'); // a removed route cannot suppress a new fallbackexpect(feishuIm.sendMarkdownText).toHaveBeenCalledTimes(5);} finally {- pendingHandoffSessions.clear();clearInputHandoffChannelNotices();}});@@ -378,6 +434,8 @@ describe('notificationService — channels 分发', () => {{ sessionId: 's1', title: 'x'.repeat(1025), kind: 'done' },{ sessionId: 's1', title: 'x', kind: 'done', channels: 'all' },null,+ ...['', 1, 'x'.repeat(257)].map(inputHandoffRequestId => ({ sessionId: 's1', title: 'x', kind: 'needs-reply', inputHandoffRequestId })),+ { sessionId: 's1', title: 'x', kind: 'done', inputHandoffRequestId: 'request' },];for (const payload of invalids) {await expect(invokeHandler(payload)).rejects.toThrow('invalid session event payload');diff --git a/apps/desktop/src/main/im/__tests__/desktopConfirmNotice.test.ts b/apps/desktop/src/main/im/__tests__/desktopConfirmNotice.test.tsindex 66d0e8ff17..0300943dde 100644--- a/apps/desktop/src/main/im/__tests__/desktopConfirmNotice.test.ts+++ b/apps/desktop/src/main/im/__tests__/desktopConfirmNotice.test.ts@@ -22,7 +22,7 @@ describe('createDesktopConfirmNotifier', () => {getFeishuOpenId: async () => 'ou_123',sendFeishuText: send,});- notify('feishu_bot_ou_123', '「提交 GitHub issue」的确认卡');+ expect(await notify('feishu_bot_ou_123', '「提交 GitHub issue」的确认卡')).toBe(true);await flush();expect(send).toHaveBeenCalledWith('ou_123',@@ -38,7 +38,7 @@ describe('createDesktopConfirmNotifier', () => {getFeishuOpenId: async () => null,sendFeishuText: send,});- notify('desktop-session', 'x');+ expect(await notify('desktop-session', 'x')).toBe(false);await flush();expect(send).not.toHaveBeenCalled();});@@ -63,7 +63,7 @@ describe('createDesktopConfirmNotifier', () => {},logWarn: sendFail,});- notify2('s1', 'x');+ expect(await notify2('s1', 'x')).toBe(true);await flush();expect(sendFail).toHaveBeenCalled();});diff --git a/apps/desktop/src/main/im/desktopConfirmNotice.ts b/apps/desktop/src/main/im/desktopConfirmNotice.tsindex 4aedfd6fba..67728dcbad 100644--- a/apps/desktop/src/main/im/desktopConfirmNotice.ts+++ b/apps/desktop/src/main/im/desktopConfirmNotice.ts@@ -58,23 +58,26 @@ export function buildInputHandoffNoticeText(taskTitle: string): string {/*** 组装 fire-and-forget 通知函数(DI 便于单测;生产接线见- * desktopConfirmNoticeWiring.ts)。+ * desktopConfirmNoticeWiring.ts)。返回是否解析到目标,而非是否发送成功;+ * 忽略返回值的既有调用方仍为 best-effort,不抛出。*/export function createDesktopConfirmNotifier(deps: DesktopConfirmNoticeDeps,buildText: (what: string) => string = buildDesktopConfirmNoticeText,-): (sessionId: string, what: string) => void {- return (sessionId, what) => {- void (async () => {- try {- const openId = await deps.getFeishuOpenId(sessionId);- if (!openId) return;- await deps.sendFeishuText(openId, buildText(what));- } catch (err) {- deps.logWarn?.(- `desktop-confirm IM notice failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`,- );- }- })();+): (sessionId: string, what: string) => Promise<boolean> {+ return async (sessionId, what) => {+ let handled = false;+ try {+ const openId = await deps.getFeishuOpenId(sessionId);+ if (!openId) return false;+ // Finding a target claims this notice, even when best-effort delivery fails.+ handled = true;+ await deps.sendFeishuText(openId, buildText(what));+ } catch (err) {+ deps.logWarn?.(+ `desktop-confirm IM notice failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ return handled;};}diff --git a/apps/desktop/src/main/im/desktopConfirmNoticeWiring.ts b/apps/desktop/src/main/im/desktopConfirmNoticeWiring.tsindex eaef002fa9..053f5205c4 100644--- a/apps/desktop/src/main/im/desktopConfirmNoticeWiring.ts+++ b/apps/desktop/src/main/im/desktopConfirmNoticeWiring.ts@@ -26,7 +26,7 @@ const log = createLogger('im-desktop-confirm-notice');/** 生产接线:接管绑定 / sessions 行反查 feishuOpenId + 复用 im/host 的 feishuIm 实例。 */export function createFeishuDesktopConfirmNotifier(buildText?: (what: string) => string,-): (sessionId: string, what: string) => void {+): (sessionId: string, what: string) => Promise<boolean> {return createDesktopConfirmNotifier({async getFeishuOpenId(sessionId) {return resolveFeishuNoticeTarget(diff --git a/apps/desktop/src/main/im/shared/__tests__/inputHandoffChannelNotice.test.ts b/apps/desktop/src/main/im/shared/__tests__/inputHandoffChannelNotice.test.tsindex 3dbd1b7e35..31c50bde1e 100644--- a/apps/desktop/src/main/im/shared/__tests__/inputHandoffChannelNotice.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/inputHandoffChannelNotice.test.ts@@ -4,6 +4,9 @@ import {bindInputHandoffChannelNotice,clearInputHandoffChannelNotices,sendInputHandoffChannelNotice,+ notifyInputHandoffOnce,+ getInputHandoffNoticeOwnership,+ forgetInputHandoffNotice,} from '../inputHandoffChannelNotice';function fakeSession(id: string) {@@ -25,6 +28,32 @@ afterEach(() => {});describe('代输入 channel pointer', () => {+ // #6754 / input-handoff §2.4 / unit: every step shares the first actual route+ // decision, including after completion; persisted source is never consulted.+ it('records the actual notice once per request and retains it across route changes until request cleanup', async () => {+ const { session, setStatus } = fakeSession('bot');+ const deliver = vi.fn(async () => true);+ bindInputHandoffChannelNotice(session, deliver);+ const resolve = vi.fn(async () => sendInputHandoffChannelNotice('bot', 'pointer', log));+ const first = notifyInputHandoffOnce('bot', 'request-1', resolve);+ expect(notifyInputHandoffOnce('bot', 'request-1', resolve)).toBe(first);+ await expect(first).resolves.toBe(true);+ setStatus('closed');+ await expect(getInputHandoffNoticeOwnership('bot', 'request-1')).resolves.toBe(true);+ expect(getInputHandoffNoticeOwnership('other', 'request-1')).toBeUndefined();+ expect(deliver).toHaveBeenCalledExactlyOnceWith('pointer');+ expect(resolve).toHaveBeenCalledOnce();++ await expect(notifyInputHandoffOnce('bot', 'request-2', resolve)).resolves.toBe(false);+ forgetInputHandoffNotice('bot', 'request-1');+ expect(getInputHandoffNoticeOwnership('bot', 'request-1')).toBeUndefined();+ expect(getInputHandoffNoticeOwnership('bot', 'request-2')).toBeDefined();+ let current = true;+ await notifyInputHandoffOnce('bot', 'owner-request', async () => false, () => current);+ current = false;+ expect(getInputHandoffNoticeOwnership('bot', 'owner-request')).toBeUndefined();+ });+it('goes to the chat that drives the task, and only while that task is open', async () => {const { session, setStatus } = fakeSession('s1');const deliver = vi.fn(async () => true);diff --git a/apps/desktop/src/main/im/shared/inputHandoffChannelNotice.ts b/apps/desktop/src/main/im/shared/inputHandoffChannelNotice.tsindex 75a93f708a..eac4a2d637 100644--- a/apps/desktop/src/main/im/shared/inputHandoffChannelNotice.ts+++ b/apps/desktop/src/main/im/shared/inputHandoffChannelNotice.ts@@ -16,9 +16,31 @@ interface Route {const routes = new Map<string, Route>();-/** Main-only routing truth; a bot's persisted source does not identify its active channel. */-export function hasInputHandoffChannelNotice(sessionId: string): boolean {- return routes.has(sessionId);+// Keep the request's decision through the handoff service's terminal retention.+// A late Renderer event must not infer ownership from the next turn's live route.+const notices = new Map<string, { sessionId: string; handled: Promise<boolean>; isCurrent: () => boolean }>();++export function notifyInputHandoffOnce(+ sessionId: string,+ requestId: string,+ notify: () => Promise<boolean>,+ isCurrent: () => boolean = () => true,+): Promise<boolean> {+ const previous = notices.get(requestId);+ if (previous) return previous.sessionId === sessionId ? previous.handled : Promise.resolve(true);+ const handled = Promise.resolve().then(notify);+ notices.set(requestId, { sessionId, handled, isCurrent });+ return handled;+}++/** Undefined means this host no longer knows the event, not permission to send a fallback. */+export function getInputHandoffNoticeOwnership(sessionId: string, requestId: string): Promise<boolean> | undefined {+ const notice = notices.get(requestId);+ return notice?.sessionId === sessionId && notice.isCurrent() ? notice.handled : undefined;+}++export function forgetInputHandoffNotice(sessionId: string, requestId: string): void {+ if (notices.get(requestId)?.sessionId === sessionId) notices.delete(requestId);}export function bindInputHandoffChannelNotice(@@ -62,4 +84,5 @@ export function sendInputHandoffChannelNotice(/** Tests only. */export function clearInputHandoffChannelNotices(): void {for (const route of [...routes.values()]) route.cleanup();+ notices.clear();}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 9b29645615..a316d6dca5 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -250,7 +250,7 @@ import {} from '../cindy-brain/ghostGrantConfirmBridge.js';import { createFeishuDesktopConfirmNotifier } from '../im/desktopConfirmNoticeWiring.js';import { buildInputHandoffNoticeText } from '../im/desktopConfirmNotice.js';-import { sendInputHandoffChannelNotice } from '../im/shared/inputHandoffChannelNotice.js';+import { sendInputHandoffChannelNotice, notifyInputHandoffOnce, forgetInputHandoffNotice } from '../im/shared/inputHandoffChannelNotice.js';import { bindingStore } from '../im/binding.js';import { isHeadlessGhostSetupTurn } from '../mcp-integrations/ghostSetupInteractionSurface.js';import {@@ -3318,7 +3318,6 @@ const ghostSetupInteractionBridge = initGhostSetupInteractionBridge({* Broadcasts carry step structure only; owner values never leave the* trusted local channel or the signed v3 exchange.*/-const inputHandoffImNotified = new Set<string>();/** Who is answering: this Desktop, or the server-verified controller device. */function inputHandoffActor(): InputHandoffHolder {const context = getDeviceLinkInvokeContext();@@ -3342,19 +3341,22 @@ const inputHandoffImNotifier = createFeishuDesktopConfirmNotifier(buildInputHand*/function notifyInputHandoffOwner(sessionId: string, snapshot: InputHandoffSnapshot): void {const generation = getMobileNotifyGeneration();+ const ownerScope = captureDataOwnerBroadcastScope();+ const titleRead = readSessionTitle(sessionId);+ // Register before any await: Renderer can race both lookup and handoff completion.+ void notifyInputHandoffOnce(sessionId, snapshot.requestId, async () => {+ const title = await titleRead;+ if (!isDataOwnerBroadcastScopeCurrent(ownerScope)) return true;+ if (sendInputHandoffChannelNotice(sessionId, buildInputHandoffNoticeText(title), log)) return true;+ return inputHandoffImNotifier(sessionId, title);+ }, () => isDataOwnerBroadcastScopeCurrent(ownerScope))+ .catch(err => log.warn('[input-handoff] owner IM notice failed (non-fatal)', err));void (async () => {try {const [title, preview] = await Promise.all([- readSessionTitle(sessionId),+ titleRead,readSessionNotificationPreview(sessionId, false).catch(() => undefined),]);- // An IM-driven task gets one text pointer per request, not one per screen.- if (!inputHandoffImNotified.has(snapshot.requestId)) {- inputHandoffImNotified.add(snapshot.requestId);- // Channel-driven tasks get it in their chat; a desktop task taken over from Feishu (/ctr) by its binding.- if (!sendInputHandoffChannelNotice(sessionId, buildInputHandoffNoticeText(title), log))- inputHandoffImNotifier(sessionId, title);- }sendMobileSessionNotify({sessionId,title: preview?.teammateName ?? title,@@ -3407,8 +3409,8 @@ initInputHandoffService({},notifyOwner: (sessionId, snapshot) => notifyInputHandoffOwner(sessionId, snapshot),describeDevice: describeInputHandoffDevice,- onClosed: (_sessionId, requestId) => {- inputHandoffImNotified.delete(requestId);+ onClosed: (sessionId, requestId) => {+ forgetInputHandoffNotice(sessionId, requestId);},continueAgent: async (sessionId, requestId, message) => {if (!inputHandoffContinuation) throw new Error('INPUT_HANDOFF_CONTINUATION_UNAVAILABLE');diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.tsindex e5747c11f6..398417e616 100644--- a/apps/desktop/src/main/notificationService.ts+++ b/apps/desktop/src/main/notificationService.ts@@ -34,8 +34,7 @@ import { drainSessionActiveTurnWrites, getSessionNotificationTurnSignal } from 'import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './device-link/broadcast-tap';import { latestMessageText } from './localDb/latestMessageText';import { drainPersistQueue } from './messagePersistBroadcaster';-import { getInputHandoffService } from './input-handoff/service';-import { hasInputHandoffChannelNotice } from './im/shared/inputHandoffChannelNotice';+import { getInputHandoffNoticeOwnership } from './im/shared/inputHandoffChannelNotice';import { createLogger } from './logger';import {getSessionExternalNotificationText,@@ -80,6 +79,8 @@ interface ShowSessionEventPayload {sessionId: string;title: string;kind: SessionEventKind;+ /** Local handoff event identity, verified against Main's request-scoped notice record. */+ inputHandoffRequestId?: string;/*** 渠道偏好。renderer 侧 gate 后填入,缺省时按"仅桌面"兼容,防御漏传——* 当前唯一 invoke 调用方 CCAgentSidebarUpper.tsx 总是显式传 channels,@@ -391,13 +392,17 @@ export function initNotificationService(deps: NotificationServiceDeps): void {}})().catch((err) => log.warn('[notification] reply notification failed (non-fatal)', err));- // Channel-driven handoffs already receive Main's fixed pointer once per- // request. Bot tasks share source='bot' with ordinary Desktop bot tasks,- // so decide from the live request and route instead of Renderer metadata.- const channelOwnsHandoff = kind === 'needs-reply'- && getInputHandoffService()?.hasPending(sessionId)- && hasInputHandoffChannelNotice(sessionId);- if (wantFeishu && kind !== 'done' && !channelOwnsHandoff) {+ if (wantFeishu && kind !== 'done') {+ if (payload.inputHandoffRequestId) {+ const ownership = getInputHandoffNoticeOwnership(sessionId, payload.inputHandoffRequestId);+ // Unknown/expired events cannot invent a new fallback. A known event+ // keeps its actual routing decision even after the handoff ends.+ if (!ownership || await ownership.catch(err => {+ log.warn('[notification] handoff routing unavailable', err);+ return true;+ })) return;+ if (!isDataOwnerBroadcastScopeCurrent(ownerScope) || getWindow()?.isFocused()) return;+ }await sendFeishuMessage(feishuIm, safeTitle, kind);}},@@ -424,7 +429,11 @@ function assertValidSessionEventPayload(typeof p.kind !== 'string' ||!SESSION_EVENT_KINDS.has(p.kind) ||(p.channels !== undefined && (typeof p.channels !== 'object' || p.channels === null)) ||- (p.markAttention !== undefined && typeof p.markAttention !== 'boolean')+ (p.markAttention !== undefined && typeof p.markAttention !== 'boolean') ||+ (p.inputHandoffRequestId !== undefined && (+ p.kind !== 'needs-reply' || typeof p.inputHandoffRequestId !== 'string'+ || p.inputHandoffRequestId.length === 0 || p.inputHandoffRequestId.length > 256+ ))) {throw new TypeError('invalid session event payload');}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 9bb6cc9b3b..424ee0a993 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -3846,6 +3846,7 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string;title: string;kind: 'done' | 'error' | 'needs-reply';+ inputHandoffRequestId?: string;channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };markAttention?: boolean;}): Promise<void> => ipcRenderer.invoke('notification:show-session-event', payload),diff --git a/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts b/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.tsindex 8d1fa147cd..ec5355b7f3 100644--- a/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts@@ -116,20 +116,22 @@ describe('shared session event notifications', () => {});});- // #6754: only channel-driven / attached handoffs already have Main's pointer.- // Exercise the shared delivery entry, including the channels sent to Main.+ // #6754 review 4373832299 / unit: persisted sources and bindings do not prove+ // that this request has an IM pointer. Main resolves the actual request target.it.each([{ source: 'desktop', openId: null, attached: false, fallback: true },- { source: 'feishu', openId: 'ou_native', attached: false, fallback: false },- { source: 'desktop', openId: 'ou_legacy', attached: false, fallback: false },- { source: 'desktop', openId: null, attached: true, fallback: false },- { source: 'telegram', openId: null, attached: false, fallback: false },- ])('preserves handoff Feishu delivery only without Main channel ownership: %j', async entry => {+ { source: 'feishu', openId: 'ou_native', attached: false, fallback: true },+ { source: 'desktop', openId: 'ou_legacy', attached: false, fallback: true },+ { source: 'desktop', openId: null, attached: true, fallback: true },+ { source: 'telegram', openId: null, attached: false, fallback: true },+ { source: 'slack', openId: null, attached: false, fallback: true },+ { source: 'discord', openId: null, attached: false, fallback: true },+ ])('passes handoff identity to Main regardless of persisted source: %j', async entry => {gates.feishu = true;getSession.mockResolvedValue({ source: entry.source, feishuOpenId: entry.openId });resolveBinding.mockResolvedValue({ attached: entry.attached });- sendSessionEventNotification('handoff', 'Task', 'needs-reply', { inputHandoff: true });+ sendSessionEventNotification('handoff', 'Task', 'needs-reply', { inputHandoff: true, inputHandoffRequestId: 'request-1' });// Desktop must not wait for the asynchronous route lookup.expect(showSessionEvent).toHaveBeenCalledWith({sessionId: 'handoff', title: 'Task', kind: 'needs-reply',@@ -145,6 +147,7 @@ describe('shared session event notifications', () => {expect(markAttention).toHaveBeenCalledTimes(1);if (entry.fallback) expect(showSessionEvent).toHaveBeenLastCalledWith({sessionId: 'handoff', title: 'Task', kind: 'needs-reply', markAttention: false,+ inputHandoffRequestId: 'request-1',channels: { desktop: false, feishu: true, mobile: false },});});@@ -154,7 +157,7 @@ describe('shared session event notifications', () => {gates.feishu = true;let release!: (row: unknown) => void;getSession.mockReturnValueOnce(new Promise(resolve => { release = resolve; }));- sendSessionEventNotification('handoff', 'Task', 'needs-reply', { inputHandoff: true });+ sendSessionEventNotification('handoff', 'Task', 'needs-reply', { inputHandoff: true, inputHandoffRequestId: 'request-1' });if (change === 'owner-change') setDataOwnerGeneration('another-owner');if (change === 'setting-off') gates.feishu = false;if (change === 'focused') vi.mocked(document.hasFocus).mockReturnValue(true);diff --git a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.tsindex 97cf395c24..890f8e232b 100644--- a/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts+++ b/apps/desktop/src/renderer/__tests__/useSessionRunningStatusSilence.test.ts@@ -673,7 +673,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {});await emitSnapshot(new Map([['s-handoff', handoffStatus(1)]]));- expect(onSessionNeedsReply).toHaveBeenCalledExactlyOnceWith('s-handoff', { inputHandoff: true });+ expect(onSessionNeedsReply).toHaveBeenCalledExactlyOnceWith('s-handoff', { inputHandoff: true, inputHandoffRequestId: 'same-request' });first.result.current.clearNotification('s-handoff');first.unmount();vi.mocked(addSessionAttention).mockClear();@@ -693,7 +693,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {await emitSnapshot(new Map([['s-handoff', handoffStatus(2)]]));expect(onSessionNeedsReply).toHaveBeenCalledTimes(2);- expect(onSessionNeedsReply).toHaveBeenLastCalledWith('s-handoff', { inputHandoff: true });+ expect(onSessionNeedsReply).toHaveBeenLastCalledWith('s-handoff', { inputHandoff: true, inputHandoffRequestId: 'same-request' });expect(addSessionAttention).toHaveBeenCalledWith('s-handoff', 'awaiting');await emitSnapshot(new Map([['s-handoff', handoffStatus(2)]]));expect(onSessionNeedsReply).toHaveBeenCalledTimes(2);@@ -708,7 +708,7 @@ describe('useSessionRunningStatus silenced completion handling', () => {...status(false), hasPendingInputHandoff: true, hasActionableInputHandoff: true,pendingRequestKeys: ['handoff:same-request:1'],}]]));- expect(onSessionNeedsReply).toHaveBeenLastCalledWith('s-mixed', { inputHandoff: true });+ expect(onSessionNeedsReply).toHaveBeenLastCalledWith('s-mixed', { inputHandoff: true, inputHandoffRequestId: 'same-request' });await emitSnapshot(new Map([['s-mixed', {...status(false), hasPendingInputHandoff: true, hasActionableInputHandoff: true,diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 4ecea96198..f3225873ba 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -1203,7 +1203,7 @@ function ExpandedView({const unnamedLabelRef = useRef('');unnamedLabelRef.current = t('ccAgent.common.unnamedSession');const fireSessionNotification = useCallback(- (sessionId: string, kind: 'done' | 'error' | 'needs-reply', options?: { inputHandoff: true }) => {+ (sessionId: string, kind: 'done' | 'error' | 'needs-reply', options?: { inputHandoff: true; inputHandoffRequestId?: string }) => {const session = findSessionNotificationSession(sessionId, [sessionsRef.current,allSessionsForNotificationRef.current,@@ -1263,7 +1263,7 @@ function ExpandedView({[fireSessionNotification],);const handleSessionNeedsReply = useCallback(- (sessionId: string, options?: { inputHandoff: true }) => fireSessionNotification(sessionId, 'needs-reply', options),+ (sessionId: string, options?: { inputHandoff: true; inputHandoffRequestId?: string }) => fireSessionNotification(sessionId, 'needs-reply', options),[fireSessionNotification],);diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.tsindex 36e03eed12..763696a487 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts@@ -141,10 +141,25 @@ function dispatcher(local: NotificationSession[], remote: NotificationSession[]};return new Function(...Object.keys(bindings), emitted)(...Object.values(bindings)) as (sessionId: string, kind: 'done' | 'error' | 'needs-reply',+ options?: { inputHandoff: true; inputHandoffRequestId: string },) => void;}describe('disabled Make notification dispatch', () => {+ // #6754 / unit: run the production sidebar callback to protect the event ID+ // through each local dispatch branch, including the async hidden-bot fallback.+ it.each(['ordinary', 'worker', 'unknown'] as const)('forwards handoff request identity for %s tasks', async route => {+ const options = { inputHandoff: true as const, inputHandoffRequestId: 'request-1' };+ const fire = dispatcher(route === 'unknown' ? [] : [{+ id: route, title: 'Task', source: 'desktop',+ ...(route === 'worker' ? { orcaRole: 'worker' as const } : {}),+ }]);+ fire(route, 'needs-reply', options);+ await Promise.resolve();+ await Promise.resolve();+ expect(send).toHaveBeenCalledExactlyOnceWith(route, expect.any(String), 'needs-reply', expect.objectContaining(options));+ });+it.each(['cindy-make', 'cindy-make-merge'].flatMap(source =>(['local', 'archived', 'remote'] as const).flatMap(location =>(['done', 'error', 'needs-reply'] as const).map(kind => ({ source, location, kind })),diff --git a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.tsindex 0180e70779..e96dd4193f 100644--- a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts+++ b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts@@ -103,7 +103,7 @@ interface UseSessionRunningStatusOptions {* edge fires for a new request (or new input-handoff step) in the session.* Like onSessionDone, no active-session filter; the consumer decides.*/- onSessionNeedsReply?: (sessionId: string, options?: { inputHandoff: true }) => void;+ onSessionNeedsReply?: (sessionId: string, options?: { inputHandoff: true; inputHandoffRequestId?: string }) => void;}/**@@ -392,8 +392,14 @@ export function useSessionRunningStatus(&& !info.hasPendingPermission&& !info.hasPendingPlanReview&& !info.hasPendingPluginSetup;- if (handoffOnly) onSessionNeedsReplyRef.current?.(id, { inputHandoff: true });- else onSessionNeedsReplyRef.current?.(id);+ if (handoffOnly) {+ const handoffKey = (newKeys ?? keys)?.find((key) => key.startsWith('handoff:'));+ const requestId = handoffKey?.slice('handoff:'.length, handoffKey.lastIndexOf(':'));+ onSessionNeedsReplyRef.current?.(id, {+ inputHandoff: true,+ ...(requestId ? { inputHandoffRequestId: requestId } : {}),+ });+ } else onSessionNeedsReplyRef.current?.(id);}// Other hook consumers only read running status. They may add the// in-app dot, but must not consume the system notification owner's edge.diff --git a/apps/desktop/src/renderer/lib/sessionEventNotification.ts b/apps/desktop/src/renderer/lib/sessionEventNotification.tsindex 0862caff26..b086114833 100644--- a/apps/desktop/src/renderer/lib/sessionEventNotification.ts+++ b/apps/desktop/src/renderer/lib/sessionEventNotification.ts@@ -115,6 +115,8 @@ export function sendSessionEventNotification(feishu?: boolean;/** Main owns the phone push; Feishu falls back only without an IM target. */inputHandoff?: true;+ /** The request that caused this event, independent of later task state. */+ inputHandoffRequestId?: string;} = {},): void {// The user is already looking at Cindy. In-app attention remains available,@@ -122,13 +124,13 @@ export function sendSessionEventNotification(if (typeof document !== 'undefined' && document.hasFocus()) return;if (kind === 'needs-reply' && options.inputHandoff) {- // Keep the desktop reminder immediate while existing IPC reads determine- // whether Main already sends the request's fixed pointer in an IM channel.+ // Keep the desktop reminder immediate; Main owns request-scoped IM routing.deliverSessionEventNotification(sessionId, title, kind, options.remoteDevice === true,{ ...options, mobile: false, feishu: false });// The controller cannot resolve the execution host's IM bindings locally.- if (options.remoteDevice !== true && options.feishu !== false && getFeishuNotificationsEnabled()) {- void sendUnhandledHandoffFeishuNotification(sessionId, title);+ if (options.remoteDevice !== true && options.feishu !== false && options.inputHandoffRequestId+ && getFeishuNotificationsEnabled()) {+ void sendUnhandledHandoffFeishuNotification(sessionId, title, options.inputHandoffRequestId);}return;}@@ -142,26 +144,18 @@ export function sendSessionEventNotification(deliverSessionEventNotification(sessionId, title, kind, options.remoteDevice === true, options);}-const IM_SESSION_SOURCES = new Set(['feishu', 'slack', 'telegram', 'x', 'discord', 'wechat', 'dingtalk', 'wecom']);--/** Ordinary Desktop handoffs have no Main IM pointer; preserve the owner's global Feishu setting. */-async function sendUnhandledHandoffFeishuNotification(sessionId: string, title: string): Promise<void> {+/** Main resolves the event's IM ownership; persisted source alone is not a live route. */+async function sendUnhandledHandoffFeishuNotification(sessionId: string, title: string, requestId: string): Promise<void> {const owner = getDataOwnerGeneration();try {- const [row, binding] = await Promise.all([- window.electronAPI.localDb.sessions.get(sessionId),- window.electronAPI.binding.resolveSession(sessionId),- ]);- // Failed/absent routing data is not proof that Main has no target.+ const row = await window.electronAPI.localDb.sessions.get(sessionId);+ // Missing session data is not proof of a valid local notification target.if (!row || typeof row !== 'object' || Array.isArray(row)) return;- const session = row as { source?: unknown; feishuOpenId?: unknown };- if (binding.attached- || (typeof session.source === 'string' && IM_SESSION_SOURCES.has(session.source))- || (typeof session.feishuOpenId === 'string' && session.feishuOpenId.trim())) return;if (!isDataOwnerGenerationCurrent(owner) || !getFeishuNotificationsEnabled()|| (typeof document !== 'undefined' && document.hasFocus())) return;await window.electronAPI.notificationShowSessionEvent({sessionId, title, kind: 'needs-reply', markAttention: false,+ inputHandoffRequestId: requestId,channels: { desktop: false, feishu: true, mobile: false },});} catch {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 82673297cf..1f5adf6692 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2934,6 +2934,7 @@ interface ElectronAPI {sessionId: string;title: string;kind: 'done' | 'error' | 'needs-reply';+ inputHandoffRequestId?: string;/*** 选择性走哪些通知通道; 缺省 / 未传 → 兼容旧行为(仅桌面)。* renderer 侧 gate(localStorage notifications.enabled /