Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(review): 静音要收走已上岛的卡片,并补三处竞态

WZBbiao6bcfd237cbbb
diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.ts
index 16a16ba861..75f70c6849 100644
--- a/apps/desktop/src/main/__tests__/notificationService.test.ts
+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts
@@ -234,6 +234,24 @@ describe('notificationService — channels 分发', () => {
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 --git a/apps/desktop/src/main/localDb/__tests__/agentIslandSessionPatch.test.ts b/apps/desktop/src/main/localDb/__tests__/agentIslandSessionPatch.test.ts
new file mode 100644
index 0000000000..5e931946b8
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/agentIslandSessionPatch.test.ts
@@ -0,0 +1,59 @@
+/**
+ * agentIslandSessionPatch —— sessions patch 里灵动岛关心字段的转发口径。
+ *
+ * 「消息免打扰」不只是「后面的事件别进岛」:任务可能已经上岛了,只挡后续事件会让
+ * 卡片永远停在「运行中」。所以开静音和转入后台一样,要把这个任务从岛上收走。
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ handleSessionClosed: vi.fn(),
+ handleSessionMetadataPatch: vi.fn(),
+ getAgentIslandService: vi.fn(),
+}));
+
+vi.mock('../../agent-island/service.js', () => ({
+ getAgentIslandService: h.getAgentIslandService,
+}));
+
+import { notifyAgentIslandSessionPatch } from '../agentIslandSessionPatch';
+
+async function notify(patch: Record<string, unknown>): Promise<void> {
+ notifyAgentIslandSessionPatch('session-1', patch);
+ // 模块用动态 import 解耦,断言前把微任务队列排空。
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.getAgentIslandService.mockReturnValue({
+ handleSessionClosed: h.handleSessionClosed,
+ handleSessionMetadataPatch: h.handleSessionMetadataPatch,
+ });
+});
+
+describe('notifyAgentIslandSessionPatch', () => {
+ it('pulls a task off the island when a mute is turned on', async () => {
+ await notify({ notificationsMuted: true });
+
+ expect(h.handleSessionClosed).toHaveBeenCalledWith('session-1');
+ });
+
+ it('leaves the island alone when a mute is turned off', async () => {
+ await notify({ notificationsMuted: false });
+
+ expect(h.handleSessionClosed).not.toHaveBeenCalled();
+ expect(h.handleSessionMetadataPatch).not.toHaveBeenCalled();
+ });
+
+ it('still forwards metadata patches', async () => {
+ await notify({ title: 'Renamed' });
+
+ expect(h.handleSessionClosed).not.toHaveBeenCalled();
+ expect(h.handleSessionMetadataPatch).toHaveBeenCalledWith('session-1', {
+ title: 'Renamed',
+ workingDir: undefined,
+ workspaceKind: undefined,
+ });
+ });
+});
diff --git a/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts b/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts
index 04bff19d93..84d6873171 100644
--- a/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts
+++ b/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts
@@ -6,6 +6,8 @@ export interface AgentIslandSessionPatch {
workspaceKind?: unknown;
/** 插件后台隐藏时刻;非空 = 任务转入后台,灵动岛与菜单栏收起该任务。 */
hiddenAt?: unknown;
+ /** 开了「消息免打扰」;灵动岛收起该任务。 */
+ notificationsMuted?: unknown;
}
/** 把本地 session 归档/删除/转入后台和 metadata 更新同步给 Agent Island。 */
@@ -20,7 +22,8 @@ export function notifyAgentIslandSessionPatch(
if (
patch.status === 'archived' ||
patch.status === 'deleted' ||
- (patch.hiddenAt !== undefined && patch.hiddenAt !== null)
+ (patch.hiddenAt !== undefined && patch.hiddenAt !== null) ||
+ patch.notificationsMuted === true
) {
service.handleSessionClosed(sessionId);
return;
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsPerTaskFlags.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsPerTaskFlags.test.ts
index 4bf254018c..493aba5e99 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsPerTaskFlags.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsPerTaskFlags.test.ts
@@ -61,7 +61,12 @@ vi.mock('../../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRend
import { registerSessionIpc } from '../sessions';
import { setSessionHidden } from '../sessionHidden';
-import { isSessionHiddenSync, isSessionNotificationsMutedSync, resetSessionFlagRegistryForTesting } from '../../sessionFlagRegistry';
+import {
+ isSessionHiddenSync,
+ isSessionNotificationsMutedSync,
+ noteSessionHidden,
+ resetSessionFlagRegistryForTesting,
+} from '../../sessionFlagRegistry';
function createDb(): void {
h.sqlite?.close();
@@ -240,11 +245,17 @@ describe('per-task notification mute (sessions.notifications_muted)', () => {
patch: { notificationsMuted: true },
});
expect(isSessionNotificationsMutedSync('visible')).toBe(true);
+ // 已经上岛的任务被静音时要顺手把它从岛上收走,否则后面的事件(含终态)都被挡住,
+ // 卡片会永远停在「运行中」。
+ expect(h.notifyAgentIslandSessionPatch).toHaveBeenCalledWith('visible', {
+ notificationsMuted: true,
+ });
});
it('clears the mute and broadcasts the new value to every window', async () => {
await update('visible', { notificationsMuted: true });
h.tapWindowBroadcast.mockClear();
+ h.notifyAgentIslandSessionPatch.mockClear();
await update('visible', { notificationsMuted: false });
@@ -254,6 +265,8 @@ describe('per-task notification mute (sessions.notifications_muted)', () => {
patch: { notificationsMuted: false },
});
expect(isSessionNotificationsMutedSync('visible')).toBe(false);
+ // 关闭静音不动岛态(同一函数在每次 update 上还会转发标题/目录等元数据,
+ // 所以这里不断言整体未调用,只由 agentIslandSessionPatch.test.ts 钉「关静音不收岛」)。
});
it('loads mutes set before this process from the database', async () => {
@@ -264,4 +277,16 @@ describe('per-task notification mute (sessions.notifications_muted)', () => {
await vi.waitFor(() => expect(isSessionNotificationsMutedSync('plugin-visible')).toBe(true));
expect(isSessionNotificationsMutedSync('visible')).toBe(false);
});
+
+ it('keeps a stored mute when another flag is written while the index is still loading', async () => {
+ h.sqlite!.prepare('UPDATE sessions SET notifications_muted = 1 WHERE id = ?').run('plugin-visible');
+ // 触发加载但不等它完成:紧接着的 hidden 写入落在加载窗口内。
+ expect(isSessionHiddenSync('plugin-visible')).toBe(false);
+ noteSessionHidden('plugin-visible', false);
+
+ await list();
+
+ // 这一行被 hidden 改过,不得连带丢掉它原有的静音标记。
+ await vi.waitFor(() => expect(isSessionNotificationsMutedSync('plugin-visible')).toBe(true));
+ });
});
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 9139c443bf..8c9ddf264b 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -2049,6 +2049,11 @@ export async function updateSessionInDb(
// 「消息免打扰」是通知面专用标记:同步给进程内索引,免得通知/灵动岛路径逐事件查库。
if (p.notificationsMuted !== undefined) {
noteSessionNotificationsMuted(sid, updated.notificationsMuted === true, dbClient);
+ // 已经上岛的任务现在才被静音:后面的事件(含终态)都被门挡住,得先把它从岛上收走,
+ // 否则卡片会永远停在「运行中」。
+ if (updated.notificationsMuted === true) {
+ notifyAgentIslandSessionPatch(sid, { notificationsMuted: true });
+ }
}
const projectTargetChanged = p.workspaceKind !== undefined || p.workingDir !== undefined;
const settingsChanged = Object.keys(p).some((key) => REMOTE_PERSIST_FIELDS.has(key));
diff --git a/apps/desktop/src/main/localDb/sessionFlagRegistry.ts b/apps/desktop/src/main/localDb/sessionFlagRegistry.ts
index 1c82cf057f..fe2786c019 100644
--- a/apps/desktop/src/main/localDb/sessionFlagRegistry.ts
+++ b/apps/desktop/src/main/localDb/sessionFlagRegistry.ts
@@ -23,8 +23,9 @@ let hiddenIds = new Set<string>();
let mutedIds = new Set<string>();
let loaded = false;
let loading: Promise<void> | null = null;
-/** 加载期间已被宿主显式改动的 id:加载结果不得覆盖这些更新的事实。 */
-let touchedDuringLoad = new Set<string>();
+/** 加载期间已被宿主显式改动的 id(按字段分开记):加载结果不得覆盖这些更新的事实。 */
+let touchedHiddenDuringLoad = new Set<string>();
+let touchedMutedDuringLoad = new Set<string>();
/** 加载失败后的重试冷却:同步判定在每个 Agent 事件上调用,不能把失败放大成逐事件查库。 */
const RETRY_AFTER_FAILURE_MS = 30_000;
let failedAt = 0;
@@ -45,7 +46,8 @@ function adopt(client: DbClient): void {
mutedIds = new Set();
loaded = false;
loading = null;
- touchedDuringLoad = new Set();
+ touchedHiddenDuringLoad = new Set<string>();
+ touchedMutedDuringLoad = new Set<string>();
failedAt = 0;
}
@@ -70,12 +72,14 @@ export function ensureSessionFlagRegistryLoaded(): Promise<void> {
.where(or(isNotNull(sessions.hiddenAt), eq(sessions.notificationsMuted, true)));
if (owner !== client) return;
for (const row of rows) {
- if (touchedDuringLoad.has(row.id)) continue;
- if (row.hiddenAt != null) hiddenIds.add(row.id);
- if (row.notificationsMuted) mutedIds.add(row.id);
+ // 两列各管各的:只跳过加载期间真被改过的那个字段,否则「加载中顺手把
+ // 另一个字段改一下」会连带丢掉这一行原有的另一个标记。
+ if (!touchedHiddenDuringLoad.has(row.id) && row.hiddenAt != null) hiddenIds.add(row.id);
+ if (!touchedMutedDuringLoad.has(row.id) && row.notificationsMuted) mutedIds.add(row.id);
}
loaded = true;
- touchedDuringLoad = new Set();
+ touchedHiddenDuringLoad = new Set<string>();
+ touchedMutedDuringLoad = new Set<string>();
} catch (error) {
if (owner === client) failedAt = Date.now();
log.warn('load session flags failed', {
@@ -109,7 +113,7 @@ export function isSessionNotificationsMutedSync(sessionId: string): boolean {
export function noteSessionHidden(sessionId: string, hidden: boolean, client = currentClient()): void {
if (!client || client !== currentClient()) return;
adopt(client);
- if (!loaded) touchedDuringLoad.add(sessionId);
+ if (!loaded) touchedHiddenDuringLoad.add(sessionId);
if (hidden) hiddenIds.add(sessionId);
else hiddenIds.delete(sessionId);
if (!loaded) void ensureSessionFlagRegistryLoaded();
@@ -123,7 +127,7 @@ export function noteSessionNotificationsMuted(
): void {
if (!client || client !== currentClient()) return;
adopt(client);
- if (!loaded) touchedDuringLoad.add(sessionId);
+ if (!loaded) touchedMutedDuringLoad.add(sessionId);
if (muted) mutedIds.add(sessionId);
else mutedIds.delete(sessionId);
if (!loaded) void ensureSessionFlagRegistryLoaded();
@@ -136,6 +140,7 @@ export function resetSessionFlagRegistryForTesting(): void {
mutedIds = new Set();
loaded = false;
loading = null;
- touchedDuringLoad = new Set();
+ touchedHiddenDuringLoad = new Set<string>();
+ touchedMutedDuringLoad = new Set<string>();
failedAt = 0;
}
diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.ts
index f23b81812d..b3c09f0b17 100644
--- a/apps/desktop/src/main/notificationService.ts
+++ b/apps/desktop/src/main/notificationService.ts
@@ -336,6 +336,9 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
const afterHandoffSignal = getSessionNotificationTurnSignal(sessionId);
if (afterHandoffSignal?.id !== signal?.id || (afterHandoffSignal && !afterHandoffSignal.ended)) return;
}
+ // 取正文 / 等交接判定期间用户可能刚开了免打扰:真正发之前再确认一次。
+ // 手机通道在 sendMobileSessionNotify 内另有同一道门。
+ if (isSessionNotificationsMutedSync(sessionId)) 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.
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionNotificationMute.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionNotificationMute.test.ts
index 04a7720258..9e1b29e515 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionNotificationMute.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionNotificationMute.test.ts
@@ -2,22 +2,37 @@
* 会话级「消息免打扰」的乐观更新与回滚。
*
* 点下去侧栏必须先切文案(否则要等一次 IPC 往返才更新),写库失败必须翻回来——
- * 留着一个没落库的「已静音」会让用户以为不会被打扰,实际照旧。
+ * 留着一个没落库的「已静音」会让用户以为不会被打扰,实际照旧。但回滚本身不能盖掉
+ * 期间别处刚写进来的新值。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
-const m = vi.hoisted(() => ({ patchLocal: vi.fn(), patchMeta: vi.fn() }));
-vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { patchLocal: m.patchLocal } }));
+const m = vi.hoisted(() => ({
+ patchLocal: vi.fn(),
+ patchMeta: vi.fn(),
+ findById: vi.fn(),
+}));
+vi.mock('@/lib/sessionsStore', () => ({
+ sessionsStore: { patchLocal: m.patchLocal, findById: m.findById },
+}));
vi.mock('@/lib/sessionService', () => ({ patchMeta: m.patchMeta }));
import { setSessionNotificationsMuted } from '../sessionNotificationMute';
const session = { id: 'task', title: 'Task' } as Session;
+/** 让 mock 的 store 有真实语义:patchLocal 写进去,findById 读得到。 */
+let stored: Session;
+
beforeEach(() => {
vi.clearAllMocks();
+ stored = { ...session };
m.patchMeta.mockResolvedValue(session);
+ m.patchLocal.mockImplementation((_id: string, patch: Partial<Session>) => {
+ stored = { ...stored, ...patch };
+ });
+ m.findById.mockImplementation(() => stored);
});
describe('setSessionNotificationsMuted', () => {
@@ -38,4 +53,17 @@ describe('setSessionNotificationsMuted', () => {
expect(m.patchLocal).toHaveBeenCalledWith('task', { notificationsMuted: false });
expect(m.patchLocal).toHaveBeenLastCalledWith('task', { notificationsMuted: true });
});
+
+ it('does not roll back over a newer value another window wrote meanwhile', async () => {
+ m.patchMeta.mockImplementation(async () => {
+ // 等这一趟的过程中另一个窗口把值改回去了。
+ stored = { ...stored, notificationsMuted: false };
+ throw new Error('write failed');
+ });
+
+ await expect(setSessionNotificationsMuted(session, true)).rejects.toThrow('write failed');
+
+ expect(m.patchLocal).toHaveBeenCalledTimes(1);
+ expect(m.patchLocal).toHaveBeenCalledWith('task', { notificationsMuted: true });
+ });
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionNotificationMute.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionNotificationMute.ts
index 4835ef05c0..b5699cde6e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionNotificationMute.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionNotificationMute.ts
@@ -13,7 +13,7 @@ const log = createLogger('session-notification-mute');
*
* 乐观更新 + 失败回滚与置顶同款:先 patchLocal 让侧栏立刻切过去,写库失败再翻回来
* 并抛出,由调用方决定怎么提示。失败必须回滚——留着一个没落库的「已静音」会让用户
- * 以为不会被打扰,实际照旧。
+ * 以为不会被打扰,实际照旧;但回滚本身不能盖掉期间别处刚写进来的新值。
*/
export async function setSessionNotificationsMuted(session: Session, muted: boolean): Promise<void> {
const previous = session.notificationsMuted === true;
@@ -21,7 +21,11 @@ export async function setSessionNotificationsMuted(session: Session, muted: bool
try {
await sessionService.patchMeta(session.id, { notificationsMuted: muted });
} catch (error) {
- sessionsStore.patchLocal(session.id, { notificationsMuted: previous });
+ // 只回滚「还是我们写进去的那个值」的情况:等这一趟的过程中别的窗口可能已经改过它,
+ // 无条件写回 previous 会把新值盖掉(库里已静音、侧栏显示未静音)。
+ if (sessionsStore.findById(session.id)?.notificationsMuted === muted) {
+ sessionsStore.patchLocal(session.id, { notificationsMuted: previous });
+ }
log.error('[session notification mute]', error);
throw error;
}