Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): harden deleted session attachment cleanup (#1672)
Dash77219a9e6557
diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.tsindex 2daf3f7756..bf6e1e9112 100644--- a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts@@ -22,11 +22,9 @@ vi.mock('../../logger.js', () => ({const {cleanupOwnedUnpersistedStagedChatAttachments,- cleanupStagedChatAttachments,getChatAttachmentCacheRoot,getChatAttachmentOwnerCacheRoot,getRemoteFileCacheRoot,- removeStagedChatAttachment,stageLocalFileToCache,sweepCacheOnStartup,sweepStagedChatAttachmentsOnStartup,@@ -116,26 +114,6 @@ describe('chat attachment staging cache', () => {await expect(fs.stat(otherOwnerPath)).resolves.toBeDefined();});- it('removes only controlled .bin files', async () => {- const root = getChatAttachmentCacheRoot();- await fs.mkdir(root, { recursive: true });- const stagedPath = path.join(root, 'staged.bin');- const safeNamePath = path.join(root, 'staged.exe');- const directoryPath = path.join(root, 'directory.bin');- const outsidePath = path.join(userDataDir, 'outside.bin');- await fs.writeFile(stagedPath, 'staged');- await fs.writeFile(safeNamePath, 'safe');- await fs.mkdir(directoryPath);- await fs.writeFile(outsidePath, 'outside');-- await cleanupStagedChatAttachments([stagedPath, safeNamePath, directoryPath, outsidePath]);-- await expect(fs.stat(stagedPath)).rejects.toMatchObject({ code: 'ENOENT' });- await expect(fs.stat(safeNamePath)).resolves.toBeDefined();- await expect(fs.stat(directoryPath)).resolves.toBeDefined();- await expect(fs.stat(outsidePath)).resolves.toBeDefined();- });-it('renderer cleanup removes only current-owner files not retained by messages', async () => {const ownerId = 'owner-a';const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);@@ -182,10 +160,4 @@ describe('chat attachment staging cache', () => {await expect(fs.stat(draftPath)).resolves.toBeDefined();});-- it('is idempotent when the staged file is already gone', async () => {- await expect(removeStagedChatAttachment(path.join(getChatAttachmentCacheRoot(), 'gone.bin'))).resolves.toBe(- false,- );- });});diff --git a/apps/desktop/src/main/file-browser/remote-file-cache.ts b/apps/desktop/src/main/file-browser/remote-file-cache.tsindex 8ea8e5272f..cb673bc2ca 100644--- a/apps/desktop/src/main/file-browser/remote-file-cache.ts+++ b/apps/desktop/src/main/file-browser/remote-file-cache.ts@@ -74,64 +74,6 @@ export function getChatAttachmentCacheRoot(): string {return chatAttachmentCacheDir();}-function isInsideChatAttachmentCache(p: string): boolean {- return path.resolve(p).startsWith(`${chatAttachmentCacheDir()}${path.sep}`);-}--/**- * Extract persisted file paths from a user-message content JSON document.- * This is deliberately format-tolerant: malformed/legacy content contributes- * no paths, and the actual deletion function still applies its cache-root and- * `.bin` guards before touching anything on disk.- */-export function extractChatAttachmentPathsFromPersistedContent(content: string): string[] {- try {- const parsed = JSON.parse(content) as { files?: unknown };- if (!Array.isArray(parsed.files)) return [];- return parsed.files.flatMap((entry) => {- if (!entry || typeof entry !== 'object') return [];- const candidate = (entry as { path?: unknown }).path;- return typeof candidate === 'string' ? [candidate] : [];- });- } catch {- return [];- }-}--/** Remove one staged attachment if it is a safe, controlled cache file. */-export async function removeStagedChatAttachment(filePath: string): Promise<boolean> {- if (- typeof filePath !== 'string' ||- !path.isAbsolute(filePath) ||- !isInsideChatAttachmentCache(filePath) ||- path.extname(filePath).toLowerCase() !== '.bin'- ) {- return false;- }- try {- const stat = await fs.lstat(filePath);- if (!stat.isFile() && !stat.isSymbolicLink()) return false;- await fs.unlink(filePath);- return true;- } catch (err) {- const code = (err as NodeJS.ErrnoException | null)?.code;- if (code !== 'ENOENT') {- log.warn('staged chat attachment cleanup failed', {- filePath,- error: String(err),- });- }- return false;- }-}--/** Best-effort batch cleanup used by draft/message/session lifecycle hooks. */-export async function cleanupStagedChatAttachments(- filePaths: readonly string[],-): Promise<void> {- await Promise.all(filePaths.map((filePath) => removeStagedChatAttachment(filePath)));-}-function normalizePathForComparison(filePath: string): string {const resolved = path.resolve(filePath);return process.platform === 'win32' ? resolved.toLowerCase() : resolved;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesClearRace.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesClearRace.test.tsindex f78b0ee874..61be0a28c3 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesClearRace.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesClearRace.test.ts@@ -43,11 +43,6 @@ vi.mock('../../../cindy-media/ledger', () => ({removeRefs: vi.fn(async () => undefined),removeSessionAttachmentRefIfUnreferencedByLiveMessage: vi.fn(async () => undefined),}));-vi.mock('../../../file-browser/remote-file-cache', () => ({- cleanupStagedChatAttachments: vi.fn(async () => undefined),- extractChatAttachmentPathsFromPersistedContent: (content: unknown) =>- content === 'attachment' ? ['C:\\chat-attachment-cache\\race.bin'] : [],-}));vi.mock('../../../device-link/invoke-context', () => ({isDeviceLinkInvoke: vi.fn(() => false),}));@@ -137,7 +132,6 @@ describe('message persistence clear boundary', () => {});it('rewinds a row that lost the clear race and is idempotent', async () => {- const { cleanupStagedChatAttachments } = await import('../../../file-browser/remote-file-cache');sqlite.prepare(`INSERT INTO messages@@ -157,10 +151,6 @@ describe('message persistence clear boundary', () => {clientId: 'client-1',clientIds: ['client-1'],});- expect(cleanupStagedChatAttachments).toHaveBeenCalledWith([- 'C:\\chat-attachment-cache\\race.bin',- ]);-h.broadcast.mockClear();await rewindPersistedUserMessageAfterClear('s1', 'client-1');expect(h.broadcast).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.tsindex 6aef131eb4..ceda5e52c4 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts@@ -8,11 +8,12 @@ const h = vi.hoisted(() => ({db: null as ReturnType<typeof drizzle> | null,sqlite: null as Database.Database | null,handlers: new Map<string, (...args: unknown[]) => unknown>(),- cleanupStagedChatAttachments: vi.fn(async (_filePaths: readonly string[]) => undefined),- query: vi.fn(async (query: string): Promise<Array<{ content: string }>> => {- if (!h.sqlite) throw new Error('test sqlite not initialized');- return h.sqlite.prepare(query).all() as Array<{ content: string }>;- }),+ query: vi.fn(+ async (query: string, params: unknown[] = []): Promise<Array<Record<string, unknown>>> => {+ if (!h.sqlite) throw new Error('test sqlite not initialized');+ return h.sqlite.prepare(query).all(...params) as Array<Record<string, unknown>>;+ },+ ),tx: vi.fn(async (_name: string,@@ -73,22 +74,6 @@ vi.mock('../../../cindy-media/ledger', () => ({vi.mock('../../../cindy-media/chatAttachments', () => ({commitMessageMediaRefs: vi.fn(async () => undefined),}));-vi.mock('../../../file-browser/remote-file-cache', () => ({- cleanupStagedChatAttachments: h.cleanupStagedChatAttachments,- extractChatAttachmentPathsFromPersistedContent: (content: string): string[] => {- try {- const parsed = JSON.parse(content) as { files?: unknown };- if (!Array.isArray(parsed.files)) return [];- return parsed.files.flatMap((entry) => {- if (!entry || typeof entry !== 'object') return [];- const candidate = (entry as { path?: unknown }).path;- return typeof candidate === 'string' ? [candidate] : [];- });- } catch {- return [];- }- },-}));vi.mock('../../client/current', () => ({getDbClient: () => ({ drizzle: h.db, query: h.query, tx: h.tx }),}));@@ -100,7 +85,6 @@ import {findPendingForkOrigin,getMessageDeletionTarget,commitMessageDeletion,- listDeletableSessionPersistedChatAttachmentPaths,listPersistedChatAttachmentPaths,markLatestAgentHandoffConsumed,readPriorUserRoundCost,@@ -186,15 +170,15 @@ function insertCostMessage(}describe('staged chat attachment retention', () => {- it('keeps a shared staged path until the last non-deleted fork is deleted', async () => {+ it('extracts distinct protected paths in SQLite without returning message bodies', async () => {const sqlite = createDb();- sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('parent', 'deleted');- sqlite- .prepare('INSERT INTO sessions (id, parent_session_id, status) VALUES (?, ?, ?)')- .run('fork', 'parent', 'active');+ sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('deleted', 'deleted');+ sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('retained', 'active');const sharedPath = 'C:\\chat-attachment-cache\\owner\\shared.bin';- const parentOnlyPath = 'C:\\chat-attachment-cache\\owner\\parent-only.bin';+ const retainedPath = 'C:\\chat-attachment-cache\\owner\\retained.bin';+ const deletedPath = 'C:\\chat-attachment-cache\\owner\\deleted.bin';+ const unrelatedContent = JSON.stringify({ text: 'x'.repeat(1024 * 1024) });const insert = sqlite.prepare(`INSERT INTO messages (id, client_id, session_id, role, content, created_at@@ -203,66 +187,47 @@ describe('staged chat attachment retention', () => {)`);insert.run({- id: 'parent-message',- sessionId: 'parent',- content: JSON.stringify({- files: [{ path: sharedPath }, { path: parentOnlyPath }],- }),+ id: 'retained-unrelated',+ sessionId: 'retained',+ content: unrelatedContent,createdAt: 1,});insert.run({- id: 'fork-message',- sessionId: 'fork',- content: JSON.stringify({ files: [{ path: sharedPath }] }),+ id: 'retained-attachment',+ sessionId: 'retained',+ content: JSON.stringify({+ files: [+ { path: sharedPath },+ 'legacy-scalar-entry',+ { path: retainedPath },+ { path: sharedPath },+ ],+ }),createdAt: 2,});-- await expect(listDeletableSessionPersistedChatAttachmentPaths('parent')).resolves.toEqual([- parentOnlyPath,- ]);-- sqlite.prepare("UPDATE sessions SET status = 'deleted' WHERE id = 'fork'").run();- await expect(listDeletableSessionPersistedChatAttachmentPaths('parent')).resolves.toEqual([- sharedPath,- parentOnlyPath,- ]);- });-- it('keeps a fork-referenced path when deleting a message from the parent session', async () => {- const sqlite = createDb();- sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('parent', 'active');- sqlite- .prepare('INSERT INTO sessions (id, parent_session_id, status) VALUES (?, ?, ?)')- .run('fork', 'parent', 'active');-- const sharedPath = 'C:\\chat-attachment-cache\\owner\\shared.bin';- const parentOnlyPath = 'C:\\chat-attachment-cache\\owner\\parent-only.bin';- const insert = sqlite.prepare(`- INSERT INTO messages (- id, client_id, session_id, role, content, created_at- ) VALUES (- @id, @clientId, @sessionId, 'user', @content, @createdAt- )- `);insert.run({- id: 'parent-message',- clientId: 'parent-client',- sessionId: 'parent',- content: JSON.stringify({ files: [{ path: sharedPath }, { path: parentOnlyPath }] }),- createdAt: 1,+ id: 'deleted-attachment',+ sessionId: 'deleted',+ content: JSON.stringify({ files: [{ path: deletedPath }] }),+ createdAt: 3,});insert.run({- id: 'fork-message',- clientId: 'fork-client',- sessionId: 'fork',- content: JSON.stringify({ files: [{ path: sharedPath }] }),- createdAt: 2,+ id: 'malformed-attachment',+ sessionId: 'retained',+ content: '{"files":[{"path":"chat-attachment-cache',+ createdAt: 4,});- h.cleanupStagedChatAttachments.mockClear();- await commitMessageDeletion('parent', ['parent-client'], 'handoff');-- expect(h.cleanupStagedChatAttachments).toHaveBeenCalledWith([parentOnlyPath]);+ h.query.mockClear();+ await expect(listPersistedChatAttachmentPaths()).resolves.toEqual([+ sharedPath,+ retainedPath,+ ]);+ expect(h.query).toHaveBeenCalledWith(+ expect.stringContaining('json_tree'),+ ['%chat-attachment-cache%'],+ );+ expect(h.query.mock.calls[0][0]).toContain('SELECT DISTINCT');});it('does not protect staged paths referenced only by deleted sessions', async () => {diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex ec057ca9c3..d62c865619 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -7,7 +7,7 @@*/import { ipcMain, BrowserWindow } from 'electron';-import { and, asc, eq, inArray, lt, gt, gte, desc, isNull, ne, or, sql, type SQL } from 'drizzle-orm';+import { and, asc, eq, inArray, lt, gt, gte, desc, isNull, or, sql, type SQL } from 'drizzle-orm';import { createId } from '@paralleldrive/cuid2';import { getDbClient } from '../client/current';@@ -34,10 +34,6 @@ import { importExternalClaudeCodeMessagesForSession } from '../../maker-host/claimport { isDeviceLinkInvoke } from '../../device-link/invoke-context';import { onMessageCreated as onChatMessageCreatedForEmbedding } from '../../embedders/chat-history-embedder';import { recomputePrRefsForSession, recordPrRefsForMessage } from '../../git-context/prRefsStore';-import {- cleanupStagedChatAttachments,- extractChatAttachmentPathsFromPersistedContent,-} from '../../file-browser/remote-file-cache';import {isSyntheticTriggerText,mergeDismissedIntoErrorContent,@@ -105,12 +101,23 @@ function ownerStampForBroadcast(return getSafeOwnerPushStamp();}-const PERSISTED_CHAT_ATTACHMENT_ROWS_SQL = `SELECT m.content+// DbClient uses better-sqlite3 `.all()`: never return whole message bodies for+// retention bookkeeping. JSON1 extracts only the distinct paths that startup+// cleanup needs, while LIKE avoids invoking json_each for unrelated history.+const PERSISTED_CHAT_ATTACHMENT_CONTENT_PATTERN = '%chat-attachment-cache%';+const PERSISTED_CHAT_ATTACHMENT_PATHS_SQL = `SELECT DISTINCT+ attachment.atom AS filePathFROM messages AS mJOIN sessions AS s ON s.id = m.session_id+ JOIN json_tree(+ CASE WHEN json_valid(m.content) THEN m.content ELSE '{}' END,+ '$.files'+ ) AS attachmentWHERE s.status != 'deleted'AND m.rewind_at IS NULL- AND m.content LIKE '%chat-attachment-cache%'`;+ AND m.content LIKE ?+ AND attachment.key = 'path'+ AND attachment.type = 'text'`;export interface EstimatedSessionValueEntry {clientId: string;@@ -139,70 +146,13 @@ const VALID_ROLES: ReadonlySet<MessageRole> = new Set(['thinking',] as const);-function uniqueStrings(values: readonly string[]): string[] {- return [...new Set(values)];-}--/** Return staged attachment paths persisted by a session's messages. */-export async function listSessionPersistedChatAttachmentPaths(- sessionId: string,-): Promise<string[]> {- const rows = await getDbClient().drizzle- .select({ content: messages.content })- .from(messages)- .where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt)));- return uniqueStrings(- rows.flatMap((row) => extractChatAttachmentPathsFromPersistedContent(row.content)),- );-}--/**- * Return the staged attachment paths that may be removed after deleting one- * session. Forked sessions copy persisted message content, so a path remains- * protected while any other non-deleted session still references it.- */-export async function listDeletableSessionPersistedChatAttachmentPaths(- sessionId: string,-): Promise<string[]> {- const [sessionPaths, retainedPaths] = await Promise.all([- listSessionPersistedChatAttachmentPaths(sessionId),- listPersistedChatAttachmentPathsForOtherSessions(sessionId),- ]);- return sessionPaths.filter((filePath) => !retainedPaths.includes(filePath));-}--/** Return staged attachment paths referenced by other non-deleted sessions. */-export async function listPersistedChatAttachmentPathsForOtherSessions(- sessionId: string,-): Promise<string[]> {- const rows = await getDbClient().drizzle- .select({ content: messages.content })- .from(messages)- .innerJoin(sessions, eq(messages.sessionId, sessions.id))- .where(- and(- ne(messages.sessionId, sessionId),- ne(sessions.status, 'deleted'),- isNull(messages.rewindAt),- ),- );- return uniqueStrings(- rows.flatMap((row) => extractChatAttachmentPathsFromPersistedContent(row.content)),- );-}-/** Return all staged attachment paths retained by the current owner's message DB. */export async function listPersistedChatAttachmentPaths(): Promise<string[]> {- const rows = await getDbClient().query<{ content: unknown }>(- PERSISTED_CHAT_ATTACHMENT_ROWS_SQL,- );- return uniqueStrings(- rows.flatMap((row) =>- typeof row.content === 'string'- ? extractChatAttachmentPathsFromPersistedContent(row.content)- : [],- ),+ const rows = await getDbClient().query<{ filePath: unknown }>(+ PERSISTED_CHAT_ATTACHMENT_PATHS_SQL,+ [PERSISTED_CHAT_ATTACHMENT_CONTENT_PATTERN],);+ return rows.flatMap((row) => (typeof row.filePath === 'string' ? [row.filePath] : []));}export function registerMessageIpc(): void {@@ -882,14 +832,6 @@ export async function commitMessageDeletion(}> {const now = Date.now();const db = getDbClient().drizzle;- const deletedAttachmentPaths = uniqueStrings(- (- await db- .select({ content: messages.content })- .from(messages)- .where(and(eq(messages.sessionId, sessionId), inArray(messages.clientId, clientIds)))- ).flatMap((row) => extractChatAttachmentPathsFromPersistedContent(row.content)),- );const result = await getDbClient().tx('message.delete', {sessionId,clientIds,@@ -902,29 +844,6 @@ export async function commitMessageDeletion(updatedAt: now,});- if (deletedAttachmentPaths.length > 0) {- try {- const remainingAttachmentPaths = new Set(- await listSessionPersistedChatAttachmentPaths(sessionId),- );- const retainedByOtherSessions = new Set(- await listPersistedChatAttachmentPathsForOtherSessions(sessionId),- );- await cleanupStagedChatAttachments(- deletedAttachmentPaths.filter(- (filePath) =>- !retainedByOtherSessions.has(filePath) && !remainingAttachmentPaths.has(filePath),- ),- );- } catch (error) {- log.warn('message staged attachment cleanup failed', {- sessionId,- deletedClientIds: clientIds,- error: error instanceof Error ? error.message : String(error),- });- }- }-// 当前生产聊天附件主要是 session-attachment 粗粒度引用,不能因删除一轮// 误删同 session 其它气泡仍在用的 blob。这里只释放明确以消息 id/clientId// 登记的 message refs;零引用 blob 由 recycler 统一回收。@@ -1076,7 +995,6 @@ export async function rewindPersistedUserMessageAfterClear(if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;if (updated.changes === 0) return;- const attachmentPaths = extractChatAttachmentPathsFromPersistedContent(row.content);const mediaCleanup = await Promise.allSettled([...new Set([row.id, row.clientId])].map((refId) =>removeMediaRefs({ refKind: 'message', refId }),@@ -1106,28 +1024,6 @@ export async function rewindPersistedUserMessageAfterClear(error: cleanup.reason instanceof Error ? cleanup.reason.message : String(cleanup.reason),});}- if (attachmentPaths.length > 0) {- try {- const [remaining, retainedByOtherSessions] = await Promise.all([- listSessionPersistedChatAttachmentPaths(sessionId),- listPersistedChatAttachmentPathsForOtherSessions(sessionId),- ]);- const remainingSet = new Set(remaining);- const retainedSet = new Set(retainedByOtherSessions);- await cleanupStagedChatAttachments(- attachmentPaths.filter(- (filePath) => !remainingSet.has(filePath) && !retainedSet.has(filePath),- ),- );- } catch (error) {- log.warn('clear-race staged attachment cleanup failed', {- sessionId,- clientId,- error: error instanceof Error ? error.message : String(error),- });- }- }-broadcastMessageDeleted({ sessionId, clientId, clientIds: [clientId] }, ownerScope);void recomputePrRefsForSession(sessionId).catch(() => undefined);}diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 013876dabd..f23da9a6e0 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -52,10 +52,8 @@ import {} from '../sessionActiveTurn';import {dismissErrorMessage,- listDeletableSessionPersistedChatAttachmentPaths,rebroadcastAgentSwitchBoundary,} from './messages';-import { cleanupStagedChatAttachments } from '../../file-browser/remote-file-cache';import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';const log = createLogger('sessions');@@ -1447,14 +1445,6 @@ export async function patchSessionMetaInDb(err: err instanceof Error ? err.message : String(err),});});- void listDeletableSessionPersistedChatAttachmentPaths(sessionId)- .then((filePaths) => cleanupStagedChatAttachments(filePaths))- .catch((err) => {- log.warn('staged chat attachment cleanup failed', {- sessionId,- err: err instanceof Error ? err.message : String(err),- });- });}removeHookAttachmentDir(sessionId, patch.status);scheduleWorktreeRecycleForStatusChange(sessionId, patch.status);