Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 移除附件启动扫描并增加缓存目录清理 (#3410)
DavidShenXD25826bc8cbbc
diff --git a/apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.ts b/apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.tsindex 424d9143e4..fa9c48dd8f 100644--- a/apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.ts+++ b/apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.ts@@ -18,10 +18,9 @@ describe('chat attachment IPC owner boundary', () => {expect(attachmentIpcSource).not.toContain('authManager.getAuthState().user?.id');});- it('protects persisted paths and rechecks owner scope before renderer cleanup', () => {- expect(attachmentIpcSource).toContain(- 'const protectedPaths = await listPersistedChatAttachmentPaths();',- );+ it('does not query message history and rechecks owner scope before renderer cleanup', () => {+ expect(attachmentIpcSource).not.toContain('listPersistedChatAttachmentPaths');+ expect(attachmentIpcSource).not.toContain('getDbClient');expect(attachmentIpcSource).toContain('activeOwnerScopeKey() === ownerScopeKey');expect(attachmentIpcSource).toContain('cleanupOwnedUnpersistedStagedChatAttachments({');});diff --git a/apps/desktop/src/main/__tests__/imageCacheStartupSweepDisabled.test.ts b/apps/desktop/src/main/__tests__/imageCacheStartupSweepDisabled.test.tsindex a0d6f4f09c..9e555503e3 100644--- a/apps/desktop/src/main/__tests__/imageCacheStartupSweepDisabled.test.ts+++ b/apps/desktop/src/main/__tests__/imageCacheStartupSweepDisabled.test.ts@@ -1,15 +1,24 @@import { describe, expect, it } from 'vitest';import fs from 'node:fs';-describe('legacy image cache settings', () => {- it('does not scan message history during startup', () => {+describe('fixed cache directory settings', () => {+ it('does not scan message history during startup or draft cleanup', () => {const bootstrap = fs.readFileSync(new URL('../bootstrap-electron.ts', import.meta.url),'utf8',);+ const messages = fs.readFileSync(+ new URL('../localDb/ipc/messages.ts', import.meta.url),+ 'utf8',+ );expect(bootstrap).not.toContain('sweepStartupDraftImages');expect(bootstrap).not.toContain('image-cache-orphan-sweep');+ expect(bootstrap).not.toContain('sweepStagedChatAttachmentsOnStartup');+ expect(bootstrap).not.toContain('listPersistedChatAttachmentPaths');+ expect(messages).not.toContain('listPersistedChatAttachmentPaths');+ expect(messages).not.toContain('%chat-attachment-cache%');+ expect(messages).not.toContain("'$.files'");});it('does not expose automatic scan or cleanup handlers', () => {@@ -23,13 +32,92 @@ describe('legacy image cache settings', () => {expect(storageIpc).not.toContain('FROM messages INDEXED BY');});- it('guards the fixed directory opener with the trusted renderer check', () => {+ it('guards every fixed directory action with the trusted renderer check', () => {+ const bootstrap = fs.readFileSync(+ new URL('../bootstrap-electron.ts', import.meta.url),+ 'utf8',+ );+ for (const channel of [+ 'cindy-media:legacy-images-open-dir',+ 'cindy-media:legacy-images-clear',+ 'cindy-media:chat-attachments-open-dir',+ 'cindy-media:chat-attachments-clear',+ ]) {+ const start = bootstrap.indexOf(`ipcMain.handle('${channel}'`);+ expect(start, channel).toBeGreaterThan(-1);+ expect(bootstrap.slice(start, start + 300), channel).toContain(+ 'assertTrustedAppRendererEvent(event)',+ );+ }+ });++ it('confirms fixed directory deletion in Main with cancel as the safe default', () => {const bootstrap = fs.readFileSync(new URL('../bootstrap-electron.ts', import.meta.url),'utf8',);- const start = bootstrap.indexOf("ipcMain.handle('cindy-media:legacy-images-open-dir'");- expect(start).toBeGreaterThan(-1);- expect(bootstrap.slice(start, start + 300)).toContain('assertTrustedAppRendererEvent(event)');+ const confirmBlock = bootstrap.slice(+ bootstrap.indexOf('const confirmFixedDirectoryClear'),+ bootstrap.indexOf('const captureActiveChatAttachmentRoot'),+ );++ expect(confirmBlock).toContain('BrowserWindow.fromWebContents(event.sender)');+ expect(confirmBlock).toContain('dialog.showMessageBox(ownerWindow');+ expect(confirmBlock).toContain("t('settings.about.storage.cancelButton')");+ expect(confirmBlock).toContain('defaultId: 1');+ expect(confirmBlock).toContain('cancelId: 1');+ expect(confirmBlock).toContain('noLink: true');++ for (const channel of [+ 'cindy-media:legacy-images-clear',+ 'cindy-media:chat-attachments-clear',+ ]) {+ const start = bootstrap.indexOf(`ipcMain.handle('${channel}'`);+ expect(bootstrap.slice(start, start + 900), channel).toContain(+ 'confirmFixedDirectoryClear(event',+ );+ }+ });++ it('encodes fixed directory confirmation and cleanup failures as IPC errors', () => {+ const bootstrap = fs.readFileSync(+ new URL('../bootstrap-electron.ts', import.meta.url),+ 'utf8',+ );+ const storageBlock = bootstrap.slice(+ bootstrap.indexOf('// ── 存储空间卡片(关于页)IPC:媒体总仓回收器 + 对账'),+ bootstrap.indexOf('// F5: SDK send-time temporary base64 read'),+ );++ expect(storageBlock).toContain('const runFixedDirectoryIpcAction');+ expect(storageBlock).toContain('if (isIpcError(error)) throw error;');+ expect(storageBlock).toContain(+ "throwIpcError('INTERNAL', 'fixed cache directory action failed')",+ );+ expect(storageBlock).toContain(+ "'fixed directory cleanup requires a live owner window'",+ );+ expect(storageBlock).toContain(+ "runFixedDirectoryIpcAction('legacy-images-clear'",+ );+ expect(storageBlock).toContain(+ "runFixedDirectoryIpcAction('chat-attachments-clear'",+ );+ });++ it('opens and clears only the active owner chat attachment directory', () => {+ const bootstrap = fs.readFileSync(+ new URL('../bootstrap-electron.ts', import.meta.url),+ 'utf8',+ );+ const storageBlock = bootstrap.slice(+ bootstrap.indexOf('// ── 存储空间卡片'),+ bootstrap.indexOf('// F5: SDK send-time temporary base64 read'),+ );++ expect(storageBlock).toContain('const ownerId = getActiveAppSession().dataOwnerId;');+ expect(storageBlock).toContain('getChatAttachmentOwnerCacheRoot(ownerId)');+ expect(storageBlock).toContain('activeOwnerScopeKey() === ownerScopeKey');+ expect(storageBlock).not.toContain('getChatAttachmentCacheRoot()');});});diff --git a/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts b/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.tsindex df30e65f6a..f916d827c6 100644--- a/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts@@ -22,8 +22,11 @@ describe('model pricing prewarm ordering', () => {const localDbReady = source.indexOf('const dbClientTakeover = await ensureLifecycleDbClient(userId);');const failedGuard = source.indexOf("dbClientTakeover.mode === 'failed'");const unchangedGuard = source.indexOf("dbClientTakeover.mode === 'unchanged'");- const attachmentSweep = source.indexOf('sweepStagedChatAttachmentsOnStartup({');- const lifecycleStartupBlock = source.slice(localDbReady, attachmentSweep);+ const takeoverStart = source.indexOf(+ 'if (dbClientTakeover.shouldReleaseMainDb',+ unchangedGuard,+ );+ const lifecycleStartupBlock = source.slice(localDbReady, takeoverStart);const earlyUsageIpc = source.indexOf('registerMakerUsageIpc(ipcMaker);');const prewarm = source.indexOf('void prewarmModelPricing();');const refreshCatalog = source.indexOf('await refreshCustomProvidersIntoCatalog(');@@ -31,7 +34,7 @@ describe('model pricing prewarm ordering', () => {expect(localDbReady).toBeGreaterThanOrEqual(0);expect(failedGuard).toBeGreaterThan(localDbReady);expect(unchangedGuard).toBeGreaterThan(failedGuard);- expect(attachmentSweep).toBeGreaterThan(unchangedGuard);+ expect(takeoverStart).toBeGreaterThan(unchangedGuard);expect(lifecycleStartupBlock).not.toContain('BrowserWindow.getAllWindows().some(isSecondaryAppWindow)',);@@ -49,19 +52,13 @@ describe('model pricing prewarm ordering', () => {expect(source.slice(earlyUsageIpc, nextIpc)).not.toContain('prewarmModelPricing');});- it('does not block owner ensureReady on staged attachment bookkeeping', () => {+ it('does not run staged attachment bookkeeping during owner startup', () => {const onReady = source.slice(source.indexOf('onReady: async (userId) => {'),source.indexOf('onReadyError:'),);- expect(onReady).toContain('STARTUP_STAGED_ATTACHMENT_SWEEP_DELAY_MS');- expect(onReady).toContain('setTimeout(() => {');- expect(onReady).toContain('void sweepStagedChatAttachmentsOnStartup({');- expect(onReady).toContain('loadProtectedPaths: listPersistedChatAttachmentPaths');- expect(onReady).not.toMatch(/await listPersistedChatAttachmentPaths\(\)/);- expect(onReady).not.toMatch(/await sweepStagedChatAttachmentsOnStartup\(/);- expect(onReady.indexOf('setTimeout(() => {')).toBeLessThan(- onReady.indexOf('void sweepStagedChatAttachmentsOnStartup({'),- );+ expect(onReady).not.toContain('chat-attachment-cache');+ expect(onReady).not.toContain('listPersistedChatAttachmentPaths');+ expect(onReady).not.toContain('sweepStagedChatAttachmentsOnStartup');});});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 02537ff37c..1a4fe9a897 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -61,7 +61,6 @@ import {waitForTurnChangeSetPersistence,} from './turn-change-set/store.js';-const PROCESS_STARTED_AT_MS = Date.now();// Official Linux binaries total hundreds of MB. Keep one shared deadline for// both downloads, but allow normal consumer connections to finish while the// splash displays real byte progress.@@ -256,9 +255,9 @@ import { createChatAttachmentStageHandler } from './chatAttachmentStage';import {cleanupOwnedUnpersistedStagedChatAttachments,getChatAttachmentCacheRoot,+ getChatAttachmentOwnerCacheRoot,getRemoteFileCacheRoot,stageLocalFileToCache,- sweepStagedChatAttachmentsOnStartup,} from './file-browser/remote-file-cache';import { sweepLegacyDialogueWorkingDirs } from './localDb/dialogueWorkdirSelfHeal';import { legacyDialogueUserDataDirNames } from '@cindy/maker-shared/brand-identity';@@ -298,7 +297,6 @@ import { cindyGhostSchemePrivilege } from './cindy-brain/runtime/electronSandboximport { fetchReleaseNotes, fetchReleaseNotesIndex } from './releaseNotesService';import { resolveWorkspacePathCached, resolveWorkspacePathBatchCached } from './pathResolver';import { registerLocalDbIpc } from './localDb/ipc/registerAll';-import { listPersistedChatAttachmentPaths } from './localDb/ipc/messages';import {getSessionRowSnapshot,resumeDeletedPiSubagentCleanup,@@ -6816,14 +6814,12 @@ const registerIpcHandlers = () => {const ownerScopeKey = activeOwnerScopeKey();const ownerId = getActiveAppSession().dataOwnerId;if (!ownerId || isAppSessionBoundaryPending()) return;- const protectedPaths = await listPersistedChatAttachmentPaths();const isCurrentOwner = () =>activeOwnerScopeKey() === ownerScopeKey && !isAppSessionBoundaryPending();if (!isCurrentOwner()) return;await cleanupOwnedUnpersistedStagedChatAttachments({ownerId,filePaths,- protectedPaths,canRemove: isCurrentOwner,});});@@ -7218,6 +7214,94 @@ const registerIpcHandlers = () => {// ── 存储空间卡片(关于页)IPC:媒体总仓回收器 + 对账──// 业务体在 cindy-media/storageIpc.ts(依赖注入,规则 14),这里只做接线。{+ const fixedDirectoryIpcLog = createLogger('fixed-directory-ipc');+ const runFixedDirectoryIpcAction = async <T>(+ actionName: string,+ action: () => Promise<T>,+ ): Promise<T> => {+ try {+ return await action();+ } catch (error) {+ if (isIpcError(error)) throw error;+ fixedDirectoryIpcLog.warn('fixed directory IPC action failed', {+ action: actionName,+ error: error instanceof Error ? error.message : String(error),+ });+ throwIpcError('INTERNAL', 'fixed cache directory action failed');+ }+ };+ const openExistingFixedDirectory = async (+ rootDir: string,+ canOpen: () => boolean = () => true,+ ): Promise<boolean> => {+ try {+ const stat = await fs.promises.lstat(rootDir);+ if (!stat.isDirectory()) return false;+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return false;+ throw err;+ }+ if (!canOpen()) throw new Error('fixed directory owner changed before open');+ const error = await shell.openPath(rootDir);+ if (error) throw new Error(error);+ return true;+ };+ // These actions intentionally accept no renderer path. The frozen xdt-image+ // cache has no owner metadata, so its confirmed cleanup applies to the whole+ // profile-level legacy root. Chat attachments remain scoped to the active+ // owner, but live drafts, message history, and the media ledger are not read:+ // the explicitly confirmed cache is treated as disposable in full.+ const clearFixedDirectory = async (+ rootDir: string,+ canClear: () => boolean = () => true,+ ): Promise<void> => {+ if (!canClear()) throw new Error('fixed directory owner changed before cleanup');+ await fs.promises.rm(rootDir, { recursive: true, force: true });+ };+ const confirmFixedDirectoryClear = async (+ event: Electron.IpcMainInvokeEvent,+ labels: { title: string; message: string; confirmButton: string },+ ): Promise<boolean> => {+ const ownerWindow = BrowserWindow.fromWebContents(event.sender);+ if (!ownerWindow || ownerWindow.isDestroyed()) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'fixed directory cleanup requires a live owner window',+ );+ }+ const result = await dialog.showMessageBox(ownerWindow, {+ type: 'warning',+ title: labels.title,+ message: labels.message,+ buttons: [labels.confirmButton, t('settings.about.storage.cancelButton')],+ defaultId: 1,+ cancelId: 1,+ noLink: true,+ });+ return result.response === 0 && !ownerWindow.isDestroyed() && !event.sender.isDestroyed();+ };+ const captureActiveChatAttachmentRoot = () => {+ const ownerScopeKey = activeOwnerScopeKey();+ const ownerId = getActiveAppSession().dataOwnerId;+ if (!ownerId || isAppSessionBoundaryPending()) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'chat attachment directory requires a stable data owner',+ );+ }+ return {+ rootDir: getChatAttachmentOwnerCacheRoot(ownerId),+ isCurrentOwner: () =>+ activeOwnerScopeKey() === ownerScopeKey && !isAppSessionBoundaryPending(),+ };+ };+ const withActiveChatAttachmentRoot = <T>(+ action: (rootDir: string, isCurrentOwner: () => boolean) => Promise<T>,+ ): Promise<T> => {+ const { rootDir, isCurrentOwner } = captureActiveChatAttachmentRoot();+ return action(rootDir, isCurrentOwner);+ };+// 各窗口草稿附件 URL 上报(composerDraftStore mutator 尾部推送;多窗口// 时清理取全窗口并集,防误删别的窗口的草稿图)。fire-and-forget send。ipcMain.on('cindy-media:report-draft-urls', (event, urls: string[]) => {@@ -7228,19 +7312,16 @@ const registerIpcHandlers = () => {getQueueScanTexts: collectAgentInputQueueScanTexts,loadSnapshotPayloads: loadAllQueueSnapshotPayloads,getRegisteredDraftUrls: getAllRegisteredDraftUrls,- openLegacyImagesDir: async () => {- const rootDir = imageCacheStore.getCacheRoot();- try {- const stat = await fs.promises.lstat(rootDir);- if (!stat.isDirectory()) return false;- } catch (err) {- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return false;- throw err;- }- const error = await shell.openPath(rootDir);- if (error) throw new Error(error);- return true;- },+ openLegacyImagesDir: () => openExistingFixedDirectory(imageCacheStore.getCacheRoot()),+ clearLegacyImagesDir: () => clearFixedDirectory(imageCacheStore.getCacheRoot()),+ openChatAttachmentsDir: () =>+ withActiveChatAttachmentRoot((rootDir, isCurrentOwner) =>+ openExistingFixedDirectory(rootDir, isCurrentOwner),+ ),+ clearChatAttachmentsDir: () =>+ withActiveChatAttachmentRoot((rootDir, isCurrentOwner) =>+ clearFixedDirectory(rootDir, isCurrentOwner),+ ),});ipcMain.handle('cindy-media:storage-stats', () => storageHandlers.stats());ipcMain.handle('cindy-media:storage-scan', (_event, params: { draftUrls: string[] }) =>@@ -7264,6 +7345,43 @@ const registerIpcHandlers = () => {assertTrustedAppRendererEvent(event);return storageHandlers.openLegacyImagesDir();});+ ipcMain.handle('cindy-media:legacy-images-clear', (event) =>+ runFixedDirectoryIpcAction('legacy-images-clear', async () => {+ assertTrustedAppRendererEvent(event);+ const confirmed = await confirmFixedDirectoryClear(event, {+ title: t('settings.about.storage.legacyImagesClearConfirmTitle'),+ message: t('settings.about.storage.legacyImagesClearConfirmDescription'),+ confirmButton: t('settings.about.storage.legacyImagesClearConfirmButton'),+ });+ if (!confirmed) return { cleared: false };+ await storageHandlers.clearLegacyImagesDir();+ return { cleared: true };+ }),+ );+ ipcMain.handle('cindy-media:chat-attachments-open-dir', (event) => {+ assertTrustedAppRendererEvent(event);+ return storageHandlers.openChatAttachmentsDir();+ });+ ipcMain.handle('cindy-media:chat-attachments-clear', (event) =>+ runFixedDirectoryIpcAction('chat-attachments-clear', async () => {+ assertTrustedAppRendererEvent(event);+ const ownerScope = captureActiveChatAttachmentRoot();+ const confirmed = await confirmFixedDirectoryClear(event, {+ title: t('settings.about.storage.chatAttachmentsClearConfirmTitle'),+ message: t('settings.about.storage.chatAttachmentsClearConfirmDescription'),+ confirmButton: t('settings.about.storage.chatAttachmentsClearConfirmButton'),+ });+ if (!confirmed) return { cleared: false };+ if (!ownerScope.isCurrentOwner()) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'chat attachment directory owner changed before cleanup',+ );+ }+ await storageHandlers.clearChatAttachmentsDir();+ return { cleared: true };+ }),+ );}// F5: SDK send-time temporary base64 read (renderer-initiated; main-initiated@@ -7812,44 +7930,6 @@ app.on('ready', async () => {// Phase 1.1: file worker 接管 DB 连接后,释放 main 端的 _db + optimize 定时器。// 如果 worker takeover 失败并进入 inproc fallback,main _db 必须继续保留,// 否则 fallback 会拿到已关闭的连接。- //- // Staged-attachment bookkeeping is not first-paint readiness. The persisted-path- // lookup is a LIKE + json_tree scan over every retained message body; on a- // multi-GB owner DB that blocked LocalDbGate for ~24s after splash had already- // unmounted, leaving a white window. Sweep is fire-and-forget, only queries the- // DB when the owner cache already has stale files, and is delayed so the shared- // db worker can serve session-list / first-paint RPCs first. A stale-cache user- // would otherwise just move the 24s stall from the white screen onto the first- // task-list query (the db worker's better-sqlite3 .all() is synchronous).- const STARTUP_STAGED_ATTACHMENT_SWEEP_DELAY_MS = 5_000;- const stagedAttachmentSweepTimer = setTimeout(() => {- void sweepStagedChatAttachmentsOnStartup({- ownerId: userId,- createdBeforeMs: PROCESS_STARTED_AT_MS,- loadProtectedPaths: listPersistedChatAttachmentPaths,- canContinue: () =>- getActiveAppSession().dataOwnerId === userId && !isAppSessionBoundaryPending(),- })- .then((result) => {- if (result.removed > 0 || result.protected > 0) {- dbClientLog.info('[ChatAttachment] startup staged attachment sweep completed', {- ...result,- ownerId: userId,- });- }- })- .catch((err) => {- dbClientLog.warn(- '[ChatAttachment] startup staged attachment sweep failed (non-fatal)',- {- ownerId: userId,- error: err instanceof Error ? err.message : String(err),- },- );- });- }, STARTUP_STAGED_ATTACHMENT_SWEEP_DELAY_MS);- stagedAttachmentSweepTimer.unref?.();- logStartupPhase('chat-attachment-sweep');if (dbClientTakeover.shouldReleaseMainDb && process.env.XDT_DB_INPROC !== 'true') {// 只把连接交给 worker,不能释放 shared-passive schema reader lease:worker// 还会长期持有同一 DB;lease 必须留到真正 logout / app quit 才释放。diff --git a/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts b/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.tsindex b6a695bdc0..051fdc392a 100644--- a/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/storageIpc.test.ts@@ -99,6 +99,9 @@ function makeHandlers(overrides?: {snapshotPayloads?: string[];registeredDraftUrls?: string[];openLegacyImagesDir?: () => Promise<boolean>;+ clearLegacyImagesDir?: () => Promise<void>;+ openChatAttachmentsDir?: () => Promise<boolean>;+ clearChatAttachmentsDir?: () => Promise<void>;}) {return createStorageIpcHandlers({getQueueScanTexts: () => overrides?.queueTexts ?? [],@@ -107,6 +110,9 @@ function makeHandlers(overrides?: {db,legacyRootDir: legacyRoot,openLegacyImagesDir: overrides?.openLegacyImagesDir ?? (async () => false),+ clearLegacyImagesDir: overrides?.clearLegacyImagesDir ?? (async () => undefined),+ openChatAttachmentsDir: overrides?.openChatAttachmentsDir ?? (async () => false),+ clearChatAttachmentsDir: overrides?.clearChatAttachmentsDir ?? (async () => undefined),});}@@ -222,7 +228,7 @@ describe('reconcile(体检只报不删)', () => {});});-describe('legacy images directory', () => {+describe('fixed cache directories', () => {it('opens only through the fixed-purpose main dependency', async () => {const openLegacyImagesDir = vi.fn(async () => true);const result = await makeHandlers({ openLegacyImagesDir }).openLegacyImagesDir();@@ -230,4 +236,49 @@ describe('legacy images directory', () => {expect(result).toEqual({ opened: true });expect(openLegacyImagesDir).toHaveBeenCalledWith();});++ it('opens the chat attachment root only through its fixed-purpose main dependency', async () => {+ const openChatAttachmentsDir = vi.fn(async () => true);+ const result = await makeHandlers({ openChatAttachmentsDir }).openChatAttachmentsDir();++ expect(result).toEqual({ opened: true });+ expect(openChatAttachmentsDir).toHaveBeenCalledWith();+ });++ it('clears both roots without collecting live refs or reading storage data', async () => {+ const getQueueScanTexts = vi.fn(() => {+ throw new Error('fixed directory cleanup must not collect queue refs');+ });+ const loadSnapshotPayloads = vi.fn(async () => {+ throw new Error('fixed directory cleanup must not load snapshots');+ });+ const clearLegacyImagesDir = vi.fn(async () => undefined);+ const clearChatAttachmentsDir = vi.fn(async () => undefined);+ const handlers = createStorageIpcHandlers({+ getQueueScanTexts,+ loadSnapshotPayloads,+ clearLegacyImagesDir,+ clearChatAttachmentsDir,+ });++ await expect(handlers.clearLegacyImagesDir()).resolves.toBeUndefined();+ await expect(handlers.clearChatAttachmentsDir()).resolves.toBeUndefined();++ expect(clearLegacyImagesDir).toHaveBeenCalledWith();+ expect(clearChatAttachmentsDir).toHaveBeenCalledWith();+ expect(getQueueScanTexts).not.toHaveBeenCalled();+ expect(loadSnapshotPayloads).not.toHaveBeenCalled();+ });++ it('returns an IPC-safe error when a fixed directory cleanup fails', async () => {+ const handlers = makeHandlers({+ clearLegacyImagesDir: async () => {+ throw new Error('C:\\sensitive\\image-cache is locked');+ },+ });++ await expect(handlers.clearLegacyImagesDir()).rejects.toThrow(+ /\[INTERNAL\] failed to clear legacy image directory/,+ );+ });});diff --git a/apps/desktop/src/main/cindy-media/storageIpc.ts b/apps/desktop/src/main/cindy-media/storageIpc.tsindex 410a962e36..7489842137 100644--- a/apps/desktop/src/main/cindy-media/storageIpc.ts+++ b/apps/desktop/src/main/cindy-media/storageIpc.ts@@ -4,7 +4,9 @@* 依赖全部注入(规则 14):Electron 接线在 bootstrap-electron.ts 只做* ipcMain.handle 适配,测试用内存 harness 直接调 handler body。*- * 交互契约(一律先报数后动手):+ * 交互契约:+ * - 两个固定缓存目录只允许打开或整目录清理;清理前由 main 原生对话框做破坏性确认,+ * main 不接受路径,也不读取消息数据库或媒体账本;* - stats:占用总览(账面统计 + 死目录;不在设置页挂载时遍历历史图片目录);* - scan:清理预检——renderer 随参带草稿附件 URL(§4 暂存区 (1)),这里* 叠加内存队列 (2) 与崩溃快照 (3) 组成活引用集,产出各类可清理项报数;@@ -43,6 +45,12 @@ export interface StorageIpcDeps {legacyRootDir?: string;/** Fixed-purpose directory opener. It returns false when the legacy directory is absent. */openLegacyImagesDir?: () => Promise<boolean>;+ /** Delete only the fixed legacy image cache directory; no ledger or message lookup. */+ clearLegacyImagesDir?: () => Promise<void>;+ /** Fixed-purpose directory opener for the active owner's staged chat attachments. */+ openChatAttachmentsDir?: () => Promise<boolean>;+ /** Delete only the active owner's staged attachment root; no ledger or message lookup. */+ clearChatAttachmentsDir?: () => Promise<void>;}export interface StorageStatsResult {@@ -143,6 +151,48 @@ export function createStorageIpcHandlers(deps: StorageIpcDeps) {}},+ async clearLegacyImagesDir(): Promise<void> {+ if (!deps.clearLegacyImagesDir) {+ throwIpcError('INTERNAL', 'legacy image directory cleaner is unavailable');+ }+ try {+ await deps.clearLegacyImagesDir();+ } catch (err) {+ log.warn('clear legacy image directory failed', {+ error: err instanceof Error ? err.message : String(err),+ });+ throwIpcError('INTERNAL', 'failed to clear legacy image directory');+ }+ },++ async openChatAttachmentsDir(): Promise<{ opened: boolean }> {+ if (!deps.openChatAttachmentsDir) {+ throwIpcError('INTERNAL', 'chat attachment directory opener is unavailable');+ }+ try {+ return { opened: await deps.openChatAttachmentsDir() };+ } catch (err) {+ log.warn('open chat attachment directory failed', {+ error: err instanceof Error ? err.message : String(err),+ });+ throwIpcError('INTERNAL', 'failed to open chat attachment directory');+ }+ },++ async clearChatAttachmentsDir(): Promise<void> {+ if (!deps.clearChatAttachmentsDir) {+ throwIpcError('INTERNAL', 'chat attachment directory cleaner is unavailable');+ }+ try {+ await deps.clearChatAttachmentsDir();+ } catch (err) {+ log.warn('clear chat attachment directory failed', {+ error: err instanceof Error ? err.message : String(err),+ });+ throwIpcError('INTERNAL', 'failed to clear chat attachment directory');+ }+ },+async stats(): Promise<StorageStatsResult> {try {const [blobs, deadDirs] = await Promise.all([diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.tsindex 6fe3a5fc9a..419ef1184e 100644--- a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts@@ -27,7 +27,6 @@ const {getRemoteFileCacheRoot,stageLocalFileToCache,sweepCacheOnStartup,- sweepStagedChatAttachmentsOnStartup,} = await import('../remote-file-cache');afterEach(async () => {@@ -71,127 +70,7 @@ describe('chat attachment staging cache', () => {await expect(fs.readFile(stagedPath)).resolves.toEqual(payload);});- it('sweeps only old, unreferenced files for the current owner', async () => {- const ownerId = 'owner-a';- const otherOwnerId = 'owner-b';- const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);- const otherOwnerRoot = getChatAttachmentOwnerCacheRoot(otherOwnerId);- await fs.mkdir(ownerRoot, { recursive: true });- await fs.mkdir(otherOwnerRoot, { recursive: true });-- const orphanPath = path.join(ownerRoot, 'orphan.bin');- const protectedPath = path.join(ownerRoot, 'protected.bin');- const partialPath = path.join(ownerRoot, 'partial.bin.part');- const freshPath = path.join(ownerRoot, 'fresh.bin');- const otherOwnerPath = path.join(otherOwnerRoot, 'other.bin');- await Promise.all([- fs.writeFile(orphanPath, 'orphan'),- fs.writeFile(protectedPath, 'protected'),- fs.writeFile(partialPath, 'partial'),- fs.writeFile(freshPath, 'fresh'),- fs.writeFile(otherOwnerPath, 'other'),- ]);- const oldTime = new Date(Date.now() - 60_000);- await Promise.all([- fs.utimes(orphanPath, oldTime, oldTime),- fs.utimes(protectedPath, oldTime, oldTime),- fs.utimes(partialPath, oldTime, oldTime),- fs.utimes(otherOwnerPath, oldTime, oldTime),- ]);-- await expect(- sweepStagedChatAttachmentsOnStartup({- ownerId,- protectedPaths: [protectedPath],- createdBeforeMs: Date.now() - 1_000,- }),- ).resolves.toMatchObject({ inspected: 4, removed: 2, protected: 1 });-- await expect(fs.stat(orphanPath)).rejects.toMatchObject({ code: 'ENOENT' });- await expect(fs.stat(partialPath)).rejects.toMatchObject({ code: 'ENOENT' });- await expect(fs.stat(protectedPath)).resolves.toBeDefined();- await expect(fs.stat(freshPath)).resolves.toBeDefined();- await expect(fs.stat(otherOwnerPath)).resolves.toBeDefined();- });-- it('does not load persisted paths when the owner cache has no stale files', async () => {- const loadProtectedPaths = vi.fn(async () => {- throw new Error('must not query message bodies when there is nothing to sweep');- });-- await expect(- sweepStagedChatAttachmentsOnStartup({- ownerId: 'owner-empty',- createdBeforeMs: Date.now() - 1_000,- loadProtectedPaths,- }),- ).resolves.toMatchObject({ inspected: 0, removed: 0, protected: 0 });- expect(loadProtectedPaths).not.toHaveBeenCalled();-- const ownerRoot = getChatAttachmentOwnerCacheRoot('owner-fresh');- await fs.mkdir(ownerRoot, { recursive: true });- const freshPath = path.join(ownerRoot, 'fresh.bin');- await fs.writeFile(freshPath, 'fresh');-- await expect(- sweepStagedChatAttachmentsOnStartup({- ownerId: 'owner-fresh',- createdBeforeMs: Date.now() - 1_000,- loadProtectedPaths,- }),- ).resolves.toMatchObject({ inspected: 1, removed: 0, protected: 0 });- expect(loadProtectedPaths).not.toHaveBeenCalled();- await expect(fs.stat(freshPath)).resolves.toBeDefined();- });-- it('loads persisted paths only after it finds stale cache files', async () => {- const ownerId = 'owner-stale';- const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);- await fs.mkdir(ownerRoot, { recursive: true });- const orphanPath = path.join(ownerRoot, 'orphan.bin');- const protectedPath = path.join(ownerRoot, 'protected.bin');- await Promise.all([fs.writeFile(orphanPath, 'orphan'), fs.writeFile(protectedPath, 'kept')]);- const oldTime = new Date(Date.now() - 60_000);- await Promise.all([- fs.utimes(orphanPath, oldTime, oldTime),- fs.utimes(protectedPath, oldTime, oldTime),- ]);- const loadProtectedPaths = vi.fn(async () => [protectedPath]);-- await expect(- sweepStagedChatAttachmentsOnStartup({- ownerId,- createdBeforeMs: Date.now() - 1_000,- loadProtectedPaths,- }),- ).resolves.toMatchObject({ inspected: 2, removed: 1, protected: 1 });- expect(loadProtectedPaths).toHaveBeenCalledOnce();- await expect(fs.stat(orphanPath)).rejects.toMatchObject({ code: 'ENOENT' });- await expect(fs.stat(protectedPath)).resolves.toBeDefined();- });-- it('stops before deleting when the owner is no longer current', async () => {- const ownerId = 'owner-switch';- const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);- await fs.mkdir(ownerRoot, { recursive: true });- const orphanPath = path.join(ownerRoot, 'orphan.bin');- await fs.writeFile(orphanPath, 'orphan');- await fs.utimes(orphanPath, new Date(Date.now() - 60_000), new Date(Date.now() - 60_000));- const loadProtectedPaths = vi.fn(async () => []);-- await expect(- sweepStagedChatAttachmentsOnStartup({- ownerId,- createdBeforeMs: Date.now() - 1_000,- loadProtectedPaths,- canContinue: () => false,- }),- ).resolves.toMatchObject({ inspected: 1, removed: 0, protected: 0 });- expect(loadProtectedPaths).not.toHaveBeenCalled();- await expect(fs.stat(orphanPath)).resolves.toBeDefined();- });-- it('renderer cleanup removes only current-owner files not retained by messages', async () => {+ it('renderer cleanup removes only files from the explicitly discarded current-owner draft', async () => {const ownerId = 'owner-a';const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);const otherOwnerRoot = getChatAttachmentOwnerCacheRoot('owner-b');@@ -211,8 +90,7 @@ describe('chat attachment staging cache', () => {await cleanupOwnedUnpersistedStagedChatAttachments({ownerId,- filePaths: [draftPath, persistedPath, otherOwnerPath, nestedPath],- protectedPaths: [persistedPath],+ filePaths: [draftPath, otherOwnerPath, nestedPath],});await expect(fs.stat(draftPath)).rejects.toMatchObject({ code: 'ENOENT' });@@ -231,7 +109,6 @@ describe('chat attachment staging cache', () => {await cleanupOwnedUnpersistedStagedChatAttachments({ownerId,filePaths: [draftPath],- protectedPaths: [],canRemove: () => 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 2d156e69e0..34fb3e1bc7 100644--- a/apps/desktop/src/main/file-browser/remote-file-cache.ts+++ b/apps/desktop/src/main/file-browser/remote-file-cache.ts@@ -80,27 +80,25 @@ function normalizePathForComparison(filePath: string): string {}/**- * Remove renderer-owned draft copies without crossing owner or persisted-message- * boundaries. The optional guard is checked immediately before unlink so an- * account switch that happens while filesystem metadata is being read cancels- * the destructive step.+ * Remove renderer-owned draft copies without crossing the current owner boundary.+ * Callers invoke this only for explicit draft-discard paths; successful sends use+ * the non-destructive composer reset instead. The optional guard is checked+ * immediately before unlink so an account switch that happens while filesystem+ * metadata is being read cancels the destructive step.*/export async function cleanupOwnedUnpersistedStagedChatAttachments(params: {ownerId: string;filePaths: readonly string[];- protectedPaths: readonly string[];canRemove?: () => boolean;}): Promise<void> {const ownerDir = normalizePathForComparison(chatAttachmentOwnerCacheDir(params.ownerId));- const protectedPaths = new Set(params.protectedPaths.map(normalizePathForComparison));await Promise.all(params.filePaths.map(async (filePath) => {if (typeof filePath !== 'string' ||!path.isAbsolute(filePath) ||path.extname(filePath).toLowerCase() !== '.bin' ||- normalizePathForComparison(path.dirname(filePath)) !== ownerDir ||- protectedPaths.has(normalizePathForComparison(filePath))+ normalizePathForComparison(path.dirname(filePath)) !== ownerDir) {return;}@@ -122,90 +120,6 @@ export async function cleanupOwnedUnpersistedStagedChatAttachments(params: {);}-export interface StartupStagedChatAttachmentSweepResult {- inspected: number;- removed: number;- protected: number;-}--/**- * Remove abandoned dangerous-attachment staging files from the current- * account. Renderer drafts are intentionally in-memory only, so anything- * created by an earlier process and not referenced by persisted messages is- * unreachable after restart. Files created by this process are left alone to- * avoid racing a draft that is still being assembled.- *- * Filesystem is the source of work: persisted-path lookup only runs when the- * owner cache already has stale `.bin` / `.bin.part` files. A LIKE + json_tree- * scan over a multi-GB message table otherwise blocks startup for tens of- * seconds even when the cache directory does not exist.- */-export async function sweepStagedChatAttachmentsOnStartup(params: {- ownerId: string;- createdBeforeMs: number;- protectedPaths?: readonly string[];- loadProtectedPaths?: () => Promise<readonly string[]>;- canContinue?: () => boolean;-}): Promise<StartupStagedChatAttachmentSweepResult> {- const result: StartupStagedChatAttachmentSweepResult = {- inspected: 0,- removed: 0,- protected: 0,- };- const ownerDir = chatAttachmentOwnerCacheDir(params.ownerId);- const entries = await fs.readdir(ownerDir, { withFileTypes: true }).catch(() => []);- const stalePaths: string[] = [];- for (const entry of entries) {- if (!entry.isFile() && !entry.isSymbolicLink()) continue;- if (!entry.name.endsWith('.bin') && !entry.name.endsWith('.bin.part')) continue;-- const filePath = path.join(ownerDir, entry.name);- result.inspected += 1;- try {- const stat = await fs.lstat(filePath);- if (stat.mtimeMs >= params.createdBeforeMs) continue;- stalePaths.push(filePath);- } catch (err) {- const code = (err as NodeJS.ErrnoException | null)?.code;- if (code !== 'ENOENT') {- log.warn('startup staged chat attachment sweep failed for file', {- filePath,- error: String(err),- });- }- }- }- if (stalePaths.length === 0) return result;- if (params.canContinue && !params.canContinue()) return result;-- const protectedList =- params.protectedPaths ??- (params.loadProtectedPaths ? await params.loadProtectedPaths() : []);- if (params.canContinue && !params.canContinue()) return result;- const protectedPaths = new Set(protectedList.map(normalizePathForComparison));-- for (const filePath of stalePaths) {- if (protectedPaths.has(normalizePathForComparison(filePath))) {- result.protected += 1;- continue;- }- try {- if (params.canContinue && !params.canContinue()) return result;- await fs.unlink(filePath);- result.removed += 1;- } catch (err) {- const code = (err as NodeJS.ErrnoException | null)?.code;- if (code !== 'ENOENT') {- log.warn('startup staged chat attachment sweep failed for file', {- filePath,- error: String(err),- });- }- }- }- return result;-}-/** 路径身份前缀(不含 size/mtime):断线兜底按它捞最近副本。 */function prefixHashFor(id: Pick<RemoteFileIdentity, 'transport' | 'endpointId' | 'workdir' | 'relPath'>): string {return createHash('sha1')diff --git a/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts b/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.tsindex bc8dd96bba..337aeb653d 100644--- a/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts@@ -16,20 +16,19 @@ describe('shared-passive schema lease worker takeover wiring', () => {'utf8',);const unchangedGuard = bootstrap.indexOf("dbClientTakeover.mode === 'unchanged'");- const attachmentSweep = bootstrap.indexOf('sweepStagedChatAttachmentsOnStartup({');+ const unchangedReturn = bootstrap.indexOf('return;', unchangedGuard);const takeoverStart = bootstrap.indexOf('if (dbClientTakeover.shouldReleaseMainDb',- attachmentSweep,+ unchangedReturn,);const takeoverEnd = bootstrap.indexOf('custom-mcp-account-switch', takeoverStart);const takeoverBlock = bootstrap.slice(takeoverStart, takeoverEnd);expect(unchangedGuard).toBeGreaterThanOrEqual(0);- expect(attachmentSweep).toBeGreaterThan(unchangedGuard);- expect(takeoverStart).toBeGreaterThan(attachmentSweep);+ expect(unchangedReturn).toBeGreaterThan(unchangedGuard);+ expect(takeoverStart).toBeGreaterThan(unchangedReturn);expect(takeoverBlock).toContain('localDbCloseDb({ preserveSchemaMigrationLease: true })',);- expect(bootstrap.slice(unchangedGuard, attachmentSweep)).toContain('return;');});it('preserves the real lease across takeover close and releases it on logout/quit close', () => {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.tsindex 04ba7001d2..73211b5bf8 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts@@ -85,7 +85,6 @@ import {findPendingForkOrigin,getMessageDeletionTarget,commitMessageDeletion,- listPersistedChatAttachmentPaths,markLatestAgentHandoffConsumed,readPriorUserRoundCost,registerMessageIpc,@@ -169,106 +168,6 @@ function insertCostMessage(});}-describe('staged chat attachment retention', () => {- it('extracts distinct protected paths in SQLite without returning message bodies', async () => {- const sqlite = createDb();- 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 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- ) VALUES (- @id, @id, @sessionId, 'user', @content, @createdAt- )- `);- insert.run({- id: 'retained-unrelated',- sessionId: 'retained',- content: unrelatedContent,- createdAt: 1,- });- insert.run({- id: 'retained-attachment',- sessionId: 'retained',- content: JSON.stringify({- files: [- { path: sharedPath },- 'legacy-scalar-entry',- { path: retainedPath },- { path: sharedPath },- ],- }),- createdAt: 2,- });- insert.run({- id: 'deleted-attachment',- sessionId: 'deleted',- content: JSON.stringify({ files: [{ path: deletedPath }] }),- createdAt: 3,- });- insert.run({- id: 'malformed-attachment',- sessionId: 'retained',- content: '{"files":[{"path":"chat-attachment-cache',- createdAt: 4,- });-- 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 () => {- const sqlite = createDb();- sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('active', 'active');- sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('deleted', 'deleted');- sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('archived', 'archived');-- const insert = sqlite.prepare(`- INSERT INTO messages (- id, client_id, session_id, role, content, created_at- ) VALUES (- @id, @id, @sessionId, 'user', @content, @createdAt- )- `);- insert.run({- id: 'active-message',- sessionId: 'active',- content: JSON.stringify({ files: [{ path: 'C:\\chat-attachment-cache\\active.bin' }] }),- createdAt: 1,- });- insert.run({- id: 'deleted-message',- sessionId: 'deleted',- content: JSON.stringify({ files: [{ path: 'C:\\chat-attachment-cache\\deleted.bin' }] }),- createdAt: 2,- });- insert.run({- id: 'archived-message',- sessionId: 'archived',- content: JSON.stringify({ files: [{ path: 'C:\\chat-attachment-cache\\archived.bin' }] }),- createdAt: 3,- });-- await expect(listPersistedChatAttachmentPaths()).resolves.toEqual([- 'C:\\chat-attachment-cache\\active.bin',- 'C:\\chat-attachment-cache\\archived.bin',- ]);- });-});-describe('local-db:messages:list cursor', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex bcc9c5b754..c79f83ab18 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -191,24 +191,6 @@ function isAutoResumeUserRow(agentMetaJson: string | null): boolean {}}-// 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 filePath- FROM messages AS m- JOIN 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 attachment- WHERE s.status != 'deleted'- AND m.rewind_at IS NULL- AND m.content LIKE ?- AND attachment.key = 'path'- AND attachment.type = 'text'`;-export interface EstimatedSessionValueEntry {clientId: string;money: RegionalMoney;@@ -236,15 +218,6 @@ const VALID_ROLES: ReadonlySet<MessageRole> = new Set(['thinking',] as const);-/** Return all staged attachment paths retained by the current owner's message DB. */-export async function listPersistedChatAttachmentPaths(): Promise<string[]> {- 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 {ipcMain.handle('local-db:messages:list', async (_e, sessionId: unknown, opts: unknown) => {const sid = requireString(sessionId, 'sessionId');diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 67c4737cb9..dc9b46a6af 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -3836,6 +3836,15 @@ contextBridge.exposeInMainWorld('electronAPI', {openLegacyImagesDir: (): Promise<{ opened: boolean }> =>ipcRenderer.invoke('cindy-media:legacy-images-open-dir'),+ clearLegacyImagesDir: (): Promise<{ cleared: boolean }> =>+ ipcRenderer.invoke('cindy-media:legacy-images-clear'),++ openChatAttachmentsDir: (): Promise<{ opened: boolean }> =>+ ipcRenderer.invoke('cindy-media:chat-attachments-open-dir'),++ clearChatAttachmentsDir: (): Promise<{ cleared: boolean }> =>+ ipcRenderer.invoke('cindy-media:chat-attachments-clear'),+stats: (): Promise<{success: boolean;error?: string;diff --git a/apps/desktop/src/renderer/__tests__/storageCleanupCopy.test.ts b/apps/desktop/src/renderer/__tests__/storageCleanupCopy.test.tsnew file mode 100644index 0000000000..321c013c52--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/storageCleanupCopy.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';+import en from '../i18n/locales/en/common.json';+import ja from '../i18n/locales/ja/common.json';+import ko from '../i18n/locales/ko/common.json';+import zhCN from '../i18n/locales/zh-CN/common.json';+import zhTW from '../i18n/locales/zh-TW/common.json';++describe('fixed cache directory cleanup copy', () => {+ it.each([+ ['en', en, 'Clear image cache', 'Clear attachment cache'],+ ['ja', ja, '画像キャッシュを削除', '添付ファイルキャッシュを削除'],+ ['ko', ko, '이미지 캐시 정리', '첨부 파일 캐시 정리'],+ ['zh-CN', zhCN, '清理图片缓存', '清理附件缓存'],+ ['zh-TW', zhTW, '清理圖片快取', '清理附件快取'],+ ] as const)(+ '%s names the target in settings and native confirmation actions',+ (_locale, messages, imageAction, attachmentAction) => {+ const storage = messages.settings.about.storage;++ expect(storage.legacyImagesClearButton).toBe(imageAction);+ expect(storage.legacyImagesClearConfirmButton).toBe(imageAction);+ expect(storage.chatAttachmentsClearButton).toBe(attachmentAction);+ expect(storage.chatAttachmentsClearConfirmButton).toBe(attachmentAction);+ },+ );+});diff --git a/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx b/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsxindex d05c9e6ae7..b4f0da0cae 100644--- a/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx+++ b/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx@@ -1,13 +1,14 @@/*** StorageManagementCard — 关于页「存储空间」卡片。* ---------------------------------------------------------------------------- * 三段式:+ * 组成:* 1. 占用总览(挂载时异步拉一次;数据在本地,拿到前不渲染 loading 骨架,* 规则 7:先拿数据再刷新显示);- * 2. 清理:扫描(报数)→ 明细确认 → 执行 → 结果。发起扫描/清理时把+ * 2. 两个固定缓存目录:打开目录或经破坏性确认后整目录清理;+ * 3. 媒体总仓清理:扫描(报数)→ 明细确认 → 执行 → 结果。发起扫描/清理时把* composerDraftStore 全部草稿附件 URL 随参带给 main——草稿图是合法的* 零引用 blob,main 读不到 renderer 内存,不带就会被当垃圾清掉;- * 3. 体检(对账):只报不删,异常计数展示,全量清单在 main 日志里。+ * 4. 体检(对账):只报不删,异常计数展示,全量清单在 main 日志里。** 无瞬态 loading(规则 7):扫描/体检/清理都是本地毫秒级操作,按钮文案与* 已显示的结果区块在操作期间保持不动,结果到达才一次性刷新——中间态文案@@ -41,6 +42,7 @@ export function StorageManagementCard() {// in-flight 防重入标志(不进 state:操作期间界面零变化,见文件头)。const cleanupBusyRef = useRef(false);const reconcileBusyRef = useRef(false);+ const directoryCleanupBusyRef = useRef(false);const refreshStats = async () => {try {@@ -64,6 +66,45 @@ export function StorageManagementCard() {}};+ const handleClearLegacyImagesDir = async () => {+ if (directoryCleanupBusyRef.current) return;+ directoryCleanupBusyRef.current = true;+ try {+ const result = await window.electronAPI.cindyMediaStorage.clearLegacyImagesDir();+ if (!result.cleared) return;+ toast.success(t('settings.about.storage.legacyImagesCleared'));+ } catch {+ toast.error(t('settings.about.storage.legacyImagesClearFailed'));+ } finally {+ directoryCleanupBusyRef.current = false;+ }+ };++ const handleOpenChatAttachmentsDir = async () => {+ try {+ const result = await window.electronAPI.cindyMediaStorage.openChatAttachmentsDir();+ if (!result.opened) {+ toast.info(t('settings.about.storage.chatAttachmentsDirectoryMissing'));+ }+ } catch {+ toast.error(t('settings.about.storage.chatAttachmentsOpenFailed'));+ }+ };++ const handleClearChatAttachmentsDir = async () => {+ if (directoryCleanupBusyRef.current) return;+ directoryCleanupBusyRef.current = true;+ try {+ const result = await window.electronAPI.cindyMediaStorage.clearChatAttachmentsDir();+ if (!result.cleared) return;+ toast.success(t('settings.about.storage.chatAttachmentsCleared'));+ } catch {+ toast.error(t('settings.about.storage.chatAttachmentsClearFailed'));+ } finally {+ directoryCleanupBusyRef.current = false;+ }+ };+const handleScan = async () => {if (cleanupBusyRef.current) return;cleanupBusyRef.current = true;@@ -181,9 +222,35 @@ export function StorageManagementCard() {{t('settings.about.storage.legacyImagesDescription')}</p></div>- <CardButton onClick={handleOpenLegacyImagesDir}>- {t('settings.about.storage.legacyImagesOpenButton')}- </CardButton>+ <div className="flex shrink-0 items-center gap-2">+ <CardButton onClick={handleOpenLegacyImagesDir}>+ {t('settings.about.storage.legacyImagesOpenButton')}+ </CardButton>+ <CardButton onClick={handleClearLegacyImagesDir}>+ {t('settings.about.storage.legacyImagesClearButton')}+ </CardButton>+ </div>+ </div>++ <Divider />++ <div className="flex items-center justify-between gap-3 px-[18px] py-4">+ <div className="flex min-w-0 flex-col gap-1">+ <span className="text-13 text-[var(--settings-section-sublabel)]">+ {t('settings.about.storage.chatAttachmentsLabel')}+ </span>+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">+ {t('settings.about.storage.chatAttachmentsDescription')}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <CardButton onClick={handleOpenChatAttachmentsDir}>+ {t('settings.about.storage.chatAttachmentsOpenButton')}+ </CardButton>+ <CardButton onClick={handleClearChatAttachmentsDir}>+ {t('settings.about.storage.chatAttachmentsClearButton')}+ </CardButton>+ </div></div><Divider />@@ -334,7 +401,7 @@ function CardButton({type="button"onClick={onClick}className={cn(- 'shrink-0 rounded-md px-2.5 py-1 text-12 font-medium transition-colors',+ 'shrink-0 rounded-full px-2.5 py-1 text-12 font-medium transition-colors','border border-[var(--settings-theme-card-border)]',emphasis? 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)] border-transparent hover:opacity-90'diff --git a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsxindex 21ac387ce0..9925514e52 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx@@ -24,6 +24,9 @@ function storageApi() {return {reportDraftUrls: vi.fn(),openLegacyImagesDir: vi.fn(async () => ({ opened: true })),+ clearLegacyImagesDir: vi.fn(async () => ({ cleared: true })),+ openChatAttachmentsDir: vi.fn(async () => ({ opened: true })),+ clearChatAttachmentsDir: vi.fn(async () => ({ cleared: true })),stats: vi.fn(async () => ({success: true,blobs: { totalCount: 0, totalBytes: 0, cacheCount: 0, cacheBytes: 0 },@@ -48,8 +51,8 @@ beforeEach(() => {afterEach(cleanup);-describe('StorageManagementCard legacy images', () => {- it('renders the directory action without scanning legacy images', async () => {+describe('StorageManagementCard fixed cache directories', () => {+ it('renders both directory actions without scanning either directory', async () => {render(<StorageManagementCard />);await waitFor(() => {@@ -58,6 +61,15 @@ describe('StorageManagementCard legacy images', () => {expect(screen.getByRole('button', { name: 'settings.about.storage.legacyImagesOpenButton' }),).toBeTruthy();+ expect(+ screen.getByRole('button', { name: 'settings.about.storage.legacyImagesClearButton' }),+ ).toBeTruthy();+ expect(+ screen.getByRole('button', { name: 'settings.about.storage.chatAttachmentsOpenButton' }),+ ).toBeTruthy();+ expect(+ screen.getByRole('button', { name: 'settings.about.storage.chatAttachmentsClearButton' }),+ ).toBeTruthy();expect(window.electronAPI.cindyMediaStorage.scan).not.toHaveBeenCalled();expect(window.electronAPI.cindyMediaStorage.cleanup).not.toHaveBeenCalled();});@@ -90,4 +102,58 @@ describe('StorageManagementCard legacy images', () => {);});});++ it('opens the fixed chat attachment directory through the dedicated API', async () => {+ render(<StorageManagementCard />);++ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.chatAttachmentsOpenButton' }),+ );++ await waitFor(() => {+ expect(window.electronAPI.cindyMediaStorage.openChatAttachmentsDir).toHaveBeenCalledWith();+ });+ });++ it('requests image cache cleanup through the privileged API', async () => {+ render(<StorageManagementCard />);++ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.legacyImagesClearButton' }),+ );++ await waitFor(() => {+ expect(window.electronAPI.cindyMediaStorage.clearLegacyImagesDir).toHaveBeenCalledWith();+ expect(toast.success).toHaveBeenCalledWith('settings.about.storage.legacyImagesCleared');+ });+ });++ it('does not report success when native confirmation is cancelled', async () => {+ vi.mocked(window.electronAPI.cindyMediaStorage.clearChatAttachmentsDir).mockResolvedValue({+ cleared: false,+ });+ render(<StorageManagementCard />);++ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.chatAttachmentsClearButton' }),+ );++ await waitFor(() => {+ expect(window.electronAPI.cindyMediaStorage.clearChatAttachmentsDir).toHaveBeenCalledWith();+ });+ expect(toast.success).not.toHaveBeenCalled();+ });++ it('clears the chat attachment cache without passing a path', async () => {+ render(<StorageManagementCard />);++ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.chatAttachmentsClearButton' }),+ );++ await waitFor(() => {+ expect(window.electronAPI.cindyMediaStorage.clearChatAttachmentsDir).toHaveBeenCalledWith();+ expect(toast.success).toHaveBeenCalledWith('settings.about.storage.chatAttachmentsCleared');+ });+ });});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex d8f6693a92..7f5d7ffa4f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -825,8 +825,25 @@"legacyImagesLabel": "Image cache directory","legacyImagesDescription": "Cindy does not scan or clean this directory automatically. Deleting files may make images in message history unavailable; review them before deleting.","legacyImagesOpenButton": "Open directory",+ "legacyImagesClearButton": "Clear image cache","legacyImagesDirectoryMissing": "The image cache directory was not found","legacyImagesOpenFailed": "Could not open the image cache directory. Try again.",+ "legacyImagesClearConfirmTitle": "Clean up the image cache?",+ "legacyImagesClearConfirmDescription": "Only files in the image cache directory will be deleted; the message database will not be queried. Images in message history may become unavailable, and this cannot be undone.",+ "legacyImagesClearConfirmButton": "Clear image cache",+ "legacyImagesCleared": "Image cache cleaned up",+ "legacyImagesClearFailed": "Could not clean up the image cache. Try again.",+ "chatAttachmentsLabel": "Message attachment cache directory",+ "chatAttachmentsDescription": "Some attachments you send are stored here. Cindy does not scan or clean this directory automatically. Deleting files may make attachments in message history unavailable.",+ "chatAttachmentsOpenButton": "Open directory",+ "chatAttachmentsClearButton": "Clear attachment cache",+ "chatAttachmentsDirectoryMissing": "The message attachment cache directory was not found",+ "chatAttachmentsOpenFailed": "Could not open the message attachment cache directory. Try again.",+ "chatAttachmentsClearConfirmTitle": "Clean up the message attachment cache?",+ "chatAttachmentsClearConfirmDescription": "Only files in the message attachment cache directory will be deleted; the message database will not be queried. Some attachments in message history may become unavailable, and this cannot be undone.",+ "chatAttachmentsClearConfirmButton": "Clear attachment cache",+ "chatAttachmentsCleared": "Message attachment cache cleaned up",+ "chatAttachmentsClearFailed": "Could not clean up the message attachment cache. Try again.","cleanupLabel": "Disk cleanup","cleanupDescription": "Scans for media files no session references anymore, oversized caches, and obsolete folders. Shows the numbers first and deletes only after you confirm; images in composer drafts and queued messages are protected automatically.","scanButton": "Scan",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex d93760f842..1ddd20592c 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -825,8 +825,25 @@"legacyImagesLabel": "画像キャッシュディレクトリ","legacyImagesDescription": "Cindy はこのディレクトリを自動でスキャンまたはクリーンアップしません。ファイルを削除するとメッセージ履歴の画像が表示できなくなる場合があるため、内容を確認してから操作してください。","legacyImagesOpenButton": "ディレクトリを開く",+ "legacyImagesClearButton": "画像キャッシュを削除","legacyImagesDirectoryMissing": "画像キャッシュディレクトリが見つかりません","legacyImagesOpenFailed": "画像キャッシュディレクトリを開けませんでした。もう一度お試しください。",+ "legacyImagesClearConfirmTitle": "画像キャッシュをクリーンアップしますか?",+ "legacyImagesClearConfirmDescription": "画像キャッシュディレクトリ内のファイルだけを削除し、メッセージデータベースは参照しません。履歴内の画像が表示できなくなる場合があり、この操作は元に戻せません。",+ "legacyImagesClearConfirmButton": "画像キャッシュを削除",+ "legacyImagesCleared": "画像キャッシュをクリーンアップしました",+ "legacyImagesClearFailed": "画像キャッシュをクリーンアップできませんでした。もう一度お試しください。",+ "chatAttachmentsLabel": "メッセージ添付ファイルのキャッシュディレクトリ",+ "chatAttachmentsDescription": "送信する一部の添付ファイルはここに保存されます。Cindy はこのディレクトリを自動でスキャンまたはクリーンアップしません。ファイルを削除すると履歴内の添付ファイルを開けなくなる場合があります。",+ "chatAttachmentsOpenButton": "ディレクトリを開く",+ "chatAttachmentsClearButton": "添付ファイルキャッシュを削除",+ "chatAttachmentsDirectoryMissing": "メッセージ添付ファイルのキャッシュディレクトリが見つかりません",+ "chatAttachmentsOpenFailed": "メッセージ添付ファイルのキャッシュディレクトリを開けませんでした。もう一度お試しください。",+ "chatAttachmentsClearConfirmTitle": "メッセージ添付ファイルのキャッシュをクリーンアップしますか?",+ "chatAttachmentsClearConfirmDescription": "メッセージ添付ファイルのキャッシュディレクトリ内のファイルだけを削除し、メッセージデータベースは参照しません。履歴内の一部の添付ファイルを開けなくなる場合があり、この操作は元に戻せません。",+ "chatAttachmentsClearConfirmButton": "添付ファイルキャッシュを削除",+ "chatAttachmentsCleared": "メッセージ添付ファイルのキャッシュをクリーンアップしました",+ "chatAttachmentsClearFailed": "メッセージ添付ファイルのキャッシュをクリーンアップできませんでした。もう一度お試しください。","cleanupLabel": "ディスククリーンアップ","cleanupDescription": "どのセッションからも参照されていないメディアファイル、上限を超えたキャッシュ、不要になったフォルダをスキャンします。まず件数を表示し、確認後にのみ削除します。入力欄の下書きや送信待ちメッセージ内の画像は自動的に保護されます。","scanButton": "スキャン",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b609df6d67..54eeffb28f 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -825,8 +825,25 @@"legacyImagesLabel": "이미지 캐시 디렉터리","legacyImagesDescription": "Cindy는 이 디렉터리를 자동으로 검사하거나 정리하지 않습니다. 파일을 삭제하면 메시지 기록의 이미지가 표시되지 않을 수 있으므로 확인 후 작업해 주세요.","legacyImagesOpenButton": "디렉터리 열기",+ "legacyImagesClearButton": "이미지 캐시 정리","legacyImagesDirectoryMissing": "이미지 캐시 디렉터리를 찾을 수 없습니다","legacyImagesOpenFailed": "이미지 캐시 디렉터리를 열 수 없습니다. 다시 시도해 주세요.",+ "legacyImagesClearConfirmTitle": "이미지 캐시를 정리할까요?",+ "legacyImagesClearConfirmDescription": "이미지 캐시 디렉터리의 파일만 삭제하며 메시지 데이터베이스는 조회하지 않습니다. 메시지 기록의 이미지가 표시되지 않을 수 있으며 이 작업은 되돌릴 수 없습니다.",+ "legacyImagesClearConfirmButton": "이미지 캐시 정리",+ "legacyImagesCleared": "이미지 캐시를 정리했습니다",+ "legacyImagesClearFailed": "이미지 캐시를 정리할 수 없습니다. 다시 시도해 주세요.",+ "chatAttachmentsLabel": "메시지 첨부 파일 캐시 디렉터리",+ "chatAttachmentsDescription": "전송하는 일부 첨부 파일은 여기에 저장됩니다. Cindy는 이 디렉터리를 자동으로 검사하거나 정리하지 않습니다. 파일을 삭제하면 메시지 기록의 첨부 파일을 열 수 없게 될 수 있습니다.",+ "chatAttachmentsOpenButton": "디렉터리 열기",+ "chatAttachmentsClearButton": "첨부 파일 캐시 정리",+ "chatAttachmentsDirectoryMissing": "메시지 첨부 파일 캐시 디렉터리를 찾을 수 없습니다",+ "chatAttachmentsOpenFailed": "메시지 첨부 파일 캐시 디렉터리를 열 수 없습니다. 다시 시도해 주세요.",+ "chatAttachmentsClearConfirmTitle": "메시지 첨부 파일 캐시를 정리할까요?",+ "chatAttachmentsClearConfirmDescription": "메시지 첨부 파일 캐시 디렉터리의 파일만 삭제하며 메시지 데이터베이스는 조회하지 않습니다. 메시지 기록의 일부 첨부 파일을 열 수 없게 될 수 있으며 이 작업은 되돌릴 수 없습니다.",+ "chatAttachmentsClearConfirmButton": "첨부 파일 캐시 정리",+ "chatAttachmentsCleared": "메시지 첨부 파일 캐시를 정리했습니다",+ "chatAttachmentsClearFailed": "메시지 첨부 파일 캐시를 정리할 수 없습니다. 다시 시도해 주세요.","cleanupLabel": "디스크 정리","cleanupDescription": "어떤 세션에서도 참조하지 않는 미디어 파일, 한도를 초과한 캐시, 사용하지 않는 폴더를 검사합니다. 먼저 수치를 보여주고 확인 후에만 삭제합니다. 입력창 초안과 대기 중인 메시지의 이미지는 자동으로 보호됩니다.","scanButton": "검사",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 3108e92794..757c3e37b6 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -825,8 +825,25 @@"legacyImagesLabel": "图片缓存目录","legacyImagesDescription": "Cindy 不会自动扫描或清理此目录。删除文件后,历史消息中的图片可能无法显示,请自行确认后操作。","legacyImagesOpenButton": "打开目录",+ "legacyImagesClearButton": "清理图片缓存","legacyImagesDirectoryMissing": "没有找到图片缓存目录","legacyImagesOpenFailed": "无法打开图片缓存目录,请重试",+ "legacyImagesClearConfirmTitle": "清理图片缓存?",+ "legacyImagesClearConfirmDescription": "只会删除图片缓存目录中的文件,不会读取消息数据库。清理后,历史消息中的图片可能无法显示,且无法恢复。",+ "legacyImagesClearConfirmButton": "清理图片缓存",+ "legacyImagesCleared": "图片缓存已清理",+ "legacyImagesClearFailed": "无法清理图片缓存,请重试",+ "chatAttachmentsLabel": "消息附件缓存目录",+ "chatAttachmentsDescription": "发送的部分附件会保存在这里。Cindy 不会自动扫描或清理此目录;删除文件后,历史消息中的附件可能无法打开。",+ "chatAttachmentsOpenButton": "打开目录",+ "chatAttachmentsClearButton": "清理附件缓存",+ "chatAttachmentsDirectoryMissing": "没有找到消息附件缓存目录",+ "chatAttachmentsOpenFailed": "无法打开消息附件缓存目录,请重试",+ "chatAttachmentsClearConfirmTitle": "清理消息附件缓存?",+ "chatAttachmentsClearConfirmDescription": "只会删除消息附件缓存目录中的文件,不会读取消息数据库。清理后,历史消息中的部分附件可能无法打开,且无法恢复。",+ "chatAttachmentsClearConfirmButton": "清理附件缓存",+ "chatAttachmentsCleared": "消息附件缓存已清理",+ "chatAttachmentsClearFailed": "无法清理消息附件缓存,请重试","cleanupLabel": "磁盘清理","cleanupDescription": "扫描没有被任何任务引用的媒体文件、超限缓存与废弃目录。先报数,确认后才删除;输入框草稿和排队消息里的图片会被自动保护。","scanButton": "扫描",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 029d4a4f02..2ce1dd20e7 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -825,8 +825,25 @@"legacyImagesLabel": "圖片快取目錄","legacyImagesDescription": "Cindy 不會自動掃描或清理此目錄。刪除檔案後,歷史訊息中的圖片可能無法顯示,請自行確認後操作。","legacyImagesOpenButton": "開啟目錄",+ "legacyImagesClearButton": "清理圖片快取","legacyImagesDirectoryMissing": "找不到圖片快取目錄","legacyImagesOpenFailed": "無法開啟圖片快取目錄,請重試",+ "legacyImagesClearConfirmTitle": "清理圖片快取?",+ "legacyImagesClearConfirmDescription": "只會刪除圖片快取目錄中的檔案,不會讀取訊息資料庫。清理後,歷史訊息中的圖片可能無法顯示,且無法復原。",+ "legacyImagesClearConfirmButton": "清理圖片快取",+ "legacyImagesCleared": "圖片快取已清理",+ "legacyImagesClearFailed": "無法清理圖片快取,請重試",+ "chatAttachmentsLabel": "訊息附件快取目錄",+ "chatAttachmentsDescription": "傳送的部分附件會儲存在這裡。Cindy 不會自動掃描或清理此目錄;刪除檔案後,歷史訊息中的附件可能無法開啟。",+ "chatAttachmentsOpenButton": "開啟目錄",+ "chatAttachmentsClearButton": "清理附件快取",+ "chatAttachmentsDirectoryMissing": "找不到訊息附件快取目錄",+ "chatAttachmentsOpenFailed": "無法開啟訊息附件快取目錄,請重試",+ "chatAttachmentsClearConfirmTitle": "清理訊息附件快取?",+ "chatAttachmentsClearConfirmDescription": "只會刪除訊息附件快取目錄中的檔案,不會讀取訊息資料庫。清理後,歷史訊息中的部分附件可能無法開啟,且無法復原。",+ "chatAttachmentsClearConfirmButton": "清理附件快取",+ "chatAttachmentsCleared": "訊息附件快取已清理",+ "chatAttachmentsClearFailed": "無法清理訊息附件快取,請重試","cleanupLabel": "磁碟清理","cleanupDescription": "掃描沒有被任何任務引用的媒體檔案、超限快取與廢棄目錄。先報數,確認後才刪除;輸入框草稿和排隊訊息裡的圖片會被自動保護。","scanButton": "掃描",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 30a64e830a..1577820a41 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3428,6 +3428,9 @@ interface ElectronAPI {/** 本窗口草稿附件 URL 变化时上报(fire-and-forget;多窗口防误删取证)。 */reportDraftUrls: (urls: string[]) => void;openLegacyImagesDir: () => Promise<{ opened: boolean }>;+ clearLegacyImagesDir: () => Promise<{ cleared: boolean }>;+ openChatAttachmentsDir: () => Promise<{ opened: boolean }>;+ clearChatAttachmentsDir: () => Promise<{ cleared: boolean }>;stats: () => Promise<{success: boolean;error?: string;