Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

Merge upstream/main into fix/desktop-pending-reply-remount

guyong1595170e6b4b
diff --cc apps/desktop/src/main/__tests__/notificationService.test.ts
index d58e84021d,5e9f3278cd..953eed660f
--- a/apps/desktop/src/main/__tests__/notificationService.test.ts
+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts
@@@ -23,9 -23,15 +23,17 @@@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Session } from '@cindy/maker-core';
+import type { BrowserWindow } from 'electron';
+ const chatWindow = vi.hoisted(() => ({ url: 'file:///app/index.html#/bots/groups/group-1' }));
+ vi.mock('../deepLink', () => ({
+ getDeepLinkMainWindow: () => ({ isFocused: () => true, isVisible: () => true, webContents: { getURL: () => chatWindow.url } }),
+ openMainWindowChatMessage: vi.fn(),
+ openMainWindowSession: vi.fn(),
+ }));
+ vi.mock('../agent-island/companionIdentity', () => ({ companionAvatarThumbnail: async () => undefined }));
+
type IpcHandler = (event: unknown, payload: unknown) => Promise<void> | void;
// 捕获被注册的 IPC handlers。每个用例 freshModule 后重置。
@@@ -200,121 -255,91 +257,208 @@@ describe('notificationService — chann
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)(
++ it.each(['owned', 'owner-changed', 'focused', 'muted'] as const)(
+ 'keeps desktop independent of 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',
++ ...(outcome === 'muted' ? { markAttention: false } : {}),
+ channels: { desktop: true, feishu: true, mobile: false },
+ });
+ // Allow Main's independent identity enrichment to finish; the handoff
+ // routing promise below stays unresolved throughout this desktop check.
+ await flushAsync();
+ 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;
++ if (outcome === 'muted') isSessionNotificationsMutedSync.mockReturnValue(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 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, sendInputHandoffChannelNotice, notifyInputHandoffOnce, clearInputHandoffChannelNotices } =
+ await import('../im/shared/inputHandoffChannelNotice');
+ const feishuIm = makeFeishuIm('owner');
+ initNotificationService(baseDeps(feishuIm));
+ const statusListeners = new Set<(status: string) => void>();
+ bindInputHandoffChannelNotice({
+ id: 'im-bot',
+ onStatusChange: (listener: (status: string) => void) => {
+ statusListeners.add(listener);
+ return () => statusListeners.delete(listener);
+ },
+ } as unknown as Session, async () => true);
+ 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 {
+ 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 request
+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();
+ expect(notificationCtor).toHaveBeenCalledTimes(2);
+ expect(markSessionNeedsAttention).toHaveBeenCalledWith('im-bot');
+ expect(sendMobileSessionNotify).not.toHaveBeenCalled();
+
+ await claim('desktop-bot', 'request-desktop');
+ await notify('desktop-bot', 'needs-reply', 'request-desktop'); // ordinary bot: no channel route
+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledOnce();
+
+ await notify('im-bot'); // channel route alone must not hide a question
+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledTimes(2);
+ 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 claim('im-bot', 'request-3');
+ await notify('im-bot', 'needs-reply', 'request-3'); // a removed route cannot suppress a new fallback
+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledTimes(5);
+ } finally {
+ clearInputHandoffChannelNotices();
+ }
+ });
+
+ it('「消息免打扰」任务不发任何外向提醒,但未读照旧记账', async () => {
+ const { initNotificationService } = await freshService();
+ const feishuIm = makeFeishuIm('owner');
+ initNotificationService(baseDeps(feishuIm));
+ isSessionNotificationsMutedSync.mockReturnValue(true);
+
+ // done 与 needs-reply 分别走「预览后的异步分支」和「立即桌面分支」,两条都要断。
+ await invokeHandler({ sessionId: 'muted', title: 'Muted', kind: 'done', channels: { desktop: true, feishu: true, mobile: true } });
+ await invokeHandler({ sessionId: 'muted', title: 'Muted', kind: 'needs-reply', channels: { desktop: true, feishu: true, mobile: true } });
+
+ expect(isSessionNotificationsMutedSync).toHaveBeenCalledWith('muted');
+ expect(markSessionNeedsAttention).toHaveBeenCalledTimes(2);
+ expect(notificationCtor).not.toHaveBeenCalled();
+ expect(sendMobileSessionNotify).not.toHaveBeenCalled();
+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();
+ expect(feishuIm.sendText).not.toHaveBeenCalled();
+ });
+
+ // bot-autonomy / scheduler 这类 main 内直调方不经过 IPC handler,静音门必须在
+ // 公共出口(showDesktopSessionEvent)上,否则静音任务仍会弹出系统 toast。
+ it('main 内直接调公共出口时同样受静音门禁,其它设备任务不受影响', async () => {
+ const { initNotificationService, showDesktopSessionEvent } = await freshService();
+ initNotificationService(baseDeps(makeFeishuIm('owner')));
+ isSessionNotificationsMutedSync.mockReturnValue(true);
+
+ expect(showDesktopSessionEvent(() => null, { sessionId: 'muted', title: 'Muted', kind: 'needs-reply' })).toBe(false);
+ expect(notificationCtor).not.toHaveBeenCalled();
+
+ // 其它设备的任务(markAttention: false)不查本机静音标记,照旧弹。
+ expect(showDesktopSessionEvent(() => null, { sessionId: 'muted', title: 'Remote', kind: 'needs-reply', markAttention: false })).toBe(true);
+ expect(notificationCtor).toHaveBeenCalledOnce();
+ });
+
+ it('keeps remote-device notifications when a local task with the same id is muted', async () => {
+ const { initNotificationService } = await freshService();
+ const feishuIm = makeFeishuIm('owner');
+ initNotificationService(baseDeps(feishuIm));
+ isSessionNotificationsMutedSync.mockReturnValue(true);
+
+ // 还原/复制过的库里可能留着同 id 的本地任务行,那是另一条任务:它的静音标记
+ // 不得把其它设备发来的事件压掉(renderer 对远端任务传 markAttention: false)。
+ await invokeHandler({
+ sessionId: 'collision',
+ title: 'Remote',
+ kind: 'needs-reply',
+ markAttention: false,
+ channels: { desktop: true, feishu: true, mobile: true },
+ });
+
+ expect(notificationCtor).toHaveBeenCalledOnce();
+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledOnce();
+ expect(sendMobileSessionNotify).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: 'collision', muteExempt: true }),
+ );
+ });
+
+ it('keeps every channel for a task that is not muted', async () => {
+ const { initNotificationService } = await freshService();
+ const feishuIm = makeFeishuIm('owner');
+ initNotificationService(baseDeps(feishuIm));
+
+ await invokeHandler({ sessionId: 'loud', title: 'Loud', kind: 'needs-reply', channels: { desktop: true, feishu: true, mobile: true } });
+
+ expect(notificationCtor).toHaveBeenCalledOnce();
+ expect(feishuIm.sendMarkdownText).toHaveBeenCalledOnce();
+ });
+
+ it('re-checks the mute after preview enrichment so muting during the wait still suppresses', async () => {
+ const { initNotificationService } = await freshService();
+ const feishuIm = makeFeishuIm('owner');
+ // 交接判定是发出去之前的最后一个 await,就在那里把免打扰打开。
+ const check = vi.fn(async () => {
+ isSessionNotificationsMutedSync.mockReturnValue(true);
+ return false;
+ });
+ initNotificationService({ ...baseDeps(feishuIm), isCompletionHandledByTeammate: check });
+ getSessionNotificationTurnSignal.mockReturnValue({ id: 'turn:1:2', fallbackEventId: 'turn:1:2', ended: true });
+
+ await invokeHandler({ sessionId: 's1', title: 'Mid-flight', kind: 'done', channels: { desktop: true, feishu: true, mobile: true } });
+
+ expect(check).toHaveBeenCalled();
+ expect(notificationCtor).not.toHaveBeenCalled();
+ expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();
+ });
+
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');
diff --cc apps/desktop/src/main/im/__tests__/desktopConfirmNotice.test.ts
index 0300943dde,b0c66c0b91..84e33c97de
--- a/apps/desktop/src/main/im/__tests__/desktopConfirmNotice.test.ts
+++ b/apps/desktop/src/main/im/__tests__/desktopConfirmNotice.test.ts
@@@ -43,6 -43,44 +43,44 @@@ describe('createDesktopConfirmNotifier'
expect(send).not.toHaveBeenCalled();
});
+ it('「消息免打扰」任务 → 连 IM 提示也不发,连 openId 都不查(卡仍在桌面)', async () => {
+ const send = vi.fn(async () => ({}));
+ const getFeishuOpenId = vi.fn(async () => 'ou_123');
+ const notify = createDesktopConfirmNotifier({
+ getFeishuOpenId,
+ sendFeishuText: send,
+ isSuppressed: (sessionId) => sessionId === 'muted',
+ });
+ notify('muted', '「提交 GitHub issue」的确认卡');
+ // 代输入指引走同一个工厂:同一条静音判定一起管。
- notify('muted', '任务名');
++ expect(await notify('muted', '任务名')).toBe(true);
+ await flush();
+ expect(send).not.toHaveBeenCalled();
+ expect(getFeishuOpenId).not.toHaveBeenCalled();
+
+ // 同一次装配里未静音的任务不受影响。
+ notify('loud', '「提交 GitHub issue」的确认卡');
+ await flush();
+ expect(send).toHaveBeenCalledOnce();
+ });
+
+ it('解析 openId 期间开启免打扰 → 真正发送前重新判定并放弃', async () => {
+ const send = vi.fn(async () => ({}));
+ let muted = false;
+ const notify = createDesktopConfirmNotifier({
+ getFeishuOpenId: async () => {
+ // 查库期间用户点了「消息免打扰」。
+ muted = true;
+ return 'ou_123';
+ },
+ sendFeishuText: send,
+ isSuppressed: () => muted,
+ });
- notify('s1', '「提交 GitHub issue」的确认卡');
++ expect(await notify('s1', '「提交 GitHub issue」的确认卡')).toBe(true);
+ await flush();
+ expect(send).not.toHaveBeenCalled();
+ });
+
it('查询/发送失败 → 只落 warn,不抛出(不影响确认流程)', async () => {
const warn = vi.fn();
const notify = createDesktopConfirmNotifier({
diff --cc apps/desktop/src/main/im/desktopConfirmNotice.ts
index 67728dcbad,5edc44b5ae..b7b15df5a1
--- a/apps/desktop/src/main/im/desktopConfirmNotice.ts
+++ b/apps/desktop/src/main/im/desktopConfirmNotice.ts
@@@ -58,26 -63,27 +63,28 @@@ export function buildInputHandoffNotice
/**
* 组装 fire-and-forget 通知函数(DI 便于单测;生产接线见
- * desktopConfirmNoticeWiring.ts)。返回是否解析到目标,而非是否发送成功;
- * desktopConfirmNoticeWiring.ts)。
++ * desktopConfirmNoticeWiring.ts)。返回提醒是否已接管(含免打扰),而非是否发送成功;
+ * 忽略返回值的既有调用方仍为 best-effort,不抛出。
*/
export function createDesktopConfirmNotifier(
deps: DesktopConfirmNoticeDeps,
buildText: (what: string) => string = buildDesktopConfirmNoticeText,
-): (sessionId: string, what: string) => void {
- return (sessionId, what) => {
- if (deps.isSuppressed?.(sessionId)) return;
- void (async () => {
- try {
- const openId = await deps.getFeishuOpenId(sessionId);
- if (!openId) return;
- // 解析 openId 要查库,期间用户可能刚开了免打扰:真正发之前再确认一次
- // (与 notificationService 在异步富化后、发送前的那道判定同口径)。
- if (deps.isSuppressed?.(sessionId)) 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) => {
++ if (deps.isSuppressed?.(sessionId)) return true;
+ let handled = false;
+ try {
+ const openId = await deps.getFeishuOpenId(sessionId);
++ if (deps.isSuppressed?.(sessionId)) return true;
+ 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 --cc apps/desktop/src/main/im/desktopConfirmNoticeWiring.ts
index 053f5205c4,e1f74ec156..ed19947311
--- a/apps/desktop/src/main/im/desktopConfirmNoticeWiring.ts
+++ b/apps/desktop/src/main/im/desktopConfirmNoticeWiring.ts
@@@ -26,8 -27,11 +27,11 @@@ const log = createLogger('im-desktop-co
/** 生产接线:接管绑定 / 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({
+ // 「消息免打扰」任务不发 IM 提示(桌面确认卡 / 代输入指引都不发);提示属于
+ // 提醒面,与 notificationService / device-link / scheduler-host 的四道门同口径。
+ isSuppressed: (sessionId) => isSessionNotificationsMutedSync(sessionId),
async getFeishuOpenId(sessionId) {
return resolveFeishuNoticeTarget(
{
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index a316d6dca5,eb3530c405..c8f94433e4
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -3340,23 -3435,26 +3434,28 @@@ const inputHandoffImNotifier = createFe
* copy: no screen contents, no purpose text, never a value.
*/
function notifyInputHandoffOwner(sessionId: string, snapshot: InputHandoffSnapshot): void {
+ // 「消息免打扰」任务不提醒主人:这一行的 IM 指引(渠道内一行 / 飞书兜底)与
+ // 手机推送都不发。推送侧另有同一道门,这里同时收掉 IM 一侧。
+ if (isSessionNotificationsMutedSync(sessionId)) return;
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 (!isDataOwnerBroadcastScopeCurrent(ownerScope) || isSessionNotificationsMutedSync(sessionId)) 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),
]);
- // 读标题/预览是异步的:等它回来时用户可能刚开了免打扰,真正发之前再确认一次
- // (手机推送另有 sendMobileSessionNotify 内的同一道判定)。
++ // Preserve main's send-time mute check after the asynchronous reads.
+ if (isSessionNotificationsMutedSync(sessionId)) return;
- // 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,
diff --cc apps/desktop/src/main/notificationService.ts
index 398417e616,c7f5eaa4de..a26870ed51
--- a/apps/desktop/src/main/notificationService.ts
+++ b/apps/desktop/src/main/notificationService.ts
@@@ -29,14 -28,18 +28,19 @@@ import * as path from 'node:path'
import { markSessionNeedsAttention } from './appBadgeService';
import { getMobileNotifyGeneration, sendMobileSessionNotify } from './device-link';
import { notificationPreview } from './notificationPreview';
+ import { companionAvatarThumbnail } from './agent-island/companionIdentity';
+ import { getDeepLinkMainWindow, openMainWindowChatMessage, openMainWindowSession } from './deepLink';
+ import { isSessionNotificationsMutedSync } from './localDb/sessionFlagRegistry';
+ import type { ChatMessageNotification } from './maker-ipc/chatMessageNotifications';
import { readSessionNotificationPreview, type SessionNotificationPreview } from './localDb/sessionNotificationPreview';
import { drainSessionActiveTurnWrites, getSessionNotificationTurnSignal } from './localDb/sessionActiveTurn';
+ import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer';
import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './device-link/broadcast-tap';
- import { latestMessageText } from './localDb/latestMessageText';
import { drainPersistQueue } from './messagePersistBroadcaster';
+import { getInputHandoffNoticeOwnership } from './im/shared/inputHandoffChannelNotice';
import { createLogger } from './logger';
import {
+ getNotificationImageLabel,
getSessionExternalNotificationText,
getSessionNotificationBody,
getTeammateNotificationFallback,
@@@ -393,16 -441,6 +444,17 @@@ export function initNotificationService
})().catch((err) => log.warn('[notification] reply notification failed (non-fatal)', err));
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;
++ if (!isDataOwnerBroadcastScopeCurrent(ownerScope) || getWindow()?.isFocused()
++ || isSessionNotificationsMutedSync(sessionId)) return;
+ }
await sendFeishuMessage(feishuIm, safeTitle, kind);
}
},