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(desktop): clear event-backed attention after task deletion

Dante2cfcfe87382b
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index ed600fc05b..605069baf2 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -29,6 +29,8 @@ const h = vi.hoisted(() => ({
client: null as { drizzle: ReturnType<typeof drizzle> } | null,
sqlite: null as InstanceType<typeof import('better-sqlite3')> | null,
handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ setBadgeCount: vi.fn(),
+ commitBotProfileDeletion: vi.fn(),
relocate: vi.fn(async (): Promise<{ persistedSdkSessionId: string | null }> => ({
persistedSdkSessionId: null,
})),
@@ -81,7 +83,7 @@ vi.mock('electron', () => ({
// app.getPath('userData') 并对真实文件系统做 fire-and-forget fs.rm。这里返回每次
// 测试用 mkdtemp 生成的独立目录,避免并发 worktree 共享同一字面量路径互相删 fixture,
// 也避免 Windows 把 POSIX 字面量解析成盘符根相对路径。
- app: { getPath: () => h.userDataDir },
+ app: { getPath: () => h.userDataDir, setBadgeCount: h.setBadgeCount },
}));
vi.mock('@cindy/maker-core/pi-subagent-runs', () => ({
piSubagentRunRoot: (agentHome: string, sessionId: string) =>
@@ -90,6 +92,12 @@ vi.mock('@cindy/maker-core/pi-subagent-runs', () => ({
writePiSubagentDeletedTombstone: h.writePiSubagentDeletedTombstone,
clearPiSubagentDeletedTombstone: h.clearPiSubagentDeletedTombstone,
}));
+vi.mock('../../botProfileDeletionStore.js', () => ({
+ commitBotProfileDeletion: h.commitBotProfileDeletion,
+}));
+vi.mock('../../../appSessionState', () => ({
+ getActiveAppSession: () => ({ dataOwnerId: 'owner-a', generation: 1 }),
+}));
vi.mock('../../../logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
@@ -144,6 +152,7 @@ vi.mock('../../../cindy-brain/index.js', () => ({
import {
broadcastSessionPatched,
+ deleteBotProfileAndDetachSessionsInDb,
patchSessionMetaInDb,
persistSessionFields,
registerSessionIpc,
@@ -152,6 +161,11 @@ import {
setSessionWorktreeRecycle,
updateSessionInDb,
} from '../sessions';
+import {
+ clearAllSessionAttention,
+ getAttentionCount,
+ markSessionNeedsAttention,
+} from '../../../appBadgeService';
import { retireDeletedPiSubagentState } from '../piSubagentDeletion';
import { setSessionRouteLockImplementation } from '../../sessionRouteLock';
import { assertTrustedAppRendererEvent } from '../../../security/trustedAppRenderer.js';
@@ -277,7 +291,9 @@ async function invokeCreate(body: Record<string, unknown>): Promise<unknown> {
}
beforeEach(() => {
+ clearAllSessionAttention();
vi.clearAllMocks();
+ h.commitBotProfileDeletion.mockReset();
h.relocate.mockImplementation(async () => ({ persistedSdkSessionId: null }));
h.closeSession.mockClear();
h.routeLock.mockImplementation(async (_sessionId, task) => task());
@@ -322,6 +338,80 @@ afterEach(async () => {
});
describe('local-db:sessions:update handler wiring', () => {
+ it.each([invokeUpdate, invokePatchMeta])(
+ 'clears only the deleted task from event-backed app attention (%#)',
+ async (update) => {
+ // These tasks have not entered a renderer catalog projection yet.
+ markSessionNeedsAttention('cc-local');
+ markSessionNeedsAttention('codex-local');
+ expect(getAttentionCount()).toBe(2);
+
+ await update('cc-local', { status: 'deleted' });
+ expect(getAttentionCount()).toBe(1);
+ await update('codex-local', { status: 'deleted' });
+ expect(getAttentionCount()).toBe(0);
+ if (process.platform !== 'win32') expect(h.setBadgeCount).toHaveBeenLastCalledWith(0);
+ },
+ );
+
+ it.each([invokeUpdate, invokePatchMeta])(
+ 'retains attention when deletion fails or the task is missing (%#)',
+ async (update) => {
+ markSessionNeedsAttention('cc-local');
+ markSessionNeedsAttention('missing');
+ h.sqlite!.exec(`CREATE TRIGGER reject_delete BEFORE UPDATE OF status ON sessions
+ WHEN NEW.status = 'deleted' BEGIN SELECT RAISE(ABORT, 'write failed'); END`);
+ await expect(update('cc-local', { status: 'deleted' })).rejects.toThrow('PRECONDITION_FAILED');
+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get('cc-local'))
+ .toEqual({ status: 'active' });
+ await expect(update('missing', { status: 'deleted' })).rejects.toThrow('NOT_FOUND');
+ expect(getAttentionCount()).toBe(2);
+ },
+ );
+
+ it.each([invokeUpdate, invokePatchMeta])(
+ "does not clear a new owner's attention after an in-flight deletion (%#)",
+ async (update) => {
+ markSessionNeedsAttention('cc-local');
+ h.captureOwnerScope = true;
+ h.routeLock.mockImplementationOnce(async (_sessionId, task) => {
+ const result = await task();
+ h.ownerCurrent = false;
+ return result;
+ });
+ await update('cc-local', { status: 'deleted' });
+ expect(getAttentionCount()).toBe(1);
+ },
+ );
+
+ it('clears deleted Bot task attention only after its transaction succeeds', async () => {
+ markSessionNeedsAttention('bot-task');
+ markSessionNeedsAttention('other-task');
+ h.commitBotProfileDeletion.mockRejectedValueOnce(new Error('write failed'));
+ await expect(deleteBotProfileAndDetachSessionsInDb('bot', ['bot-task'], false))
+ .rejects.toThrow('write failed');
+ expect(getAttentionCount()).toBe(2);
+
+ h.commitBotProfileDeletion.mockResolvedValueOnce({ sessionIds: ['bot-task'], status: 'deleted' });
+ await deleteBotProfileAndDetachSessionsInDb('bot', ['bot-task'], false);
+ expect(getAttentionCount()).toBe(1);
+ });
+
+ it('preserves attention when Bot history is retained or the owner changes', async () => {
+ markSessionNeedsAttention('bot-task');
+ h.commitBotProfileDeletion.mockResolvedValueOnce({ sessionIds: ['bot-task'], status: 'archived' });
+ await deleteBotProfileAndDetachSessionsInDb('bot', ['bot-task'], true);
+ expect(getAttentionCount()).toBe(1);
+
+ h.captureOwnerScope = true;
+ h.commitBotProfileDeletion.mockImplementationOnce(async () => {
+ h.ownerCurrent = false;
+ return { sessionIds: ['bot-task'], status: 'deleted' };
+ });
+ await deleteBotProfileAndDetachSessionsInDb('bot', ['bot-task'], false);
+ expect(getAttentionCount()).toBe(1);
+ });
+
it('isolates device-link and renderer failures while broadcasting a session patch', () => {
const failedWindowSend = vi.fn(() => {
throw new Error('window closed');
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index e156315071..7de954ec70 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -27,6 +27,7 @@ import { getDbClient } from '../client/current';
import * as currentDb from '../client/current';
import type { DbClient } from '../client/DbClient';
import { sessions, messages } from '../schema';
+import { clearSessionAttention } from '../../appBadgeService';
import { commitBotProfileDeletion } from '../botProfileDeletionStore.js';
import {
LIST_PREVIEW_EXTRACT_SQL,
@@ -1913,6 +1914,9 @@ export async function updateSessionInDb(
row.summary = null;
}
const updated = sessionToCamel(row);
+ if (updated.status === 'deleted' && isOwnerScopeCurrent(ownerScope)) {
+ clearSessionAttention(sid, 'explicit');
+ }
const projectTargetChanged = p.workspaceKind !== undefined || p.workingDir !== undefined;
const settingsChanged = Object.keys(p).some((key) => REMOTE_PERSIST_FIELDS.has(key));
const titleChanged = p.title !== undefined;
@@ -2056,6 +2060,9 @@ export async function patchSessionMetaInDb(
cleanupSessionRuntimeForTerminalStatus(sessionId, patch.status);
return { updated: sessionToCamel(row), source: row.source };
});
+ if (updated.status === 'deleted' && isOwnerScopeCurrent(ownerScope)) {
+ clearSessionAttention(sessionId, 'explicit');
+ }
if (
(patch.status === 'deleted' || patch.status === 'archived') &&
updated.workspaceKind === 'project' &&
@@ -2367,6 +2374,9 @@ export async function deleteBotProfileAndDetachSessionsInDb(
const committedSessionIds = [...new Set(committed.sessionIds)];
for (const id of committedSessionIds) {
+ if (status === 'deleted' && isOwnerScopeCurrent(ownerScope)) {
+ clearSessionAttention(id, 'explicit');
+ }
notifyAgentIslandSessionPatch(id, { status });
broadcastSessionPatched(id, { status, source: 'desktop' }, ownerScope);
notifyGhostSessionStatusChange(id, status, null);