Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 新增数据库清理并优化大库执行体验 (#3477)
DavidShenXD01e0780dfc71
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 807e7a6245..0f1398b21f 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1532,6 +1532,13 @@ const config: ForgeConfig = {// 不是 Electron preload。target: 'preload',},+ {+ entry: 'src/main/localDb/dbSlimmingMaintenanceProcess.ts',+ config: 'vite.db-slimming-worker.config.ts',+ // DELETE / VACUUM can run for minutes on a large database. An OS-killable+ // utility process keeps Main responsive and lets users cancel before swap.+ target: 'preload',+ },{entry: 'src/main/cindy-brain/libraryDbWorker.ts',config: 'vite.library-db-worker.config.ts',diff --git a/apps/desktop/src/main/__tests__/dbSlimmingIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/dbSlimmingIpcSecurity.test.tsnew file mode 100644index 0000000000..147db33b1e--- /dev/null+++ b/apps/desktop/src/main/__tests__/dbSlimmingIpcSecurity.test.ts@@ -0,0 +1,51 @@+import fs from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++describe('database slimming IPC security wiring', () => {+ it('checks the trusted Renderer boundary before every maintenance action', () => {+ const source = fs.readFileSync(+ path.resolve(__dirname, '..', 'bootstrap-electron.ts'),+ 'utf8',+ );+ const channels = [+ 'scan',+ 'choose-backup-directory',+ 'schedule',+ 'last-result',+ 'open-last-backup-directory',+ ];++ for (const channel of channels) {+ const start = source.indexOf(`ipcMain.handle('local-db:maintenance:${channel}'`);+ const next = source.indexOf('\n ipcMain.handle(', start + 1);+ const block = source.slice(start, next === -1 ? start + 500 : next);+ const guard = block.indexOf('assertTrustedAppRendererEvent(event);');+ const sanitizer = block.indexOf('invokeLocalDbMaintenanceIpc(');+ const action = block.indexOf('localDbMaintenanceHandlers.');++ expect(start, channel).toBeGreaterThanOrEqual(0);+ expect(guard, channel).toBeGreaterThanOrEqual(0);+ expect(sanitizer, channel).toBeGreaterThan(guard);+ expect(action, channel).toBeGreaterThan(guard);+ expect(action, channel).toBeGreaterThan(sanitizer);+ }+ });++ it('keeps unexpected maintenance details in Main and requires native no-backup consent', () => {+ const source = fs.readFileSync(+ path.resolve(__dirname, '..', 'bootstrap-electron.ts'),+ 'utf8',+ );+ const sanitizerStart = source.indexOf('const invokeLocalDbMaintenanceIpc');+ const firstHandler = source.indexOf("ipcMain.handle('local-db:maintenance:scan'", sanitizerStart);+ const sanitizer = source.slice(sanitizerStart, firstHandler);++ expect(sanitizerStart).toBeGreaterThanOrEqual(0);+ expect(sanitizer).toContain('if (isIpcError(error)) throw error;');+ expect(sanitizer).toContain("throwIpcError('INTERNAL', 'database maintenance request failed')");+ expect(source).toContain('confirmWithoutBackup: async () =>');+ expect(source).toContain('await dialog.showMessageBox');+ });+});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 00d7db5f5e..b61b829e86 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -311,10 +311,24 @@ import {getRawDb as localDbGetRawDb,closeDb as localDbCloseDb,getCurrentDbPath as localDbGetCurrentDbPath,+ getDbPathForUser,} from './localDb/index';import { createDbClient, createInprocDbClient } from './localDb/client/DbClient';import { createLifecycleDbClientManager } from './localDb/client/lifecycleDbClient';-import { clearCurrentDbClient, getDbClient, setCurrentDbClient } from './localDb/client/current';+import {+ clearCurrentDbClient,+ getCurrentDbClientUserId,+ getDbClient,+ setCurrentDbClient,+} from './localDb/client/current';+import { createLocalDbMaintenanceIpcHandlers } from './localDb/ipc/maintenance';+import { writeDbSlimmingDevRelaunchSignal } from './localDb/devDbSlimmingRelaunch';+import {+ cancelDbSlimmingStartupProgress,+ getDbSlimmingStartupProgress,+ subscribeDbSlimmingStartupProgress,+} from './localDb/dbSlimmingStartupState';+import { DB_SLIMMING_STARTUP_PROGRESS_CHANGED_CHANNEL } from '../shared/localDbMaintenance';import {resolveBetterSqliteModuleEntry,resolveBetterSqliteNativeBinding,@@ -7383,6 +7397,140 @@ const registerIpcHandlers = () => {return { cleared: true };}),);++ const localDbMaintenanceHandlers = createLocalDbMaintenanceIpcHandlers({+ captureOwner: () => {+ const ownerId = getActiveAppSession().dataOwnerId;+ if (!ownerId || isAppSessionBoundaryPending()) return null;+ return { ownerId, scopeKey: activeOwnerScopeKey() };+ },+ isOwnerCurrent: ({ ownerId, scopeKey }) =>+ !isAppSessionBoundaryPending() &&+ getActiveAppSession().dataOwnerId === ownerId &&+ activeOwnerScopeKey() === scopeKey,+ getDbClient,+ getDbClientOwnerId: getCurrentDbClientUserId,+ getCurrentDbPath: () => {+ const ownerId = getActiveAppSession().dataOwnerId;+ return ownerId ? getDbPathForUser(ownerId) : null;+ },+ getUserDataDir: () => app.getPath('userData'),+ canSchedule: () => process.env.XDT_PASSIVE_SHARED_USER_DATA !== '1',+ selectBackupDirectory: async () => {+ const options = {+ title: t('settings.about.storage.dbSlimmingBackupDirectoryDialogTitle'),+ properties: ['openDirectory', 'createDirectory'] as Array<+ 'openDirectory' | 'createDirectory'+ >,+ };+ const ownerWindow = BrowserWindow.getFocusedWindow() ?? mainWindowRef;+ const result = ownerWindow && !ownerWindow.isDestroyed()+ ? await dialog.showOpenDialog(ownerWindow, options)+ : await dialog.showOpenDialog(options);+ return result.canceled ? null : result.filePaths[0] ?? null;+ },+ confirmWithoutBackup: async () => {+ const options: Electron.MessageBoxOptions = {+ type: 'warning',+ title: t('settings.about.storage.dbSlimmingConfirmTitle'),+ message: t('settings.about.storage.dbSlimmingConfirmTitle'),+ detail: t('settings.about.storage.dbSlimmingConfirmDescriptionWithoutBackup'),+ buttons: [+ t('settings.about.storage.dbSlimmingRestartButton'),+ t('settings.about.storage.cancelButton'),+ ],+ defaultId: 1,+ cancelId: 1,+ noLink: true,+ };+ const ownerWindow = BrowserWindow.getFocusedWindow() ?? mainWindowRef;+ const result = ownerWindow && !ownerWindow.isDestroyed()+ ? await dialog.showMessageBox(ownerWindow, options)+ : await dialog.showMessageBox(options);+ return result.response === 0;+ },+ revealFile: async (filePath) => {+ try {+ if (!(await fs.promises.stat(filePath)).isFile()) return false;+ } catch {+ return false;+ }+ shell.showItemInFolder(path.normalize(filePath));+ return true;+ },+ relaunch: (requestId) => {+ dbClientLog.info('database slimming relaunch requested');+ if (app.isPackaged) {+ app.relaunch();+ } else {+ // Forge owns the Vite server. A bare app.relaunch() outlives Forge,+ // then opens a white window against a dead localhost renderer. The+ // repository dev runner observes the durable cleanup marker and+ // restarts the full Forge/Vite stack after this process exits.+ const delegated = writeDbSlimmingDevRelaunchSignal(requestId);+ dbClientLog.info('database slimming dev relaunch delegated to desktop dev runner', {+ delegated,+ });+ }+ app.quit();+ },+ });+ const invokeLocalDbMaintenanceIpc = async <T>(+ action: string,+ operation: () => T | Promise<T>,+ ): Promise<T> => {+ try {+ return await operation();+ } catch (error) {+ if (isIpcError(error)) throw error;+ dbClientLog.error('database slimming IPC failed', {+ action,+ error: error instanceof Error ? error.message : String(error),+ });+ throwIpcError('INTERNAL', 'database maintenance request failed');+ }+ };+ ipcMain.handle('local-db:maintenance:scan', (event, input) => {+ assertTrustedAppRendererEvent(event);+ return invokeLocalDbMaintenanceIpc('scan', () => localDbMaintenanceHandlers.scan(input));+ });+ ipcMain.handle('local-db:maintenance:choose-backup-directory', (event) => {+ assertTrustedAppRendererEvent(event);+ return invokeLocalDbMaintenanceIpc('choose-backup-directory', () =>+ localDbMaintenanceHandlers.chooseBackupDirectory(),+ );+ });+ ipcMain.handle('local-db:maintenance:schedule', (event, input) => {+ assertTrustedAppRendererEvent(event);+ return invokeLocalDbMaintenanceIpc('schedule', () =>+ localDbMaintenanceHandlers.schedule(input),+ );+ });+ ipcMain.handle('local-db:maintenance:last-result', (event) => {+ assertTrustedAppRendererEvent(event);+ return invokeLocalDbMaintenanceIpc('last-result', () =>+ localDbMaintenanceHandlers.getLastResult(),+ );+ });+ ipcMain.handle('local-db:maintenance:open-last-backup-directory', (event) => {+ assertTrustedAppRendererEvent(event);+ return invokeLocalDbMaintenanceIpc('open-last-backup-directory', () =>+ localDbMaintenanceHandlers.openLastBackupDirectory(),+ );+ });+ ipcMain.handle('local-db:maintenance:startup-progress', (event) => {+ assertTrustedAppRendererEvent(event);+ return getDbSlimmingStartupProgress();+ });+ ipcMain.handle('local-db:maintenance:cancel-startup', (event) => {+ assertTrustedAppRendererEvent(event);+ return { cancelled: cancelDbSlimmingStartupProgress() };+ });+ subscribeDbSlimmingStartupProgress((progress) => {+ const target = mainWindowRef;+ if (!target || target.isDestroyed() || target.webContents.isDestroyed()) return;+ target.webContents.send(DB_SLIMMING_STARTUP_PROGRESS_CHANGED_CHANNEL, progress);+ });}// F5: SDK send-time temporary base64 read (renderer-initiated; main-initiateddiff --git a/apps/desktop/src/main/localDb/__tests__/backup.test.ts b/apps/desktop/src/main/localDb/__tests__/backup.test.tsindex 6ca3591089..35036d055a 100644--- a/apps/desktop/src/main/localDb/__tests__/backup.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/backup.test.ts@@ -20,6 +20,7 @@ import {isoBackupTotalBudgetBytes,listIsoBackups,pruneIsoBackupsToBudget,+ tryRestoreWithFallback,} from '../backup';const GB = 1024 ** 3;@@ -117,6 +118,21 @@ describe('pruneIsoBackupsToBudget', () => {});expect(fs.existsSync(clean)).toBe(true);});++ it('不识别或清理数据库瘦身备份', () => {+ const slimming = `${dbFilePath}.slimming-backup`;+ fs.writeFileSync(slimming, 'slimming');+ makeBackup('2026-07-01T00-00-00-000Z', 100);++ expect(listIsoBackups(dbFilePath)).toHaveLength(1);+ pruneIsoBackupsToBudget(dbFilePath, {+ maxCount: 0,+ maxTotalBytes: 0,+ keepNewest: false,+ });++ expect(fs.readFileSync(slimming, 'utf8')).toBe('slimming');+ });});describe('isoBackupTotalBudgetBytes', () => {@@ -128,6 +144,15 @@ describe('isoBackupTotalBudgetBytes', () => {});});+describe('tryRestoreWithFallback', () => {+ it('自动损坏恢复不会读取数据库瘦身备份', () => {+ fs.writeFileSync(`${dbFilePath}.slimming-backup`, 'not an automatic recovery source');++ expect(tryRestoreWithFallback(dbFilePath)).toBeNull();+ expect(fs.existsSync(dbFilePath)).toBe(false);+ });+});+describe('cleanupFailedBackupArtifacts', () => {it('本体 + -journal/-wal/-shm 残留一并删除', () => {const backupPath = `${dbFilePath}.bak.2026-07-06T00-00-00-000Z`;diff --git a/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts b/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.tsnew file mode 100644index 0000000000..0fc0c8ad07--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts@@ -0,0 +1,898 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createBetterSqliteDatabase } from '../betterSqliteFactory';+import {+ discardCancelledDbSlimmingMaintenance,+ estimateDbFilesBytes,+ runDbSlimmingMaintenance,+} from '../dbSlimmingMaintenance';+import {+ adoptDbSlimmingBackup,+ dbSlimmingRequestPath,+ readDbSlimmingRequest,+ type DbSlimmingRequestRecord,+ writeDbSlimmingRequest,+ writeDbSlimmingResult,+} from '../maintenanceStore';++const REQUEST_ID = '9c5c7e99-6a6a-4d21-9152-4034a4959490';++let tmpDir: string;+let dbFilePath: string;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-db-slimming-'));+ dbFilePath = path.join(tmpDir, 'cindy-owner.db');+});++afterEach(() => {+ vi.restoreAllMocks();+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++function request(overrides: Partial<DbSlimmingRequestRecord> = {}): DbSlimmingRequestRecord {+ return {+ version: 1,+ id: REQUEST_ID,+ ownerId: 'owner-1',+ createdAt: 2_000,+ scannedAt: 2_000,+ archivedBeforeMs: 1_000,+ archiveAgeMonths: 3,+ deletedTaskCount: 0,+ archivedTaskCount: 0,+ messageCount: 0,+ beforeBytes: fs.existsSync(dbFilePath) ? estimateDbFilesBytes(dbFilePath) : 0,+ backupEnabled: false,+ phase: 'scheduled',+ ...overrides,+ };+}++const log = {+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+};++function createCleanupFixture(): void {+ const db = createBetterSqliteDatabase(dbFilePath);+ db.pragma('foreign_keys = ON');+ db.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ status TEXT NOT NULL,+ updated_at INTEGER NOT NULL,+ total_token_usage INTEGER NOT NULL DEFAULT 0,+ total_cost_usd REAL NOT NULL DEFAULT 0,+ sdk_session_id TEXT,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER,+ context_tokens INTEGER NOT NULL DEFAULT 0,+ context_window INTEGER NOT NULL DEFAULT 0,+ cleared_at INTEGER,+ summary TEXT,+ codex_plan_json TEXT,+ codex_history_has_product_prompt INTEGER,+ active_turn_started_at INTEGER,+ last_turn_ended_at INTEGER+ );+ CREATE TABLE messages (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ content TEXT NOT NULL+ );+ CREATE VIRTUAL TABLE messages_fts USING fts5(+ message_id UNINDEXED,+ session_id UNINDEXED,+ role UNINDEXED,+ content+ );+ CREATE TABLE messages_fts_rows (+ fts_rowid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ message_id TEXT NOT NULL+ );+ CREATE UNIQUE INDEX messages_fts_rows_message_id_idx ON messages_fts_rows(message_id);+ CREATE TABLE messages_fts_delete_audit (message_id TEXT NOT NULL);+ CREATE TRIGGER messages_fts_delete AFTER DELETE ON messages BEGIN+ INSERT INTO messages_fts_delete_audit (message_id) VALUES (old.id);+ DELETE FROM messages_fts+ WHERE rowid = (+ SELECT fts_rowid FROM messages_fts_rows WHERE message_id = old.id+ );+ DELETE FROM messages_fts_rows WHERE message_id = old.id;+ END;+ CREATE TABLE subagent_runs (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE+ );+ CREATE TABLE subagent_run_aliases (+ run_id TEXT NOT NULL REFERENCES subagent_runs(id) ON DELETE CASCADE,+ alias TEXT NOT NULL,+ PRIMARY KEY (run_id, alias)+ );+ CREATE TABLE session_pr_refs (id TEXT PRIMARY KEY, session_id TEXT NOT NULL);+ CREATE TABLE session_goals (session_id TEXT PRIMARY KEY);+ CREATE TABLE agent_input_queue_snapshots (session_id TEXT PRIMARY KEY, payload TEXT NOT NULL);+ CREATE TABLE ghost_cards (call_id TEXT PRIMARY KEY, session_id TEXT, html TEXT NOT NULL);+ CREATE TABLE skill_usage_sources (+ raw_file_path TEXT PRIMARY KEY,+ session_id TEXT NOT NULL+ );+ CREATE TABLE skill_usage_exposures (+ id TEXT PRIMARY KEY,+ raw_file_path TEXT NOT NULL REFERENCES skill_usage_sources(raw_file_path) ON DELETE CASCADE+ );+ CREATE TABLE media_refs (id TEXT PRIMARY KEY, origin_session_id TEXT, label TEXT);+ `);+ const insertSession = db.prepare(`+ INSERT INTO sessions (+ id, title, status, updated_at, total_token_usage, total_cost_usd,+ sdk_session_id, list_preview, list_preview_role, list_message_count,+ context_tokens, context_window, summary, codex_plan_json,+ codex_history_has_product_prompt, active_turn_started_at, last_turn_ended_at+ ) VALUES (+ ?, ?, ?, ?, 7, 1.5, 'native-id', 'stale preview', 'assistant', 1,+ 100, 200, 'summary', '{}', 1, 10, 20+ )+ `);+ for (const [id, status, updatedAt] of [+ ['deleted-old', 'deleted', 500],+ ['deleted-new', 'deleted', 2_500],+ ['archived-boundary', 'archived', 1_000],+ ['archived-new', 'archived', 1_001],+ ['active-old', 'active', 100],+ ] as const) {+ insertSession.run(id, `title-${id}`, status, updatedAt);+ db.prepare('INSERT INTO messages (id, session_id, content) VALUES (?, ?, ?)').run(+ `message-${id}`,+ id,+ 'x'.repeat(32 * 1024),+ );+ const ftsRowid = Number(+ db+ .prepare('INSERT INTO messages_fts_rows (message_id) VALUES (?)')+ .run(`message-${id}`).lastInsertRowid,+ );+ db.prepare(+ 'INSERT INTO messages_fts (rowid, message_id, session_id, role, content) VALUES (?, ?, ?, ?, ?)',+ ).run(+ ftsRowid,+ `message-${id}`,+ id,+ 'user',+ `content-${id}`,+ );+ }+ insertSession.run('archived-empty', 'title-archived-empty', 'archived', 500);+ for (const sessionId of ['deleted-old', 'archived-boundary']) {+ db.prepare('INSERT INTO subagent_runs (id, session_id) VALUES (?, ?)').run(+ `run-${sessionId}`,+ sessionId,+ );+ db.prepare('INSERT INTO subagent_run_aliases (run_id, alias) VALUES (?, ?)').run(+ `run-${sessionId}`,+ 'alias',+ );+ db.prepare('INSERT INTO session_pr_refs (id, session_id) VALUES (?, ?)').run(+ `pr-${sessionId}`,+ sessionId,+ );+ db.prepare('INSERT INTO session_goals (session_id) VALUES (?)').run(sessionId);+ db.prepare('INSERT INTO agent_input_queue_snapshots (session_id, payload) VALUES (?, ?)').run(+ sessionId,+ '[]',+ );+ db.prepare('INSERT INTO ghost_cards (call_id, session_id, html) VALUES (?, ?, ?)').run(+ `card-${sessionId}`,+ sessionId,+ '<p>history</p>',+ );+ db.prepare('INSERT INTO skill_usage_sources (raw_file_path, session_id) VALUES (?, ?)').run(+ `source-${sessionId}`,+ sessionId,+ );+ db.prepare('INSERT INTO skill_usage_exposures (id, raw_file_path) VALUES (?, ?)').run(+ `exposure-${sessionId}`,+ `source-${sessionId}`,+ );+ db.prepare('INSERT INTO media_refs (id, origin_session_id, label) VALUES (?, ?, ?)').run(+ `media-${sessionId}`,+ sessionId,+ 'keep the external-file ownership ledger intact',+ );+ }+ db.pragma('journal_mode = WAL');+ db.close();+}++function createLegacyCleanupFixture(): void {+ const db = createBetterSqliteDatabase(dbFilePath);+ db.pragma('foreign_keys = ON');+ db.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ status TEXT NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE TABLE messages (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ content TEXT NOT NULL+ );+ INSERT INTO sessions (id, status, updated_at) VALUES ('archived-old', 'archived', 500);+ INSERT INTO messages (id, session_id, content) VALUES ('message-old', 'archived-old', 'old');+ `);+ db.close();+}++function createMarkerDatabase(filePath: string, marker: string): void {+ const db = createBetterSqliteDatabase(filePath);+ db.exec('CREATE TABLE marker (value TEXT NOT NULL)');+ db.prepare('INSERT INTO marker (value) VALUES (?)').run(marker);+ db.close();+}++function readMarker(filePath: string): string {+ const db = createBetterSqliteDatabase(filePath, { readonly: true, fileMustExist: true });+ try {+ return (db.prepare('SELECT value FROM marker').get() as { value: string }).value;+ } finally {+ db.close();+ }+}++describe('runDbSlimmingMaintenance', () => {+ it('cleans only messages and their derived indexes in the frozen inactive-task scope', async () => {+ createCleanupFixture();+ const beforeBytes = estimateDbFilesBytes(dbFilePath);+ const onProgress = vi.fn();+ const beforeReplacement = vi.fn(async () => {});++ const outcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: request({ beforeBytes }),+ now: () => 3_000,+ log,+ onProgress,+ beforeReplacement,+ });++ expect(outcome.originalDatabaseReady).toBe(true);+ expect(outcome.result).toMatchObject({+ status: 'completed',+ deletedTaskCount: 1,+ archivedTaskCount: 1,+ messageCount: 2,+ backupCreated: false,+ });+ expect(onProgress).toHaveBeenCalledWith(+ expect.objectContaining({ phase: 'copying', cancellable: true }),+ );+ expect(onProgress).not.toHaveBeenCalledWith(+ expect.objectContaining({ phase: 'backing-up' }),+ );+ expect(onProgress).toHaveBeenCalledWith({+ phase: 'finalizing',+ progress: 96,+ cancellable: false,+ });+ expect(beforeReplacement).toHaveBeenCalledTimes(1);+ const db = createBetterSqliteDatabase(dbFilePath, { fileMustExist: true });+ try {+ expect(+ db.prepare('SELECT id FROM messages ORDER BY id').all().map((row) => (row as { id: string }).id),+ ).toEqual([+ 'message-active-old',+ 'message-archived-new',+ 'message-deleted-new',+ ]);+ expect(db.prepare('SELECT count(*) AS count FROM messages_fts').get()).toEqual({ count: 3 });+ expect(+ db.prepare('SELECT message_id FROM messages_fts_rows ORDER BY message_id').all(),+ ).toEqual([+ { message_id: 'message-active-old' },+ { message_id: 'message-archived-new' },+ { message_id: 'message-deleted-new' },+ ]);+ expect(db.prepare('SELECT count(*) AS count FROM messages_fts_delete_audit').get()).toEqual({+ count: 0,+ });+ db.prepare("DELETE FROM messages WHERE id = 'message-active-old'").run();+ expect(db.prepare('SELECT message_id FROM messages_fts_delete_audit').all()).toEqual([+ { message_id: 'message-active-old' },+ ]);+ expect(+ db.prepare('SELECT message_id FROM messages_fts_rows ORDER BY message_id').all(),+ ).toEqual([+ { message_id: 'message-archived-new' },+ { message_id: 'message-deleted-new' },+ ]);+ expect(db.prepare('SELECT count(*) AS count FROM subagent_runs').get()).toEqual({ count: 2 });+ expect(db.prepare('SELECT count(*) AS count FROM subagent_run_aliases').get()).toEqual({ count: 2 });+ expect(db.prepare('SELECT count(*) AS count FROM session_pr_refs').get()).toEqual({ count: 2 });+ expect(db.prepare('SELECT count(*) AS count FROM session_goals').get()).toEqual({ count: 2 });+ expect(db.prepare('SELECT count(*) AS count FROM agent_input_queue_snapshots').get()).toEqual({ count: 2 });+ expect(db.prepare('SELECT count(*) AS count FROM ghost_cards').get()).toEqual({ count: 2 });+ expect(db.prepare('SELECT count(*) AS count FROM skill_usage_sources').get()).toEqual({ count: 2 });+ expect(db.prepare('SELECT count(*) AS count FROM skill_usage_exposures').get()).toEqual({ count: 2 });+ expect(db.prepare('SELECT count(*) AS count FROM media_refs').get()).toEqual({ count: 2 });+ expect(+ db.prepare(`+ SELECT title, status, updated_at, total_token_usage, total_cost_usd,+ sdk_session_id, list_preview, list_preview_role, list_message_count,+ context_tokens, context_window, cleared_at,+ summary, codex_plan_json, codex_history_has_product_prompt,+ active_turn_started_at, last_turn_ended_at+ FROM sessions WHERE id = 'archived-boundary'+ `).get(),+ ).toEqual({+ title: 'title-archived-boundary',+ status: 'archived',+ updated_at: 1_000,+ total_token_usage: 7,+ total_cost_usd: 1.5,+ sdk_session_id: 'native-id',+ list_preview: null,+ list_preview_role: null,+ list_message_count: null,+ context_tokens: 100,+ context_window: 200,+ cleared_at: null,+ summary: 'summary',+ codex_plan_json: '{}',+ codex_history_has_product_prompt: 1,+ active_turn_started_at: 10,+ last_turn_ended_at: 20,+ });+ expect(+ db.prepare(`+ SELECT list_preview, list_preview_role, list_message_count+ FROM sessions WHERE id = 'active-old'+ `).get(),+ ).toEqual({+ list_preview: 'stale preview',+ list_preview_role: 'assistant',+ list_message_count: 1,+ });+ } finally {+ db.close();+ }+ });++ it('cleans a pre-0097 database before list projection columns are migrated', async () => {+ createLegacyCleanupFixture();+ const beforeBytes = estimateDbFilesBytes(dbFilePath);++ const outcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: request({ beforeBytes }),+ now: () => 3_000,+ log,+ });++ expect(outcome.result).toMatchObject({+ status: 'completed',+ archivedTaskCount: 1,+ messageCount: 1,+ });+ const db = createBetterSqliteDatabase(dbFilePath, { fileMustExist: true });+ try {+ expect(db.prepare('SELECT count(*) AS count FROM messages').get()).toEqual({ count: 0 });+ expect(+ (db.prepare("PRAGMA table_info('sessions')").all() as Array<{ name: string }>).map(+ (column) => column.name,+ ),+ ).not.toContain('list_preview');+ } finally {+ db.close();+ }+ });++ it('keeps the untouched original as the latest default-directory slimming backup', async () => {+ createCleanupFixture();+ const beforeBytes = estimateDbFilesBytes(dbFilePath);++ const outcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: request({ beforeBytes, backupEnabled: true }),+ now: () => 3_000,+ log,+ });++ expect(outcome.result).toMatchObject({+ status: 'completed',+ backupCreated: true,+ backupLocation: 'database-directory',+ });+ const backupPath = `${dbFilePath}.slimming-backup`;+ const backup = createBetterSqliteDatabase(backupPath, {+ readonly: true,+ fileMustExist: true,+ });+ try {+ expect(backup.prepare('SELECT count(*) AS count FROM messages').get()).toEqual({ count: 5 });+ } finally {+ backup.close();+ }+ expect(fs.existsSync(`${backupPath}.${REQUEST_ID}.previous`)).toBe(false);+ });++ it('rolls back a failed installed replacement exactly once', async () => {+ const backupPath = `${dbFilePath}.slimming-backup`;+ const previousPath = `${backupPath}.${REQUEST_ID}.previous`;+ createMarkerDatabase(backupPath, 'original');+ createMarkerDatabase(previousPath, 'older-slimming-backup');+ fs.writeFileSync(dbFilePath, 'not a sqlite database');++ const outcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: request({+ phase: 'replacement-installed',+ backupEnabled: true,+ beforeBytes: fs.statSync(dbFilePath).size,+ }),+ now: () => 3_000,+ log,+ });++ expect(outcome.result).toMatchObject({+ status: 'failed',+ reason: 'integrity-check-failed',+ originalDatabaseRestored: true,+ });+ expect(readMarker(dbFilePath)).toBe('original');+ expect(readMarker(backupPath)).toBe('older-slimming-backup');+ });++ it('does not reapply an older backup after rollback completes but marker cleanup fails', async () => {+ const backupPath = `${dbFilePath}.slimming-backup`;+ const previousPath = `${backupPath}.${REQUEST_ID}.previous`;+ createMarkerDatabase(backupPath, 'original');+ createMarkerDatabase(previousPath, 'older-slimming-backup');+ fs.writeFileSync(dbFilePath, 'not a sqlite database');+ const pending = request({+ phase: 'replacement-installed',+ backupEnabled: true,+ beforeBytes: fs.statSync(dbFilePath).size,+ });+ writeDbSlimmingRequest(tmpDir, pending);++ const requestPath = dbSlimmingRequestPath(tmpDir);+ const originalRmSync = fs.rmSync.bind(fs);+ const rmSpy = vi.spyOn(fs, 'rmSync').mockImplementation((candidate, options) => {+ if ([requestPath, `${requestPath}.bak`].includes(String(candidate))) {+ throw Object.assign(new Error('request marker is busy'), { code: 'EBUSY' });+ }+ return originalRmSync(candidate, options);+ });++ const firstOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: pending,+ now: () => 3_000,+ log,+ });++ expect(firstOutcome.result).toMatchObject({+ status: 'failed',+ reason: 'integrity-check-failed',+ originalDatabaseRestored: true,+ });+ const persisted = readDbSlimmingRequest(tmpDir);+ expect(persisted).toMatchObject({+ phase: 'rollback-completed',+ rollbackFailureReason: 'integrity-check-failed',+ });+ expect(readMarker(dbFilePath)).toBe('original');+ expect(readMarker(backupPath)).toBe('older-slimming-backup');++ rmSpy.mockRestore();+ const secondOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: persisted!,+ now: () => 4_000,+ log,+ });++ expect(secondOutcome.result).toMatchObject({+ status: 'failed',+ reason: 'integrity-check-failed',+ originalDatabaseRestored: true,+ });+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(readMarker(dbFilePath)).toBe('original');+ expect(readMarker(backupPath)).toBe('older-slimming-backup');+ });++ it('fails closed until a completed physical rollback can be persisted', async () => {+ const rollbackPath = `${dbFilePath}.slimming-${REQUEST_ID}.rollback`;+ const workPath = `${dbFilePath}.slimming-${REQUEST_ID}.work`;+ createMarkerDatabase(rollbackPath, 'original');+ fs.writeFileSync(dbFilePath, 'not a sqlite database');+ const pending = request({+ phase: 'replacement-installed',+ beforeBytes: fs.statSync(dbFilePath).size,+ });+ writeDbSlimmingRequest(tmpDir, pending);++ const requestPathPrefix = `${dbSlimmingRequestPath(tmpDir)}.`;+ const originalWriteFileSync = fs.writeFileSync.bind(fs);+ const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation((candidate, data, options) => {+ if (+ String(candidate).startsWith(requestPathPrefix) &&+ String(data).includes('"phase":"rollback-completed"')+ ) {+ throw Object.assign(new Error('rollback marker is unavailable'), { code: 'EACCES' });+ }+ return originalWriteFileSync(candidate, data, options);+ });++ const firstOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: pending,+ now: () => 3_000,+ log,+ });++ expect(firstOutcome).toMatchObject({+ originalDatabaseReady: false,+ result: {+ status: 'failed',+ reason: 'integrity-check-failed',+ originalDatabaseRestored: true,+ },+ });+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({ phase: 'replacement-installed' });+ expect(readMarker(dbFilePath)).toBe('original');+ expect(fs.existsSync(workPath)).toBe(true);++ writeSpy.mockRestore();+ const persisted = readDbSlimmingRequest(tmpDir)!;+ const secondOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: persisted,+ now: () => 4_000,+ log,+ });++ expect(secondOutcome).toMatchObject({+ originalDatabaseReady: true,+ result: {+ status: 'failed',+ reason: 'recovery-failed',+ originalDatabaseRestored: true,+ },+ });+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(readMarker(dbFilePath)).toBe('original');+ expect(fs.existsSync(workPath)).toBe(false);+ });++ it('keeps the rollback marker until occupied maintenance artifacts are removed', async () => {+ const rollbackPath = `${dbFilePath}.slimming-${REQUEST_ID}.rollback`;+ const workPath = `${dbFilePath}.slimming-${REQUEST_ID}.work`;+ createMarkerDatabase(rollbackPath, 'original');+ fs.writeFileSync(dbFilePath, 'not a sqlite database');+ const pending = request({+ phase: 'replacement-installed',+ beforeBytes: fs.statSync(dbFilePath).size,+ });+ writeDbSlimmingRequest(tmpDir, pending);++ const originalRmSync = fs.rmSync.bind(fs);+ const rmSpy = vi.spyOn(fs, 'rmSync').mockImplementation((candidate, options) => {+ if (String(candidate) === workPath) {+ throw Object.assign(new Error('rollback artifact is busy'), { code: 'EBUSY' });+ }+ return originalRmSync(candidate, options);+ });++ const firstOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: pending,+ now: () => 3_000,+ log,+ });++ expect(firstOutcome.result).toMatchObject({+ status: 'failed',+ reason: 'integrity-check-failed',+ originalDatabaseRestored: true,+ });+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({+ phase: 'rollback-completed',+ rollbackFailureReason: 'integrity-check-failed',+ });+ expect(fs.existsSync(workPath)).toBe(true);+ expect(readMarker(dbFilePath)).toBe('original');++ rmSpy.mockRestore();+ const persisted = readDbSlimmingRequest(tmpDir)!;+ const secondOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: persisted,+ now: () => 4_000,+ log,+ });++ expect(secondOutcome.result).toMatchObject({+ status: 'failed',+ reason: 'integrity-check-failed',+ originalDatabaseRestored: true,+ });+ expect(fs.existsSync(workPath)).toBe(false);+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(readMarker(dbFilePath)).toBe('original');+ });++ it('keeps a pre-replacement request until occupied working artifacts are removed', async () => {+ createLegacyCleanupFixture();+ const pending = request({ beforeBytes: estimateDbFilesBytes(dbFilePath) });+ writeDbSlimmingRequest(tmpDir, pending);+ const workPath = `${dbFilePath}.slimming-${REQUEST_ID}.work`;+ const originalRmSync = fs.rmSync.bind(fs);+ const rmSpy = vi.spyOn(fs, 'rmSync').mockImplementation((candidate, options) => {+ if (String(candidate) === workPath) {+ throw Object.assign(new Error('working artifact is busy'), { code: 'EBUSY' });+ }+ return originalRmSync(candidate, options);+ });++ const firstOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: pending,+ now: () => 3_000,+ log,+ beforeReplacement: vi.fn(async () => {+ throw new Error('stop before replacement');+ }),+ });++ expect(firstOutcome.result).toMatchObject({+ status: 'failed',+ reason: 'cleanup-failed',+ originalDatabaseRestored: true,+ });+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({ id: pending.id, phase: 'scheduled' });+ expect(fs.existsSync(workPath)).toBe(true);++ rmSpy.mockRestore();+ const persisted = readDbSlimmingRequest(tmpDir)!;+ const secondOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: persisted,+ now: () => 4_000,+ log,+ });++ expect(secondOutcome.result.status).toBe('completed');+ expect(fs.existsSync(workPath)).toBe(false);+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ });++ it('fails closed when the scheduled source database is missing', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);++ const outcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: pending,+ now: () => 3_000,+ log,+ });++ expect(outcome).toMatchObject({+ originalDatabaseReady: false,+ result: {+ status: 'failed',+ reason: 'recovery-failed',+ originalDatabaseRestored: false,+ },+ });+ expect(fs.existsSync(dbFilePath)).toBe(false);+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({ id: pending.id, phase: 'scheduled' });+ });++ it('fails closed when an installed replacement has lost its original backup', async () => {+ createMarkerDatabase(dbFilePath, 'compacted-replacement');++ const outcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: request({+ phase: 'replacement-installed',+ backupEnabled: true,+ beforeBytes: fs.statSync(dbFilePath).size,+ }),+ now: () => 3_000,+ log,+ });++ expect(outcome).toMatchObject({+ originalDatabaseReady: false,+ result: {+ status: 'failed',+ reason: 'recovery-failed',+ originalDatabaseRestored: false,+ },+ });+ expect(readMarker(dbFilePath)).toBe('compacted-replacement');+ });++ it('rebuilds a missing result after the commit marker is durable', async () => {+ createMarkerDatabase(dbFilePath, 'committed-replacement');++ const outcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: request({+ phase: 'committed',+ beforeBytes: fs.statSync(dbFilePath).size,+ }),+ now: () => 3_000,+ log,+ });++ expect(outcome).toMatchObject({+ originalDatabaseReady: true,+ result: {+ status: 'completed',+ finishedAt: 3_000,+ backupCreated: false,+ },+ });+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(readMarker(dbFilePath)).toBe('committed-replacement');+ });++ it('keeps the rollback when a committed database is invalid despite a completed result', async () => {+ const rollbackPath = `${dbFilePath}.slimming-${REQUEST_ID}.rollback`;+ createMarkerDatabase(rollbackPath, 'original');+ fs.writeFileSync(dbFilePath, 'not a sqlite database');+ const pending = request({+ phase: 'committed',+ beforeBytes: fs.statSync(dbFilePath).size,+ });+ writeDbSlimmingRequest(tmpDir, pending);+ writeDbSlimmingResult(tmpDir, {+ id: pending.id,+ ownerId: pending.ownerId,+ status: 'completed',+ finishedAt: 2_500,+ archiveAgeMonths: pending.archiveAgeMonths,+ deletedTaskCount: 1,+ archivedTaskCount: 1,+ messageCount: 1,+ beforeBytes: pending.beforeBytes,+ afterBytes: pending.beforeBytes,+ reclaimedBytes: 0,+ backupCreated: false,+ });++ const outcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: pending,+ now: () => 3_000,+ log,+ });++ expect(outcome).toMatchObject({+ originalDatabaseReady: false,+ result: {+ status: 'failed',+ reason: 'recovery-failed',+ originalDatabaseRestored: false,+ },+ });+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({ phase: 'committed' });+ expect(readMarker(rollbackPath)).toBe('original');+ });++ it('keeps the committed marker until occupied maintenance artifacts are removed', async () => {+ createMarkerDatabase(dbFilePath, 'committed-replacement');+ const pending = request({+ phase: 'committed',+ beforeBytes: fs.statSync(dbFilePath).size,+ });+ writeDbSlimmingRequest(tmpDir, pending);+ const workPath = `${dbFilePath}.slimming-${REQUEST_ID}.work`;+ fs.writeFileSync(workPath, 'occupied maintenance artifact');++ const originalRmSync = fs.rmSync.bind(fs);+ const rmSpy = vi.spyOn(fs, 'rmSync').mockImplementation((candidate, options) => {+ if (String(candidate) === workPath) {+ throw Object.assign(new Error('maintenance artifact is busy'), { code: 'EBUSY' });+ }+ return originalRmSync(candidate, options);+ });++ const firstOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: pending,+ now: () => 3_000,+ log,+ });++ expect(firstOutcome.result.status).toBe('completed');+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({ phase: 'committed' });+ expect(fs.existsSync(workPath)).toBe(true);++ rmSpy.mockRestore();+ const persisted = readDbSlimmingRequest(tmpDir)!;+ const secondOutcome = await runDbSlimmingMaintenance({+ userDataDir: tmpDir,+ dbFilePath,+ request: persisted,+ now: () => 4_000,+ log,+ });++ expect(secondOutcome.result.status).toBe('completed');+ expect(fs.existsSync(workPath)).toBe(false);+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ });+});++describe('discardCancelledDbSlimmingMaintenance', () => {+ it('does not complete cancellation while the request marker is occupied', () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const requestPath = dbSlimmingRequestPath(tmpDir);+ const originalRmSync = fs.rmSync.bind(fs);+ vi.spyOn(fs, 'rmSync').mockImplementation((candidate, options) => {+ if (String(candidate) === requestPath) {+ throw Object.assign(new Error('request marker is busy'), { code: 'EBUSY' });+ }+ return originalRmSync(candidate, options);+ });++ expect(() => discardCancelledDbSlimmingMaintenance(tmpDir, dbFilePath, pending)).toThrow(+ 'database slimming request marker could not be cleared',+ );+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({ id: pending.id, phase: 'scheduled' });+ });+});++describe('adoptDbSlimmingBackup', () => {+ it('keeps only the latest slimming backup even when the user changes folders', () => {+ const firstDir = path.join(tmpDir, 'first');+ const secondDir = path.join(tmpDir, 'second');+ fs.mkdirSync(firstDir);+ fs.mkdirSync(secondDir);+ const first = path.join(firstDir, 'cindy-owner.db.slimming-backup');+ const second = path.join(secondDir, 'cindy-owner.db.slimming-backup');+ const migrationBackup = path.join(firstDir, 'cindy-owner.db.bak.2026-08-26T00-00-00-000Z');+ fs.writeFileSync(first, 'first');+ fs.writeFileSync(second, 'second');+ fs.writeFileSync(migrationBackup, 'migration');++ adoptDbSlimmingBackup(tmpDir, 'owner-1', first);+ adoptDbSlimmingBackup(tmpDir, 'owner-1', second);++ expect(fs.existsSync(first)).toBe(false);+ expect(fs.readFileSync(second, 'utf8')).toBe('second');+ expect(fs.readFileSync(migrationBackup, 'utf8')).toBe('migration');+ });+});diff --git a/apps/desktop/src/main/localDb/__tests__/dbSlimmingStartup.test.ts b/apps/desktop/src/main/localDb/__tests__/dbSlimmingStartup.test.tsnew file mode 100644index 0000000000..628a7616cf--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/dbSlimmingStartup.test.ts@@ -0,0 +1,494 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { runPendingDbSlimmingAtStartup } from '../dbSlimmingStartup';+import {+ DbSlimmingCancelledError,+ DbSlimmingWorkerPreReplacementError,+ DbSlimmingWorkerStartupError,+} from '../dbSlimmingWorkerClient';+import {+ cancelDbSlimmingStartupProgress,+ getDbSlimmingStartupProgress,+} from '../dbSlimmingStartupState';+import {+ readDbSlimmingRequest,+ readDbSlimmingResult,+ type DbSlimmingRequestRecord,+ writeDbSlimmingRequest,+} from '../maintenanceStore';++const REQUEST_ID = '9c5c7e99-6a6a-4d21-9152-4034a4959490';++let tmpDir: string;+let dbFilePath: string;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-db-slimming-startup-'));+ dbFilePath = path.join(tmpDir, 'cindy-owner.db');+});++afterEach(() => {+ vi.restoreAllMocks();+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++function request(overrides: Partial<DbSlimmingRequestRecord> = {}): DbSlimmingRequestRecord {+ return {+ version: 1,+ id: REQUEST_ID,+ ownerId: 'owner-1',+ createdAt: 2_000,+ scannedAt: 2_000,+ archivedBeforeMs: 1_000,+ archiveAgeMonths: 3,+ deletedTaskCount: 1,+ archivedTaskCount: 2,+ messageCount: 3,+ beforeBytes: 4_096,+ backupEnabled: true,+ phase: 'scheduled',+ ...overrides,+ };+}++const log = {+ info: vi.fn(),+ error: vi.fn(),+ warn: vi.fn(),+};++describe('runPendingDbSlimmingAtStartup', () => {+ it('discards a marker only when its JSON is confirmed invalid', async () => {+ fs.writeFileSync(path.join(tmpDir, 'db-slimming-request.json'), '{invalid', 'utf8');++ await expect(+ runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: 'owner-1',+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ }),+ ).resolves.toEqual({ handled: false, originalDatabaseReady: true });++ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ });++ it('preserves the marker and fails closed when the marker cannot be read', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const readError = Object.assign(new Error('marker is temporarily locked'), { code: 'EACCES' });++ await expect(+ runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ readRequest: () => {+ throw readError;+ },+ }),+ ).rejects.toBe(readError);++ expect(readDbSlimmingRequest(tmpDir)).toEqual(pending);+ });++ it('leaves another owner request untouched and never opens that owner database', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const runMaintenance = vi.fn();++ const outcome = await runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath: path.join(tmpDir, 'cindy-owner-2.db'),+ ownerId: 'owner-2',+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ runMaintenance,+ });++ expect(outcome).toEqual({ handled: false, originalDatabaseReady: true });+ expect(runMaintenance).not.toHaveBeenCalled();+ expect(readDbSlimmingRequest(tmpDir)).toEqual(pending);+ });++ it('runs the pending request only while holding the writer lease', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const completed = {+ id: pending.id,+ ownerId: pending.ownerId,+ status: 'completed' as const,+ finishedAt: 3_000,+ archiveAgeMonths: 3 as const,+ deletedTaskCount: 1,+ archivedTaskCount: 2,+ messageCount: 3,+ beforeBytes: 4_096,+ afterBytes: 2_048,+ reclaimedBytes: 2_048,+ backupCreated: true,+ backupLocation: 'database-directory' as const,+ backupPath: `${dbFilePath}.slimming-backup`,+ };+ const runMaintenance = vi.fn(async () => ({+ result: completed,+ originalDatabaseReady: true,+ }));++ const outcome = await runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ runMaintenance,+ });++ expect(runMaintenance).toHaveBeenCalledWith(+ expect.objectContaining({+ userDataDir: tmpDir,+ dbFilePath,+ request: pending,+ }),+ );+ expect(outcome).toEqual({+ handled: true,+ result: completed,+ originalDatabaseReady: true,+ });+ });++ it('records database-in-use without running maintenance for a reader lease', async () => {+ writeDbSlimmingRequest(tmpDir, request());+ const runMaintenance = vi.fn();++ const outcome = await runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: 'owner-1',+ leaseKind: 'reader',+ loadVectorExtension: vi.fn(() => true),+ log,+ now: () => 3_000,+ runMaintenance,+ });++ expect(runMaintenance).not.toHaveBeenCalled();+ expect(outcome).toMatchObject({+ handled: true,+ originalDatabaseReady: true,+ result: {+ status: 'failed',+ reason: 'database-in-use',+ originalDatabaseRestored: true,+ },+ });+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(readDbSlimmingResult(tmpDir)).toMatchObject({+ ownerId: 'owner-1',+ status: 'failed',+ reason: 'database-in-use',+ });+ });++ it('does not consume a reader-lease request while its marker is occupied', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const requestPath = path.join(tmpDir, 'db-slimming-request.json');+ const originalRmSync = fs.rmSync.bind(fs);+ vi.spyOn(fs, 'rmSync').mockImplementation((candidate, options) => {+ if (String(candidate) === requestPath) {+ throw Object.assign(new Error('request marker is busy'), { code: 'EBUSY' });+ }+ return originalRmSync(candidate, options);+ });+ const runMaintenance = vi.fn();++ await expect(+ runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'reader',+ loadVectorExtension: vi.fn(() => true),+ log,+ runMaintenance,+ }),+ ).rejects.toThrow('database slimming request marker could not be cleared');++ expect(runMaintenance).not.toHaveBeenCalled();+ expect(readDbSlimmingRequest(tmpDir)).toEqual(pending);+ expect(readDbSlimmingResult(tmpDir)).toMatchObject({+ id: pending.id,+ status: 'failed',+ reason: 'database-in-use',+ });+ });++ it('keeps the request scheduled when the reader in-use result cannot be persisted', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const resultPathPrefix = `${path.join(tmpDir, 'db-slimming-result.json')}.`;+ const originalWriteFileSync = fs.writeFileSync.bind(fs);+ vi.spyOn(fs, 'writeFileSync').mockImplementation((candidate, data, options) => {+ if (String(candidate).startsWith(resultPathPrefix)) {+ throw Object.assign(new Error('result marker is unavailable'), { code: 'EACCES' });+ }+ return originalWriteFileSync(candidate, data, options);+ });+ const runMaintenance = vi.fn();++ const outcome = await runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'reader',+ loadVectorExtension: vi.fn(() => true),+ log,+ runMaintenance,+ });++ expect(runMaintenance).not.toHaveBeenCalled();+ expect(outcome).toMatchObject({+ handled: true,+ originalDatabaseReady: true,+ result: { status: 'failed', reason: 'database-in-use' },+ });+ expect(readDbSlimmingRequest(tmpDir)).toEqual(pending);+ expect(readDbSlimmingResult(tmpDir)).toBeNull();+ });++ it.each([+ ['swap-prepared', undefined],+ ['replacement-installed', undefined],+ ['rollback-completed', 'replacement-failed'],+ ['committed', undefined],+ ] as const)('preserves a %s recovery marker when only a reader lease is available', async (+ phase,+ rollbackFailureReason,+ ) => {+ const pending = request({+ phase,+ ...(rollbackFailureReason ? { rollbackFailureReason } : {}),+ });+ writeDbSlimmingRequest(tmpDir, pending);+ const runMaintenance = vi.fn();++ await expect(+ runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'reader',+ loadVectorExtension: vi.fn(() => true),+ log,+ runMaintenance,+ }),+ ).rejects.toThrow('database slimming recovery requires the writer lease');++ expect(runMaintenance).not.toHaveBeenCalled();+ expect(readDbSlimmingRequest(tmpDir)).toEqual(pending);+ expect(readDbSlimmingResult(tmpDir)).toBeNull();+ });++ it('propagates an unrecoverable maintenance outcome so startup can fail closed', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const failed = {+ id: pending.id,+ ownerId: pending.ownerId,+ status: 'failed' as const,+ finishedAt: 3_000,+ archiveAgeMonths: 3 as const,+ reason: 'recovery-failed' as const,+ originalDatabaseRestored: false,+ };++ const outcome = await runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ runMaintenance: vi.fn(async () => ({+ result: failed,+ originalDatabaseReady: false,+ })),+ });++ expect(outcome).toEqual({+ handled: true,+ result: failed,+ originalDatabaseReady: false,+ });+ });++ it('records and clears a worker startup failure before any database work begins', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);++ const outcome = await runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ now: () => 3_000,+ runMaintenance: vi.fn(async () => {+ throw new DbSlimmingWorkerStartupError('bundle missing');+ }),+ });++ expect(outcome).toMatchObject({+ handled: true,+ originalDatabaseReady: true,+ result: {+ status: 'failed',+ reason: 'cleanup-failed',+ originalDatabaseRestored: true,+ },+ });+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(readDbSlimmingResult(tmpDir)).toMatchObject({+ id: pending.id,+ status: 'failed',+ reason: 'cleanup-failed',+ });+ });++ it('continues startup after a utility process failure before replacement', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);++ const outcome = await runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ now: () => 3_000,+ runMaintenance: vi.fn(async () => {+ throw new DbSlimmingWorkerPreReplacementError('utility process crashed');+ }),+ });++ expect(outcome).toMatchObject({+ handled: true,+ originalDatabaseReady: true,+ result: {+ status: 'failed',+ reason: 'cleanup-failed',+ originalDatabaseRestored: true,+ },+ });+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(readDbSlimmingResult(tmpDir)).toMatchObject({+ id: pending.id,+ status: 'failed',+ reason: 'cleanup-failed',+ });+ });++ it('does not continue startup after a utility process failure while its request is occupied', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const requestPath = path.join(tmpDir, 'db-slimming-request.json');+ const originalRmSync = fs.rmSync.bind(fs);+ vi.spyOn(fs, 'rmSync').mockImplementation((candidate, options) => {+ if (String(candidate) === requestPath) {+ throw Object.assign(new Error('request marker is busy'), { code: 'EBUSY' });+ }+ return originalRmSync(candidate, options);+ });++ await expect(+ runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ now: () => 3_000,+ runMaintenance: vi.fn(async () => {+ throw new DbSlimmingWorkerPreReplacementError('utility process crashed');+ }),+ }),+ ).rejects.toThrow('database slimming request marker could not be cleared');++ expect(readDbSlimmingRequest(tmpDir)).toEqual(pending);+ expect(readDbSlimmingResult(tmpDir)).toMatchObject({+ id: pending.id,+ status: 'failed',+ reason: 'cleanup-failed',+ });+ });++ it('discards the working copy and continues startup when the user cancels', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);++ const outcome = await runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ runMaintenance: vi.fn(async (options) => {+ options.onProgress?.({ phase: 'cleaning', progress: 52, cancellable: true });+ expect(cancelDbSlimmingStartupProgress()).toBe(true);+ expect(options.signal?.aborted).toBe(true);+ throw new DbSlimmingCancelledError();+ }),+ });++ expect(outcome).toEqual({ handled: false, originalDatabaseReady: true });+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(getDbSlimmingStartupProgress()).toBeNull();+ });++ it('does not report cancellation complete while the request marker is occupied', async () => {+ const pending = request();+ writeDbSlimmingRequest(tmpDir, pending);+ const requestPath = path.join(tmpDir, 'db-slimming-request.json');+ const originalRmSync = fs.rmSync.bind(fs);+ vi.spyOn(fs, 'rmSync').mockImplementation((candidate, options) => {+ if (String(candidate) === requestPath) {+ throw Object.assign(new Error('request marker is busy'), { code: 'EBUSY' });+ }+ return originalRmSync(candidate, options);+ });++ await expect(+ runPendingDbSlimmingAtStartup({+ userDataDir: tmpDir,+ dbFilePath,+ ownerId: pending.ownerId,+ leaseKind: 'writer',+ loadVectorExtension: vi.fn(() => true),+ log,+ runMaintenance: vi.fn(async () => {+ throw new DbSlimmingCancelledError();+ }),+ }),+ ).rejects.toThrow('database slimming request marker could not be cleared');++ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({ id: pending.id, phase: 'scheduled' });+ expect(getDbSlimmingStartupProgress()).toBeNull();+ });+});diff --git a/apps/desktop/src/main/localDb/__tests__/dbSlimmingStartupState.test.ts b/apps/desktop/src/main/localDb/__tests__/dbSlimmingStartupState.test.tsnew file mode 100644index 0000000000..e13aff3bcb--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/dbSlimmingStartupState.test.ts@@ -0,0 +1,84 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ beginDbSlimmingStartupProgress,+ cancelDbSlimmingStartupProgress,+ getDbSlimmingStartupProgress,+ subscribeDbSlimmingStartupProgress,+ type DbSlimmingStartupProgressJob,+} from '../dbSlimmingStartupState';+import type { DbSlimmingRequestRecord } from '../maintenanceStore';++let activeJob: DbSlimmingStartupProgressJob | null = null;++afterEach(() => {+ activeJob?.finish();+ activeJob = null;+});++function request(): DbSlimmingRequestRecord {+ return {+ version: 1,+ id: 'request-1',+ ownerId: 'owner-1',+ createdAt: 1,+ scannedAt: 2,+ archivedBeforeMs: 3,+ archiveAgeMonths: '7-days',+ deletedTaskCount: 4,+ archivedTaskCount: 5,+ messageCount: 6,+ estimatedMessageBytes: 100,+ beforeBytes: 96 * 1024 * 1024,+ backupEnabled: false,+ phase: 'scheduled',+ };+}++describe('database cleanup startup progress state', () => {+ it('publishes monotonic progress and turns cancellation into an abort signal', () => {+ let now = 1_000;+ const listener = vi.fn();+ const unsubscribe = subscribeDbSlimmingStartupProgress(listener);+ activeJob = beginDbSlimmingStartupProgress(request(), () => now);++ expect(getDbSlimmingStartupProgress()).toMatchObject({+ requestId: 'request-1',+ phase: 'preparing',+ progress: 1,+ cancellable: true,+ startedAt: 1_000,+ });++ now = 4_000;+ activeJob.update({ phase: 'compacting', progress: 60, cancellable: true });+ activeJob.update({ phase: 'compacting', progress: 55, cancellable: true });+ expect(getDbSlimmingStartupProgress()).toMatchObject({+ phase: 'compacting',+ progress: 60,+ cancellable: true,+ });++ expect(cancelDbSlimmingStartupProgress()).toBe(true);+ expect(activeJob.signal.aborted).toBe(true);+ expect(getDbSlimmingStartupProgress()).toMatchObject({+ phase: 'cancelling',+ cancellable: false,+ });+ expect(cancelDbSlimmingStartupProgress()).toBe(false);++ activeJob.finish();+ activeJob = null;+ expect(getDbSlimmingStartupProgress()).toBeNull();+ expect(listener).toHaveBeenLastCalledWith(null);+ unsubscribe();+ });++ it('rejects cancellation once final replacement begins', () => {+ activeJob = beginDbSlimmingStartupProgress(request(), () => 1_000);+ activeJob.update({ phase: 'finalizing', progress: 96, cancellable: false });++ expect(cancelDbSlimmingStartupProgress()).toBe(false);+ expect(activeJob.signal.aborted).toBe(false);+ });+});diff --git a/apps/desktop/src/main/localDb/__tests__/dbSlimmingUpgradeOrder.test.ts b/apps/desktop/src/main/localDb/__tests__/dbSlimmingUpgradeOrder.test.tsnew file mode 100644index 0000000000..e8767d3f39--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/dbSlimmingUpgradeOrder.test.ts@@ -0,0 +1,39 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++describe('database cleanup and upgrade startup order', () => {+ it('derives both the cleanup database path and request owner from the same user id', () => {+ const source = readFileSync(path.resolve(__dirname, '..', 'index.ts'), 'utf8');+ const pathBinding = source.indexOf('const filePath = dbPath(userId)');+ const cleanup = source.indexOf('maintenance = await runPendingDbSlimmingAtStartup', pathBinding);+ const cleanupBlock = source.slice(cleanup, source.indexOf('});', cleanup) + 3);++ expect(pathBinding).toBeGreaterThanOrEqual(0);+ expect(cleanup).toBeGreaterThan(pathBinding);+ expect(cleanupBlock).toContain('dbFilePath: filePath');+ expect(cleanupBlock).toContain('ownerId: userId');+ });++ it('finishes cleanup recovery before opening the database for migration', () => {+ const source = readFileSync(path.resolve(__dirname, '..', 'index.ts'), 'utf8');+ const cleanup = source.indexOf('maintenance = await runPendingDbSlimmingAtStartup');+ const recoveryGuard = source.indexOf('if (!maintenance.originalDatabaseReady)', cleanup);+ const open = source.indexOf('_db = openWithPragmas(filePath)', recoveryGuard);+ const schemaStartup = source.indexOf(+ 'const schemaStartup = await runSchemaStartupPolicy',+ open,+ );+ const migration = source.indexOf(+ 'runMigrations: () => runMigrations(db, filePath)',+ schemaStartup,+ );++ expect(cleanup).toBeGreaterThanOrEqual(0);+ expect(recoveryGuard).toBeGreaterThan(cleanup);+ expect(open).toBeGreaterThan(recoveryGuard);+ expect(schemaStartup).toBeGreaterThan(open);+ expect(migration).toBeGreaterThan(schemaStartup);+ });+});diff --git a/apps/desktop/src/main/localDb/__tests__/dbSlimmingWorkerClient.test.ts b/apps/desktop/src/main/localDb/__tests__/dbSlimmingWorkerClient.test.tsnew file mode 100644index 0000000000..b514e163b2--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/dbSlimmingWorkerClient.test.ts@@ -0,0 +1,441 @@+import { EventEmitter } from 'node:events';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('electron', () => ({+ utilityProcess: { fork: vi.fn() },+}));++vi.mock('../sqliteVecLoader', () => ({+ resolveSqliteVecExtPath: () => 'C:\\native\\vec0.dll',+}));++const {+ DB_SLIMMING_WORKER_READY_TIMEOUT_MS,+ DB_SLIMMING_WORKER_TERMINATION_TIMEOUT_MS,+ DbSlimmingCancelledError,+ DbSlimmingWorkerPreReplacementError,+ DbSlimmingWorkerStartupError,+ DbSlimmingWorkerTerminationUnconfirmedError,+ dbSlimmingWorkerInactivityTimeoutMs,+ deferReleaseUntilDbSlimmingWorkerTermination,+ runDbSlimmingMaintenanceInWorker,+} = await import('../dbSlimmingWorkerClient');++class FakeUtilityProcess extends EventEmitter {+ readonly posted: unknown[] = [];+ kill = vi.fn(() => true);++ postMessage(message: unknown): void {+ this.posted.push(message);+ }+}++function createRequest() {+ return {+ version: 1 as const,+ id: 'request-1',+ ownerId: 'owner-1',+ createdAt: 1,+ scannedAt: 2,+ archivedBeforeMs: 3,+ archiveAgeMonths: '7-days' as const,+ deletedTaskCount: 4,+ archivedTaskCount: 5,+ messageCount: 6,+ estimatedMessageBytes: 4_096,+ beforeBytes: 8_192,+ backupEnabled: false,+ phase: 'scheduled' as const,+ };+}++describe('runDbSlimmingMaintenanceInWorker', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('allows proportionally more inactivity time for a 20 GiB database', () => {+ expect(dbSlimmingWorkerInactivityTimeoutMs(20 * 1024 ** 3)).toBe(45 * 60_000);+ });++ it('times out when the utility process never becomes ready or reports an exit', async () => {+ vi.useFakeTimers();+ const child = new FakeUtilityProcess();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request: createRequest(),+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );+ const resultError = resultPromise.catch((error: unknown) => error);++ await vi.advanceTimersByTimeAsync(DB_SLIMMING_WORKER_READY_TIMEOUT_MS);+ expect(child.kill).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(DB_SLIMMING_WORKER_TERMINATION_TIMEOUT_MS);++ const error = await resultError;+ expect(error).toBeInstanceOf(DbSlimmingWorkerTerminationUnconfirmedError);+ expect(error).toMatchObject({+ message: 'database cleanup process termination was not confirmed',+ });+ if (!(error instanceof DbSlimmingWorkerTerminationUnconfirmedError)) {+ throw new Error('expected an unconfirmed termination error');+ }+ const releaseWriterLease = vi.fn();+ expect(deferReleaseUntilDbSlimmingWorkerTermination(error, releaseWriterLease)).toBe(true);+ await Promise.resolve();+ expect(releaseWriterLease).not.toHaveBeenCalled();++ child.emit('exit', 1);+ await error.terminationConfirmed;+ expect(releaseWriterLease).toHaveBeenCalledTimes(1);+ });++ it('times out safely while only disposable copies have been touched', async () => {+ vi.useFakeTimers();+ const child = new FakeUtilityProcess();+ const request = createRequest();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request,+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );+ const resultError = resultPromise.catch((error: unknown) => error);++ child.emit('message', { type: 'ready' });+ child.emit('message', {+ type: 'progress',+ progress: { phase: 'cleaning', progress: 52, cancellable: true },+ });+ await vi.advanceTimersByTimeAsync(dbSlimmingWorkerInactivityTimeoutMs(request.beforeBytes));+ expect(child.kill).toHaveBeenCalledTimes(1);+ child.emit('exit', 1);++ expect(await resultError).toBeInstanceOf(DbSlimmingWorkerPreReplacementError);+ });++ it('fails closed when the utility process stalls after the commit boundary', async () => {+ vi.useFakeTimers();+ const child = new FakeUtilityProcess();+ const request = createRequest();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request,+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );+ const resultError = resultPromise.catch((error: unknown) => error);++ child.emit('message', { type: 'ready' });+ child.emit('message', {+ type: 'progress',+ progress: { phase: 'finalizing', progress: 96, cancellable: false },+ });+ child.emit('message', { type: 'commit-ready' });+ await vi.advanceTimersByTimeAsync(dbSlimmingWorkerInactivityTimeoutMs(request.beforeBytes));+ expect(child.kill).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(DB_SLIMMING_WORKER_TERMINATION_TIMEOUT_MS);++ const error = await resultError;+ expect(error).toBeInstanceOf(DbSlimmingWorkerTerminationUnconfirmedError);+ if (!(error instanceof DbSlimmingWorkerTerminationUnconfirmedError)) {+ throw new Error('expected an unconfirmed termination error');+ }+ const releaseWriterLease = vi.fn();+ expect(+ deferReleaseUntilDbSlimmingWorkerTermination(error, releaseWriterLease),+ ).toBe(true);+ await Promise.resolve();+ expect(releaseWriterLease).not.toHaveBeenCalled();++ child.emit('exit', 1);+ await error.terminationConfirmed;+ expect(releaseWriterLease).toHaveBeenCalledTimes(1);+ });++ it('starts the utility process, forwards progress and waits for the final commit handshake', async () => {+ const child = new FakeUtilityProcess();+ const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ const onProgress = vi.fn();+ const request = createRequest();+ const outcome = {+ result: {+ id: request.id,+ ownerId: request.ownerId,+ status: 'failed' as const,+ finishedAt: 8,+ archiveAgeMonths: request.archiveAgeMonths,+ reason: 'cleanup-failed' as const,+ originalDatabaseRestored: true,+ },+ originalDatabaseReady: true,+ };++ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request,+ loadVectorExtension: vi.fn(() => true),+ log,+ onProgress,+ },+ () => child,+ );++ child.emit('message', { type: 'ready' });+ expect(child.posted[0]).toEqual({+ type: 'start',+ input: {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request,+ sqliteVecExtensionPath: 'C:\\native\\vec0.dll',+ },+ });++ child.emit('message', {+ type: 'progress',+ progress: { phase: 'compacting', progress: 70, cancellable: true },+ });+ child.emit('message', { type: 'log', level: 'info', message: 'phase', meta: { step: 1 } });+ child.emit('message', {+ type: 'progress',+ progress: { phase: 'finalizing', progress: 96, cancellable: false },+ });+ child.emit('message', { type: 'commit-ready' });++ expect(onProgress).toHaveBeenLastCalledWith({+ phase: 'finalizing',+ progress: 96,+ cancellable: false,+ });+ expect(child.posted.at(-1)).toEqual({ type: 'commit' });++ child.emit('message', { type: 'result', outcome });+ await expect(resultPromise).resolves.toEqual(outcome);+ expect(log.info).toHaveBeenCalledExactlyOnceWith('phase', { step: 1 });+ expect(child.kill).toHaveBeenCalledTimes(1);+ });++ it('kills cancellable native work and resolves cancellation after the process exits', async () => {+ const child = new FakeUtilityProcess();+ const controller = new AbortController();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request: createRequest(),+ signal: controller.signal,+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );++ child.emit('message', { type: 'ready' });+ child.emit('message', {+ type: 'progress',+ progress: { phase: 'cleaning', progress: 52, cancellable: true },+ });+ controller.abort();+ expect(child.kill).toHaveBeenCalledTimes(1);+ child.emit('exit', 0);++ await expect(resultPromise).rejects.toBeInstanceOf(DbSlimmingCancelledError);+ expect(child.kill).toHaveBeenCalledTimes(1);+ });++ it('holds the writer lease when cancellation cannot confirm termination', async () => {+ const child = new FakeUtilityProcess();+ child.kill.mockImplementation(() => {+ throw new Error('termination request failed');+ });+ const controller = new AbortController();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request: createRequest(),+ signal: controller.signal,+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );+ const resultError = resultPromise.catch((error: unknown) => error);++ child.emit('message', { type: 'ready' });+ controller.abort();++ const error = await resultError;+ expect(error).toBeInstanceOf(DbSlimmingWorkerTerminationUnconfirmedError);+ if (!(error instanceof DbSlimmingWorkerTerminationUnconfirmedError)) {+ throw new Error('expected an unconfirmed termination error');+ }+ const releaseWriterLease = vi.fn();+ expect(deferReleaseUntilDbSlimmingWorkerTermination(error, releaseWriterLease)).toBe(true);+ await Promise.resolve();+ expect(releaseWriterLease).not.toHaveBeenCalled();++ child.emit('exit', 1);+ await error.terminationConfirmed;+ expect(releaseWriterLease).toHaveBeenCalledTimes(1);+ });++ it('ignores cancellation after the replacement safety boundary', async () => {+ const child = new FakeUtilityProcess();+ const controller = new AbortController();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request: createRequest(),+ signal: controller.signal,+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );++ child.emit('message', { type: 'ready' });+ child.emit('message', {+ type: 'progress',+ progress: { phase: 'finalizing', progress: 96, cancellable: false },+ });+ child.emit('message', { type: 'commit-ready' });+ controller.abort();+ expect(child.kill).not.toHaveBeenCalled();++ const request = createRequest();+ const outcome = {+ result: {+ id: request.id,+ ownerId: request.ownerId,+ status: 'completed' as const,+ finishedAt: 8,+ archiveAgeMonths: request.archiveAgeMonths,+ deletedTaskCount: 4,+ archivedTaskCount: 5,+ messageCount: 6,+ beforeBytes: 8_192,+ afterBytes: 4_096,+ reclaimedBytes: 4_096,+ backupCreated: false,+ },+ originalDatabaseReady: true,+ };+ child.emit('message', { type: 'result', outcome });++ await expect(resultPromise).resolves.toEqual(outcome);+ });++ it('holds the writer lease when a process error does not confirm exit', async () => {+ vi.useFakeTimers();+ const child = new FakeUtilityProcess();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request: createRequest(),+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );+ const resultError = resultPromise.catch((error: unknown) => error);++ child.emit('message', { type: 'ready' });+ child.emit('error', new Error('ipc failed'));+ expect(child.kill).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(DB_SLIMMING_WORKER_TERMINATION_TIMEOUT_MS);++ const error = await resultError;+ expect(error).toBeInstanceOf(DbSlimmingWorkerTerminationUnconfirmedError);+ if (!(error instanceof DbSlimmingWorkerTerminationUnconfirmedError)) {+ throw new Error('expected an unconfirmed termination error');+ }+ const releaseWriterLease = vi.fn();+ expect(deferReleaseUntilDbSlimmingWorkerTermination(error, releaseWriterLease)).toBe(true);+ await Promise.resolve();+ expect(releaseWriterLease).not.toHaveBeenCalled();++ child.emit('exit', 1);+ await error.terminationConfirmed;+ expect(releaseWriterLease).toHaveBeenCalledTimes(1);+ });++ it('distinguishes a process startup failure before maintenance begins', async () => {+ const child = new FakeUtilityProcess();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request: createRequest(),+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );++ child.emit('error', new Error('bundle missing'));+ child.emit('exit', 1);++ await expect(resultPromise).rejects.toBeInstanceOf(DbSlimmingWorkerStartupError);+ });++ it('marks an unexpected exit as safely recoverable while only copies were touched', async () => {+ const child = new FakeUtilityProcess();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request: createRequest(),+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );++ child.emit('message', { type: 'ready' });+ child.emit('message', {+ type: 'progress',+ progress: { phase: 'copying', progress: 30, cancellable: true },+ });+ child.emit('exit', 1);++ await expect(resultPromise).rejects.toBeInstanceOf(DbSlimmingWorkerPreReplacementError);+ });++ it('does not claim the original is untouched after replacement begins', async () => {+ const child = new FakeUtilityProcess();+ const resultPromise = runDbSlimmingMaintenanceInWorker(+ {+ userDataDir: 'C:\\user-data',+ dbFilePath: 'C:\\user-data\\owner.db',+ request: createRequest(),+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ },+ () => child,+ );++ child.emit('message', { type: 'ready' });+ child.emit('message', {+ type: 'progress',+ progress: { phase: 'finalizing', progress: 96, cancellable: false },+ });+ child.emit('message', { type: 'commit-ready' });+ child.emit('exit', 1);++ await expect(resultPromise).rejects.not.toBeInstanceOf(DbSlimmingWorkerPreReplacementError);+ });+});diff --git a/apps/desktop/src/main/localDb/__tests__/devDbSlimmingRelaunch.test.ts b/apps/desktop/src/main/localDb/__tests__/devDbSlimmingRelaunch.test.tsnew file mode 100644index 0000000000..2d20b4c7a3--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/devDbSlimmingRelaunch.test.ts@@ -0,0 +1,43 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { writeDbSlimmingDevRelaunchSignal } from '../devDbSlimmingRelaunch';++const temporaryDirectories: string[] = [];++afterEach(() => {+ for (const directory of temporaryDirectories.splice(0)) {+ fs.rmSync(directory, { recursive: true, force: true });+ }+});++describe('writeDbSlimmingDevRelaunchSignal', () => {+ it('atomically writes a request signal only inside the runner temp directory', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-db-cleanup-relaunch-'));+ temporaryDirectories.push(tempDir);+ const signalPath = path.join(tempDir, 'relaunch.json');++ expect(+ writeDbSlimmingDevRelaunchSignal('request-1', { signalPath, tempDir }),+ ).toBe(true);+ expect(JSON.parse(fs.readFileSync(signalPath, 'utf8'))).toMatchObject({+ version: 1,+ requestId: 'request-1',+ });+ expect(fs.existsSync(`${signalPath}.${process.pid}.tmp`)).toBe(false);+ });++ it('refuses paths outside the runner temp directory', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-db-cleanup-relaunch-'));+ temporaryDirectories.push(tempDir);+ const signalPath = path.join(path.dirname(tempDir), `${path.basename(tempDir)}-outside.json`);++ expect(+ writeDbSlimmingDevRelaunchSignal('request-1', { signalPath, tempDir }),+ ).toBe(false);+ expect(fs.existsSync(signalPath)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/localDb/backup.ts b/apps/desktop/src/main/localDb/backup.tsindex 6c30b40ab1..cb631749cf 100644--- a/apps/desktop/src/main/localDb/backup.ts+++ b/apps/desktop/src/main/localDb/backup.ts@@ -1,13 +1,15 @@/*** chat-data-localization F1/F3:本地 db 文件备份与恢复(V0.4 修订 + ADR-FE7 移除)。*- * 两类备份文件(互不挤压配额):+ * 三类备份文件(互不挤压配额):* - `.bak.{ISO}` —— schema migration 前的快照,按"份数 + 总体积"双上限轮转* (见 `pruneIsoBackupsToBudget` / `isoBackupTotalBudgetBytes`)。* - `.bak.clean` —— 历史"干净退出快照"。**新版本不再生成**(write 路径* `cleanExitSnapshot` 已移除,详见 localDb/index.ts 文件头 ADR-FE7 修订说明)。* 已存在的旧 `.bak.clean` 文件仍作为 SQLITE_CORRUPT 恢复的 Step 1 兜底,* 向后兼容老用户。新装用户磁盘上不会有这个文件。+ * - `.slimming-backup` —— 用户主动数据库瘦身前的最近一份快照,由+ * `maintenanceStore` 的独立索引轮换;本文件的升级配额和自动损坏恢复不读取它。** SQLITE_CORRUPT 兜底:`.bak.clean`(若存在)优先 → `.bak.{ISO}` 回落(ADR-FE8)。* 主路径靠 SQLite WAL crash recovery(业界主流方案,VSCode/Slack/codex 同款)。@@ -89,7 +91,7 @@ export function cleanupFailedBackupArtifacts(backupPath: string): void {/*** 列出当前 db 对应的所有 `.bak.{ISO}` 文件,按 ISO 时间戳字典序升序返回。- * 显式排除 `.bak.clean`——配额隔离(ADR-FE9)。+ * 显式只接受 ISO 命名;`.bak.clean` 和 `.slimming-backup` 均不会进入升级配额。*/export function listIsoBackups(dbFilePath: string): string[] {const dir = path.dirname(dbFilePath);@@ -258,6 +260,9 @@ export interface RestoreResult {* Step 2: 回落到最新 `.bak.{ISO}`* Step 3: 都不可用 → return null(调用方阻断启动 + 弹 OS 对话框)*+ * 主动瘦身备份不参与这条自动恢复链,避免把用户选择的历史截面+ * 误当成 schema migration 的可兼容回滚点。+ ** 每一级恢复后会用 better-sqlite3 试只读打开 + quick_check 验证;打不开则继续下一级。*/export function tryRestoreWithFallback(dbFilePath: string): RestoreResult | null {diff --git a/apps/desktop/src/main/localDb/betterSqliteFactory.ts b/apps/desktop/src/main/localDb/betterSqliteFactory.tsindex bcf84f7fd0..71847f24f6 100644--- a/apps/desktop/src/main/localDb/betterSqliteFactory.ts+++ b/apps/desktop/src/main/localDb/betterSqliteFactory.ts@@ -50,7 +50,7 @@ export function getElectronNativeBindingPath(}export function resolveBetterSqliteNativeBinding(- env: EnvLike = process.env,+ env: EnvLike = runtimeProcessEnv(),versions: ProcessVersionsLike = process.versions,options: ResolveNativeBindingOptions = {},): string | undefined {@@ -72,6 +72,18 @@ export function resolveBetterSqliteNativeBinding(return undefined;}+/**+ * Vite replaces the literal `process.env` expression in preload-target bundles+ * with a build-time object. Utility processes still need their fork-time env,+ * especially the Electron-native better-sqlite3 binding selected by Main.+ */+function runtimeProcessEnv(): EnvLike {+ const runtimeProcess = Reflect.get(globalThis, 'process') as+ | { env?: EnvLike }+ | undefined;+ return runtimeProcess?.env ?? {};+}+// createRequire 绑定到本 bundle 文件位置 —— 与主进程静态 `import Database from 'better-sqlite3'`// 同一解析上下文,所以这里 resolve 出来的路径在 dev / packaged 都指向真正被加载的那份// better-sqlite3 (packaged 下是 app.asar.unpacked/node_modules/better-sqlite3/...)。diff --git a/apps/desktop/src/main/localDb/dbSlimmingBetterSqlite.ts b/apps/desktop/src/main/localDb/dbSlimmingBetterSqlite.tsnew file mode 100644index 0000000000..7504064995--- /dev/null+++ b/apps/desktop/src/main/localDb/dbSlimmingBetterSqlite.ts@@ -0,0 +1,21 @@+import { createRequire } from 'node:module';+import { workerData } from 'node:worker_threads';++type DatabaseConstructor = new (+ filename: string | Buffer,+ options?: Record<string, unknown>,+) => unknown;++const moduleRequire = createRequire(import.meta.url);+const modulePath = (workerData as { betterSqliteModulePath?: string } | undefined)+ ?.betterSqliteModulePath ?? process.env.CINDY_DB_SLIMMING_BETTER_SQLITE_MODULE;+const loaded = moduleRequire(modulePath || 'better-sqlite3') as+ | DatabaseConstructor+ | { default?: DatabaseConstructor };+const Database = typeof loaded === 'function' ? loaded : loaded.default;++if (typeof Database !== 'function') {+ throw new Error('database cleanup worker could not load better-sqlite3');+}++export default Database;diff --git a/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts b/apps/desktop/src/main/localDb/dbSlimmingMaintenance.tsnew file mode 100644index 0000000000..480c5f86ea--- /dev/null+++ b/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts@@ -0,0 +1,1055 @@+import type Database from 'better-sqlite3';+import fs from 'node:fs';+import path from 'node:path';++import type {+ DbSlimmingFailureReason,+ DbSlimmingMaintenanceProgress,+} from '../../shared/localDbMaintenance';+import { createBetterSqliteDatabase, restrictDbFilePermissions } from './betterSqliteFactory';+import {+ adoptDbSlimmingBackup,+ clearDbSlimmingRequest,+ readDbSlimmingResult,+ type DbSlimmingRequestRecord,+ type DbSlimmingResultRecord,+ writeDbSlimmingRequest,+ writeDbSlimmingResult,+} from './maintenanceStore';++const TEMP_SPACE_MARGIN_BYTES = 64 * 1024 * 1024;+const SQLITE_SIDECAR_SUFFIXES = ['-wal', '-shm', '-journal'] as const;++export interface DbSlimmingMaintenanceLog {+ info(message: string, meta?: unknown): void;+ warn(message: string, meta?: unknown): void;+ error(message: string, meta?: unknown): void;+}++export interface RunDbSlimmingMaintenanceOptions {+ userDataDir: string;+ dbFilePath: string;+ request: DbSlimmingRequestRecord;+ loadVectorExtension?: (db: Database.Database) => boolean;+ now?: () => number;+ log: DbSlimmingMaintenanceLog;+ signal?: AbortSignal;+ onProgress?: (progress: DbSlimmingMaintenanceProgress) => void;+ beforeReplacement?: () => Promise<void>;+}++export interface RunDbSlimmingMaintenanceOutcome {+ result: DbSlimmingResultRecord;+ originalDatabaseReady: boolean;+}++interface MaintenancePaths {+ work: string;+ rollback: string;+ backupFinal: string | null;+ backupPrevious: string | null;+ backupCandidate: string | null;+ backupLocation: 'database-directory' | 'custom-directory' | undefined;+ defaultDirectoryBackup: boolean;+}++interface TargetCounts {+ deletedTaskCount: number;+ archivedTaskCount: number;+ messageCount: number;+}++class DbSlimmingMaintenanceError extends Error {+ constructor(+ readonly reason: DbSlimmingFailureReason,+ message: string,+ readonly originalDatabaseReady = true,+ options?: ErrorOptions,+ ) {+ super(message, options);+ this.name = 'DbSlimmingMaintenanceError';+ }+}++/** Conservative peak space: one working copy plus SQLite's VACUUM scratch copy. */+export function dbSlimmingTemporaryBytesRequired(databaseBytes: number): number {+ return Math.max(0, Math.ceil(databaseBytes * 2 + TEMP_SPACE_MARGIN_BYTES));+}++export function dbVolumeFreeBytes(dbFilePath: string): number | null {+ return directoryFreeBytes(path.dirname(dbFilePath));+}++export function estimateDbFilesBytes(dbFilePath: string): number {+ let total = 0;+ for (const candidate of [dbFilePath, `${dbFilePath}-wal`]) {+ try {+ total += fs.statSync(candidate).size;+ } catch {+ // Missing WAL files are normal after a clean checkpoint.+ }+ }+ return total;+}++/**+ * Runs only while ensureReady owns the schema writer lease and before the normal+ * database connection or worker is opened. All destructive work happens on a+ * copy; the original remains the rollback source until the replacement passes.+ */+export async function runDbSlimmingMaintenance(+ options: RunDbSlimmingMaintenanceOptions,+): Promise<RunDbSlimmingMaintenanceOutcome> {+ const now = options.now ?? Date.now;+ let request = options.request;+ const paths = maintenancePaths(options.dbFilePath, request);+ let replacementInstalled = request.phase === 'replacement-installed';+ let committed = request.phase === 'committed';++ reportProgress(options, 'preparing', 2, request.phase === 'scheduled');++ try {+ // A failed rollback-marker write leaves the previous replacement-installed+ // marker on disk, while the restored replacement is parked back at work.+ // Advance that durable state before treating the active database as the+ // committed replacement on a later startup.+ if (request.phase === 'replacement-installed' && fs.existsSync(paths.work)) {+ request = {+ ...request,+ phase: 'rollback-completed',+ rollbackFailureReason: request.rollbackFailureReason ?? 'recovery-failed',+ };+ writeDbSlimmingRequest(options.userDataDir, request);+ }++ if (request.phase === 'rollback-completed') {+ const originalDatabaseReady = verifyDatabaseFile(options.dbFilePath);+ const result: DbSlimmingResultRecord = {+ id: request.id,+ ownerId: request.ownerId,+ status: 'failed',+ finishedAt: now(),+ archiveAgeMonths: request.archiveAgeMonths,+ reason: originalDatabaseReady+ ? (request.rollbackFailureReason ?? 'recovery-failed')+ : 'recovery-failed',+ originalDatabaseRestored: originalDatabaseReady,+ };+ if (!originalDatabaseReady) {+ return { result, originalDatabaseReady: false };+ }+ try {+ writeDbSlimmingResult(options.userDataDir, result);+ } catch (error) {+ options.log.warn('database slimming rollback result could not be persisted', {+ requestId: request.id,+ error: error instanceof Error ? error.message : String(error),+ });+ return { result, originalDatabaseReady: true };+ }+ if (!finalizeFailedCleanup(options.userDataDir, paths)) {+ options.log.warn('database slimming rollback cleanup will be retried', {+ requestId: request.id,+ });+ }+ return { result, originalDatabaseReady: true };+ }++ if (request.phase === 'committed') {+ if (!verifyDatabaseFile(options.dbFilePath)) {+ throw new DbSlimmingMaintenanceError(+ 'recovery-failed',+ 'committed replacement database is invalid',+ false,+ );+ }+ let result: DbSlimmingResultRecord | null = null;+ try {+ result = readDbSlimmingResult(options.userDataDir);+ } catch (error) {+ options.log.warn('committed database slimming result could not be read', {+ requestId: request.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (+ !result ||+ result.id !== request.id ||+ result.ownerId !== request.ownerId ||+ result.status !== 'completed'+ ) {+ registerInstalledBackup(options, request, paths);+ result = completedResult(request, paths, options.dbFilePath, now());+ writeDbSlimmingResult(options.userDataDir, result);+ }+ try {+ finalizeCommittedCleanup(options.userDataDir, paths);+ } catch (error) {+ options.log.warn('database slimming committed cleanup will be retried', {+ requestId: request.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ return { result, originalDatabaseReady: true };+ }++ if (request.phase === 'swap-prepared') {+ restoreOriginalDatabase(options.dbFilePath, paths, options.log);+ request = { ...request, phase: 'scheduled' };+ writeDbSlimmingRequest(options.userDataDir, request);+ } else if (request.phase === 'replacement-installed') {+ if (!verifyDatabaseFile(options.dbFilePath)) {+ throw new DbSlimmingMaintenanceError(+ 'integrity-check-failed',+ 'replacement database did not pass startup recovery validation',+ );+ }+ registerInstalledBackup(options, request, paths);+ const recoveredResult = completedResult(request, paths, options.dbFilePath, now());+ try {+ writeDbSlimmingResult(options.userDataDir, recoveredResult);+ } catch (error) {+ options.log.warn('database slimming recovery result could not be persisted', {+ requestId: request.id,+ error: error instanceof Error ? error.message : String(error),+ });+ return { result: recoveredResult, originalDatabaseReady: true };+ }+ request = { ...request, phase: 'committed' };+ try {+ writeDbSlimmingRequest(options.userDataDir, request);+ committed = true;+ finalizeCommittedCleanup(options.userDataDir, paths);+ } catch (error) {+ options.log.warn('database slimming recovery cleanup will be retried', {+ requestId: request.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ return { result: recoveredResult, originalDatabaseReady: true };+ }++ recoverInterruptedCustomBackupInstall(paths);+ cleanupUncommittedArtifacts(paths);+ assertMaintenanceSpace(options.dbFilePath, request, paths);+ reportProgress(options, 'preparing', 5, true);++ const beforeBytes = estimateDbFilesBytes(options.dbFilePath);+ request = { ...request, beforeBytes };+ writeDbSlimmingRequest(options.userDataDir, request);++ const source = openSourceDatabase(options.dbFilePath);+ try {+ if (paths.backupCandidate && paths.backupFinal) {+ reportProgress(options, 'backing-up', 7, true);+ await createAndInstallCustomBackup(source, paths, options.log, (fraction) => {+ reportProgress(options, 'backing-up', 7 + fraction * 13, true);+ });+ registerInstalledBackup(options, request, paths, true);+ }+ removeDatabaseFamily(paths.work);+ try {+ const progressStart = paths.backupCandidate ? 20 : 7;+ const progressSpan = paths.backupCandidate ? 20 : 33;+ reportProgress(options, 'copying', progressStart, true);+ await source.backup(paths.work, {+ progress: (progress) => {+ const fraction = backupFraction(progress);+ reportProgress(+ options,+ 'copying',+ progressStart + fraction * progressSpan,+ true,+ );+ return 4_096;+ },+ });+ } catch (error) {+ throw new DbSlimmingMaintenanceError('cleanup-failed', 'working copy failed', true, {+ cause: error,+ });+ }+ } finally {+ source.close();+ }++ const targetCounts = compactWorkingCopy(paths.work, request, options);+ request = { ...request, ...targetCounts };+ writeDbSlimmingRequest(options.userDataDir, request);++ reportProgress(options, 'finalizing', 96, false);+ await options.beforeReplacement?.();+ request = { ...request, phase: 'swap-prepared' };+ writeDbSlimmingRequest(options.userDataDir, request);+ installReplacement(options.dbFilePath, paths);+ replacementInstalled = true;++ request = { ...request, phase: 'replacement-installed' };+ writeDbSlimmingRequest(options.userDataDir, request);+ // The verified VACUUM INTO output is renamed within the same directory.+ // Re-reading the same multi-gigabyte file after each rename adds no useful+ // corruption coverage and makes cleanup scale with several full DB scans.+ registerInstalledBackup(options, request, paths, true);++ const result = completedResult(request, paths, options.dbFilePath, now());+ try {+ writeDbSlimmingResult(options.userDataDir, result);+ } catch (error) {+ options.log.warn('database slimming result could not be persisted', {+ requestId: request.id,+ error: error instanceof Error ? error.message : String(error),+ });+ return { result, originalDatabaseReady: true };+ }+ request = { ...request, phase: 'committed' };+ try {+ writeDbSlimmingRequest(options.userDataDir, request);+ committed = true;+ finalizeCommittedCleanup(options.userDataDir, paths);+ } catch (error) {+ // The replacement and the completed result are already durable. Keep the+ // on-disk committed marker so the next startup can retry artifact cleanup+ // instead of reporting a false failure or rolling back a database that+ // already passed both integrity checks.+ options.log.warn('database slimming committed cleanup will be retried', {+ requestId: request.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ options.log.info('database slimming completed', {+ requestId: request.id,+ deletedTasks: request.deletedTaskCount,+ archivedTasks: request.archivedTaskCount,+ messages: request.messageCount,+ reclaimedBytes: result.reclaimedBytes,+ backupCreated: result.backupCreated,+ });+ reportProgress(options, 'finalizing', 100, false);+ return { result, originalDatabaseReady: true };+ } catch (error) {+ const maintenanceError = normalizeMaintenanceError(error);+ let originalDatabaseReady = maintenanceError.originalDatabaseReady;+ let rollbackMarkerDurable = false;+ let recoveryStateDurable = true;+ if (!committed && (replacementInstalled || request.phase === 'swap-prepared')) {+ try {+ restoreOriginalDatabase(options.dbFilePath, paths, options.log);+ originalDatabaseReady = verifyDatabaseFile(options.dbFilePath);+ } catch (restoreError) {+ originalDatabaseReady = false;+ options.log.error('database slimming rollback failed', {+ requestId: request.id,+ error: restoreError instanceof Error ? restoreError.message : String(restoreError),+ });+ }+ if (originalDatabaseReady) {+ try {+ request = {+ ...request,+ phase: 'rollback-completed',+ rollbackFailureReason: maintenanceError.reason,+ };+ writeDbSlimmingRequest(options.userDataDir, request);+ rollbackMarkerDurable = true;+ } catch (markerError) {+ recoveryStateDurable = false;+ options.log.warn('database slimming rollback marker could not be advanced', {+ requestId: request.id,+ error: markerError instanceof Error ? markerError.message : String(markerError),+ });+ }+ }+ }+ const result: DbSlimmingResultRecord = {+ id: request.id,+ ownerId: request.ownerId,+ status: 'failed',+ finishedAt: now(),+ archiveAgeMonths: request.archiveAgeMonths,+ reason: originalDatabaseReady ? maintenanceError.reason : 'recovery-failed',+ originalDatabaseRestored: originalDatabaseReady,+ };+ let resultPersisted = false;+ try {+ writeDbSlimmingResult(options.userDataDir, result);+ resultPersisted = true;+ } catch (resultError) {+ options.log.warn('database slimming result marker could not be written', {+ requestId: request.id,+ error: resultError instanceof Error ? resultError.message : String(resultError),+ });+ }+ if (originalDatabaseReady && recoveryStateDurable) {+ if (rollbackMarkerDurable) {+ if (resultPersisted && !finalizeFailedCleanup(options.userDataDir, paths)) {+ options.log.warn('database slimming rollback cleanup will be retried', {+ requestId: request.id,+ });+ }+ } else if (resultPersisted && !finalizeFailedCleanup(options.userDataDir, paths)) {+ options.log.warn('database slimming failed cleanup will be retried', {+ requestId: request.id,+ });+ }+ }+ options.log.error('database slimming failed', {+ requestId: request.id,+ reason: result.reason,+ originalDatabaseReady: originalDatabaseReady && recoveryStateDurable,+ error: maintenanceError.message,+ });+ return { result, originalDatabaseReady: originalDatabaseReady && recoveryStateDurable };+ }+}++function maintenancePaths(+ dbFilePath: string,+ request: DbSlimmingRequestRecord,+): MaintenancePaths {+ const dbDir = path.dirname(dbFilePath);+ const customBackupDir = request.backupDirectory+ ? path.resolve(request.backupDirectory)+ : undefined;+ const defaultDirectoryBackup =+ request.backupEnabled &&+ (!customBackupDir || pathsEqual(customBackupDir, path.resolve(dbDir)));+ const backupDir = request.backupEnabled ? (customBackupDir ?? dbDir) : null;+ const backupFinal = backupDir+ ? path.join(backupDir, `${path.basename(dbFilePath)}.slimming-backup`)+ : null;+ return {+ work: `${dbFilePath}.slimming-${request.id}.work`,+ rollback: `${dbFilePath}.slimming-${request.id}.rollback`,+ backupFinal,+ backupPrevious: backupFinal ? `${backupFinal}.${request.id}.previous` : null,+ backupCandidate:+ request.backupEnabled && !defaultDirectoryBackup && backupFinal+ ? `${backupFinal}.${request.id}.candidate`+ : null,+ backupLocation: request.backupEnabled+ ? defaultDirectoryBackup+ ? 'database-directory'+ : 'custom-directory'+ : undefined,+ defaultDirectoryBackup,+ };+}++function assertMaintenanceSpace(+ dbFilePath: string,+ request: DbSlimmingRequestRecord,+ paths: MaintenancePaths,+): void {+ const databaseBytes = Math.max(request.beforeBytes, estimateDbFilesBytes(dbFilePath));+ const dbDir = path.dirname(dbFilePath);+ let required = dbSlimmingTemporaryBytesRequired(databaseBytes);+ const backupDir = paths.backupCandidate ? path.dirname(paths.backupCandidate) : null;+ if (backupDir) {+ let backupDirStat: fs.Stats;+ try {+ backupDirStat = fs.statSync(backupDir);+ } catch (error) {+ throw new DbSlimmingMaintenanceError(+ 'backup-failed',+ 'backup destination is unavailable',+ true,+ { cause: error },+ );+ }+ if (!backupDirStat.isDirectory()) {+ throw new DbSlimmingMaintenanceError('backup-failed', 'backup destination is not a directory');+ }+ }+ if (backupDir && directoriesShareVolume(dbDir, backupDir)) {+ required += databaseBytes;+ }+ const dbFree = directoryFreeBytes(dbDir);+ if (dbFree !== null && dbFree < required) {+ throw new DbSlimmingMaintenanceError(+ 'insufficient-space',+ `database volume needs ${required} bytes but only ${dbFree} bytes are free`,+ );+ }+ if (paths.backupCandidate && backupDir && !directoriesShareVolume(dbDir, backupDir)) {+ const backupFree = directoryFreeBytes(backupDir);+ const backupRequired = databaseBytes + TEMP_SPACE_MARGIN_BYTES;+ if (backupFree !== null && backupFree < backupRequired) {+ throw new DbSlimmingMaintenanceError(+ 'insufficient-space',+ `backup volume needs ${backupRequired} bytes but only ${backupFree} bytes are free`,+ );+ }+ }+}++function openSourceDatabase(dbFilePath: string): Database.Database {+ let db: Database.Database;+ try {+ db = createBetterSqliteDatabase(dbFilePath, { fileMustExist: true });+ } catch (error) {+ throw new DbSlimmingMaintenanceError(+ 'cleanup-failed',+ 'source database could not be opened',+ false,+ { cause: error },+ );+ }+ try {+ db.pragma('busy_timeout = 5000');+ db.pragma('wal_checkpoint(TRUNCATE)');+ verifyOpenDatabase(db);+ restrictDbFilePermissions(dbFilePath);+ return db;+ } catch (error) {+ db.close();+ throw new DbSlimmingMaintenanceError('integrity-check-failed', 'source database is invalid', true, {+ cause: error,+ });+ }+}++async function createAndInstallCustomBackup(+ source: Database.Database,+ paths: MaintenancePaths,+ log: DbSlimmingMaintenanceLog,+ onProgress?: (fraction: number) => void,+): Promise<void> {+ const candidate = paths.backupCandidate;+ const finalPath = paths.backupFinal;+ const previous = paths.backupPrevious;+ if (!candidate || !finalPath || !previous) return;+ removeDatabaseFamily(candidate);+ removeDatabaseFamily(previous);+ try {+ await source.backup(candidate, {+ progress: (progress) => {+ onProgress?.(backupFraction(progress));+ return 4_096;+ },+ });+ if (!verifyDatabaseFile(candidate)) {+ throw new Error('backup integrity check failed');+ }+ restrictDbFilePermissions(candidate);+ if (fs.existsSync(finalPath)) renameWithRetry(finalPath, previous);+ try {+ renameWithRetry(candidate, finalPath);+ } catch (error) {+ if (fs.existsSync(previous) && !fs.existsSync(finalPath)) {+ renameWithRetry(previous, finalPath);+ }+ throw error;+ }+ removeDatabaseFamily(previous);+ restrictDbFilePermissions(finalPath);+ } catch (error) {+ removeDatabaseFamily(candidate);+ log.warn('database slimming backup creation failed', {+ backupName: path.basename(finalPath),+ error: error instanceof Error ? error.message : String(error),+ });+ throw new DbSlimmingMaintenanceError('backup-failed', 'database backup failed', true, {+ cause: error,+ });+ }+}++function compactWorkingCopy(+ workPath: string,+ request: DbSlimmingRequestRecord,+ options: RunDbSlimmingMaintenanceOptions,+): TargetCounts {+ const vacuumPath = `${workPath}.vacuum`;+ removeDatabaseFamily(vacuumPath);+ let db: Database.Database | null = createBetterSqliteDatabase(workPath, { fileMustExist: true });+ try {+ // This copy is disposable and the untouched source remains the rollback+ // authority. Avoid writing a second copy of changed pages to a rollback+ // journal; a crash simply discards this work file on the next startup.+ db.pragma('journal_mode = OFF');+ db.pragma('synchronous = OFF');+ db.pragma('foreign_keys = ON');+ db.pragma('busy_timeout = 5000');+ if (tableExists(db, 'chat_messages_vec_v1')) {+ if (!options.loadVectorExtension?.(db)) {+ throw new DbSlimmingMaintenanceError(+ 'cleanup-failed',+ 'sqlite vector extension is required to clean message vectors',+ );+ }+ }++ db.exec('DROP TABLE IF EXISTS temp.db_slimming_targets');+ db.exec('CREATE TEMP TABLE db_slimming_targets (id TEXT PRIMARY KEY, status TEXT NOT NULL)');+ db.prepare(+ `INSERT INTO temp.db_slimming_targets (id, status)+ SELECT id, status+ FROM sessions+ WHERE ((status = 'deleted' AND updated_at <= ?)+ OR (status = 'archived' AND updated_at <= ?))+ AND EXISTS (SELECT 1 FROM messages WHERE messages.session_id = sessions.id)`,+ ).run(request.scannedAt, request.archivedBeforeMs);++ const counts = db+ .prepare(+ `SELECT+ SUM(CASE WHEN t.status = 'deleted' THEN 1 ELSE 0 END) AS deletedTaskCount,+ SUM(CASE WHEN t.status = 'archived' THEN 1 ELSE 0 END) AS archivedTaskCount,+ (SELECT COUNT(*)+ FROM messages m+ JOIN temp.db_slimming_targets target ON target.id = m.session_id) AS messageCount+ FROM temp.db_slimming_targets t`,+ )+ .get() as {+ deletedTaskCount: number | null;+ archivedTaskCount: number | null;+ messageCount: number;+ };+ const targetCounts: TargetCounts = {+ deletedTaskCount: counts.deletedTaskCount ?? 0,+ archivedTaskCount: counts.archivedTaskCount ?? 0,+ messageCount: counts.messageCount ?? 0,+ };++ const activeDb = db;+ const messagesFtsDeleteTriggerSql = triggerSql(activeDb, 'messages_fts_delete');+ const sessionColumns = new Set(+ (+ activeDb.prepare("PRAGMA table_info('sessions')").all() as Array<{ name: string }>+ ).map((column) => column.name),+ );+ const listProjectionColumns = [+ 'list_preview',+ 'list_preview_role',+ 'list_message_count',+ ].filter((column) => sessionColumns.has(column));+ reportProgress(options, 'cleaning', 44, true);+ const cleanup = activeDb.transaction(() => {+ // message_id/session_id are UNINDEXED FTS columns. Letting the trigger run+ // once per message turns a large cleanup into N full FTS scans. Drop only+ // this trigger inside the transaction, scan FTS once by session, clear+ // its stable rowid map in bulk, then restore the exact schema SQL.+ if (messagesFtsDeleteTriggerSql) {+ activeDb.exec('DROP TRIGGER messages_fts_delete');+ }+ if (tableExists(activeDb, 'messages_fts')) {+ activeDb.exec(+ `DELETE FROM messages_fts+ WHERE session_id IN (SELECT id FROM temp.db_slimming_targets)`,+ );+ }+ if (tableExists(activeDb, 'messages_fts_rows')) {+ activeDb.exec(+ `DELETE FROM messages_fts_rows+ WHERE message_id IN (+ SELECT message.id+ FROM messages message+ JOIN temp.db_slimming_targets target ON target.id = message.session_id+ )`,+ );+ }+ if (+ tableExists(activeDb, 'chat_messages_vec_v1') &&+ tableExists(activeDb, 'embedding_jobs')+ ) {+ activeDb.exec(+ `DELETE FROM chat_messages_vec_v1+ WHERE rowid IN (+ SELECT job.rowid+ FROM embedding_jobs job+ JOIN messages message ON message.id = job.source_id+ JOIN temp.db_slimming_targets target ON target.id = message.session_id+ WHERE job.source = 'chat'+ )`,+ );+ }+ if (tableExists(activeDb, 'embedding_jobs')) {+ activeDb.exec(+ `DELETE FROM embedding_jobs+ WHERE source = 'chat'+ AND source_id IN (+ SELECT message.id+ FROM messages message+ JOIN temp.db_slimming_targets target ON target.id = message.session_id+ )`,+ );+ }+ activeDb.exec(+ `DELETE FROM messages+ WHERE session_id IN (SELECT id FROM temp.db_slimming_targets)`,+ );+ if (listProjectionColumns.length > 0) {+ activeDb.exec(+ `UPDATE sessions+ SET ${listProjectionColumns.map((column) => `${column} = NULL`).join(', ')}+ WHERE id IN (SELECT id FROM temp.db_slimming_targets)`,+ );+ }+ if (messagesFtsDeleteTriggerSql) activeDb.exec(messagesFtsDeleteTriggerSql);+ });+ cleanup();++ db.exec('DROP TABLE temp.db_slimming_targets');+ reportProgress(options, 'compacting', 58, true);+ // VACUUM INTO writes the compact database once. In-place VACUUM first+ // builds a temporary database and then copies it back over the working+ // file, doubling the final write volume for large profiles.+ db.prepare('VACUUM INTO ?').run(vacuumPath);+ restrictDbFilePermissions(vacuumPath);+ db.close();+ db = null;+ reportProgress(options, 'verifying', 90, true);+ if (!verifyDatabaseFile(vacuumPath)) {+ throw new DbSlimmingMaintenanceError(+ 'integrity-check-failed',+ 'compacted working database did not pass integrity checks',+ );+ }+ restrictDbFilePermissions(vacuumPath);+ removeDatabaseFamily(workPath);+ renameWithRetry(vacuumPath, workPath);+ restrictDbFilePermissions(workPath);+ return targetCounts;+ } catch (error) {+ if (error instanceof DbSlimmingMaintenanceError) throw error;+ throw new DbSlimmingMaintenanceError('cleanup-failed', 'database cleanup failed', true, {+ cause: error,+ });+ } finally {+ db?.close();+ removeDatabaseFamily(vacuumPath);+ }+}++export function discardCancelledDbSlimmingMaintenance(+ userDataDir: string,+ dbFilePath: string,+ request: DbSlimmingRequestRecord,+): void {+ const paths = maintenancePaths(dbFilePath, request);+ recoverInterruptedCustomBackupInstall(paths);+ if (!cleanupUncommittedArtifacts(paths)) {+ throw new Error('cancelled database slimming artifacts could not be removed');+ }+ clearDbSlimmingRequestOrThrow(userDataDir);+}++function reportProgress(+ options: RunDbSlimmingMaintenanceOptions,+ phase: DbSlimmingMaintenanceProgress['phase'],+ progress: number,+ cancellable: boolean,+): void {+ options.onProgress?.({+ phase,+ progress: Math.min(100, Math.max(0, progress)),+ cancellable,+ });+}++function backupFraction(progress: Database.BackupMetadata): number {+ if (progress.totalPages <= 0) return 0;+ return Math.min(1, Math.max(0, 1 - progress.remainingPages / progress.totalPages));+}++function installReplacement(dbFilePath: string, paths: MaintenancePaths): void {+ try {+ removeSidecars(dbFilePath);+ if (paths.defaultDirectoryBackup) {+ if (!paths.backupFinal || !paths.backupPrevious) {+ throw new Error('default backup paths are missing');+ }+ removeDatabaseFamily(paths.backupPrevious);+ if (fs.existsSync(paths.backupFinal)) {+ renameWithRetry(paths.backupFinal, paths.backupPrevious);+ }+ renameWithRetry(dbFilePath, paths.backupFinal);+ renameWithRetry(paths.work, dbFilePath);+ restrictDbFilePermissions(paths.backupFinal);+ } else {+ removeDatabaseFamily(paths.rollback);+ renameWithRetry(dbFilePath, paths.rollback);+ renameWithRetry(paths.work, dbFilePath);+ }+ restrictDbFilePermissions(dbFilePath);+ } catch (error) {+ throw new DbSlimmingMaintenanceError('replacement-failed', 'database replacement failed', true, {+ cause: error,+ });+ }+}++function restoreOriginalDatabase(+ dbFilePath: string,+ paths: MaintenancePaths,+ log: DbSlimmingMaintenanceLog,+): void {+ removeSidecars(dbFilePath);+ const replacementWasInstalled = fs.existsSync(dbFilePath) && !fs.existsSync(paths.work);+ if (paths.defaultDirectoryBackup) {+ const backup = paths.backupFinal;+ if (!backup) throw new Error('default backup path is missing during rollback');+ if ((!fs.existsSync(dbFilePath) || replacementWasInstalled) && !fs.existsSync(backup)) {+ throw new Error('original database backup is missing during rollback');+ }+ if (!fs.existsSync(dbFilePath) || replacementWasInstalled) {+ if (replacementWasInstalled) renameWithRetry(dbFilePath, paths.work);+ renameWithRetry(backup, dbFilePath);+ }+ if (paths.backupPrevious && fs.existsSync(paths.backupPrevious)) {+ renameWithRetry(paths.backupPrevious, backup);+ }+ } else if (!fs.existsSync(dbFilePath) || replacementWasInstalled) {+ if (!fs.existsSync(paths.rollback)) {+ throw new Error('original database rollback file is missing');+ }+ if (replacementWasInstalled) renameWithRetry(dbFilePath, paths.work);+ renameWithRetry(paths.rollback, dbFilePath);+ }+ if (!fs.existsSync(dbFilePath) || !verifyDatabaseFile(dbFilePath)) {+ throw new Error('original database could not be restored');+ }+ restrictDbFilePermissions(dbFilePath);+ log.warn('database slimming replacement rolled back', { databaseName: path.basename(dbFilePath) });+}++function completedResult(+ request: DbSlimmingRequestRecord,+ paths: MaintenancePaths,+ dbFilePath: string,+ finishedAt: number,+): Extract<DbSlimmingResultRecord, { status: 'completed' }> {+ const afterBytes = estimateDbFilesBytes(dbFilePath);+ return {+ id: request.id,+ ownerId: request.ownerId,+ status: 'completed',+ finishedAt,+ archiveAgeMonths: request.archiveAgeMonths,+ deletedTaskCount: request.deletedTaskCount,+ archivedTaskCount: request.archivedTaskCount,+ messageCount: request.messageCount,+ beforeBytes: request.beforeBytes,+ afterBytes,+ reclaimedBytes: Math.max(0, request.beforeBytes - afterBytes),+ backupCreated: request.backupEnabled,+ ...(paths.backupLocation ? { backupLocation: paths.backupLocation } : {}),+ ...(request.backupEnabled && paths.backupFinal+ ? { backupPath: paths.backupFinal }+ : {}),+ };+}++function registerInstalledBackup(+ options: RunDbSlimmingMaintenanceOptions,+ request: DbSlimmingRequestRecord,+ paths: MaintenancePaths,+ alreadyVerified = false,+): void {+ if (!request.backupEnabled || !paths.backupFinal) return;+ if (!alreadyVerified && !verifyDatabaseFile(paths.backupFinal)) {+ throw new DbSlimmingMaintenanceError(+ 'backup-failed',+ 'installed database slimming backup did not pass integrity checks',+ );+ }+ try {+ adoptDbSlimmingBackup(options.userDataDir, request.ownerId, paths.backupFinal);+ } catch (error) {+ throw new DbSlimmingMaintenanceError(+ 'backup-failed',+ 'database slimming backup retention state could not be committed',+ true,+ { cause: error },+ );+ }+}++function triggerSql(db: Database.Database, triggerName: string): string | null {+ const row = db+ .prepare("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?")+ .get(triggerName) as { sql: string | null } | undefined;+ if (!row) return null;+ if (!row.sql) throw new Error(`trigger ${triggerName} has no restorable SQL`);+ return row.sql;+}++function verifyDatabaseFile(filePath: string): boolean {+ if (!fs.existsSync(filePath)) return false;+ let db: Database.Database | null = null;+ try {+ db = createBetterSqliteDatabase(filePath, { readonly: true, fileMustExist: true });+ verifyOpenDatabase(db);+ return true;+ } catch {+ return false;+ } finally {+ try {+ db?.close();+ } catch {+ // Best effort probe close.+ }+ }+}++function verifyOpenDatabase(db: Database.Database): void {+ const quickCheck = db.prepare('PRAGMA quick_check').get() as Record<string, unknown> | undefined;+ if (!quickCheck || Object.values(quickCheck)[0] !== 'ok') {+ throw new Error('PRAGMA quick_check failed');+ }+ const foreignKeyIssue = db.prepare('PRAGMA foreign_key_check').get();+ if (foreignKeyIssue) throw new Error('PRAGMA foreign_key_check failed');+}++function tableExists(db: Database.Database, tableName: string): boolean {+ return Boolean(+ db+ .prepare("SELECT 1 FROM sqlite_master WHERE type IN ('table', 'view') AND name = ?")+ .get(tableName),+ );+}++function finalizeCommittedCleanup(userDataDir: string, paths: MaintenancePaths): void {+ if (!cleanupAfterCommit(paths)) {+ throw new Error('database slimming committed artifacts could not be removed');+ }+ clearDbSlimmingRequestOrThrow(userDataDir);+}++function finalizeFailedCleanup(userDataDir: string, paths: MaintenancePaths): boolean {+ return cleanupUncommittedArtifacts(paths) && clearDbSlimmingRequest(userDataDir);+}++function clearDbSlimmingRequestOrThrow(userDataDir: string): void {+ if (!clearDbSlimmingRequest(userDataDir)) {+ throw new Error('database slimming request marker could not be cleared');+ }+}++function cleanupAfterCommit(paths: MaintenancePaths): boolean {+ const artifacts = [+ paths.work,+ `${paths.work}.vacuum`,+ paths.rollback,+ paths.backupPrevious,+ paths.backupCandidate,+ ].filter((candidate): candidate is string => candidate !== null);+ return artifacts.map((candidate) => removeDatabaseFamily(candidate)).every(Boolean);+}++function recoverInterruptedCustomBackupInstall(paths: MaintenancePaths): void {+ if (!paths.backupCandidate || !paths.backupFinal || !paths.backupPrevious) return;+ if (!fs.existsSync(paths.backupPrevious)) return;+ try {+ if (!fs.existsSync(paths.backupFinal) || !verifyDatabaseFile(paths.backupFinal)) {+ removeDatabaseFamily(paths.backupFinal);+ renameWithRetry(paths.backupPrevious, paths.backupFinal);+ }+ } catch (error) {+ throw new DbSlimmingMaintenanceError(+ 'backup-failed',+ 'interrupted database slimming backup could not be recovered',+ true,+ { cause: error },+ );+ }+}++function cleanupUncommittedArtifacts(paths: MaintenancePaths): boolean {+ const artifacts = [+ paths.work,+ `${paths.work}.vacuum`,+ paths.rollback,+ paths.backupPrevious,+ paths.backupCandidate,+ ].filter((candidate): candidate is string => candidate !== null);+ return artifacts.map((candidate) => removeDatabaseFamily(candidate)).every(Boolean);+}++function removeDatabaseFamily(filePath: string): boolean {+ return [filePath, ...SQLITE_SIDECAR_SUFFIXES.map((suffix) => `${filePath}${suffix}`)]+ .map((candidate) => removeExactFile(candidate))+ .every(Boolean);+}++function removeSidecars(filePath: string): void {+ for (const suffix of SQLITE_SIDECAR_SUFFIXES) removeExactFile(`${filePath}${suffix}`);+}++function removeExactFile(filePath: string): boolean {+ for (let attempt = 0; ; attempt += 1) {+ try {+ fs.rmSync(filePath, { force: true });+ return !fs.existsSync(filePath);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (attempt >= 3 || !['EBUSY', 'EACCES', 'EPERM'].includes(code ?? '')) {+ return !fs.existsSync(filePath);+ }+ Atomics.wait(+ new Int32Array(new SharedArrayBuffer(4)),+ 0,+ 0,+ 20 * (attempt + 1),+ );+ }+ }+}++function renameWithRetry(from: string, to: string): void {+ for (let attempt = 0; ; attempt += 1) {+ try {+ fs.renameSync(from, to);+ return;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (attempt >= 3 || !['EBUSY', 'EACCES', 'ENOTEMPTY'].includes(code ?? '')) throw error;+ Atomics.wait(+ new Int32Array(new SharedArrayBuffer(4)),+ 0,+ 0,+ 20 * (attempt + 1),+ );+ }+ }+}++function directoryFreeBytes(directory: string): number | null {+ try {+ if (typeof fs.statfsSync !== 'function') return null;+ const stat = fs.statfsSync(directory);+ return stat.bsize * stat.bavail;+ } catch {+ return null;+ }+}++function pathsEqual(left: string, right: string): boolean {+ if (process.platform === 'win32') return left.toLowerCase() === right.toLowerCase();+ return left === right;+}++function directoriesShareVolume(left: string, right: string): boolean {+ if (process.platform === 'win32') {+ return pathsEqual(path.parse(path.resolve(left)).root, path.parse(path.resolve(right)).root);+ }+ try {+ return fs.statSync(left).dev === fs.statSync(right).dev;+ } catch {+ // On platforms/filesystems where device ids are unavailable, a matching+ // volume root is the safest conservative fallback for the common case.+ const leftRoot = path.parse(path.resolve(left)).root;+ const rightRoot = path.parse(path.resolve(right)).root;+ return pathsEqual(leftRoot, rightRoot);+ }+}++function normalizeMaintenanceError(error: unknown): DbSlimmingMaintenanceError {+ if (error instanceof DbSlimmingMaintenanceError) return error;+ return new DbSlimmingMaintenanceError(+ 'cleanup-failed',+ error instanceof Error ? error.message : String(error),+ true,+ { cause: error },+ );+}diff --git a/apps/desktop/src/main/localDb/dbSlimmingMaintenanceProcess.ts b/apps/desktop/src/main/localDb/dbSlimmingMaintenanceProcess.tsnew file mode 100644index 0000000000..ec632a369e--- /dev/null+++ b/apps/desktop/src/main/localDb/dbSlimmingMaintenanceProcess.ts@@ -0,0 +1,87 @@+import fs from 'node:fs';++import { runDbSlimmingMaintenance } from './dbSlimmingMaintenance';+import type {+ DbSlimmingProcessCommand,+ DbSlimmingProcessInput,+ DbSlimmingProcessMessage,+} from './dbSlimmingProcessProtocol';++interface ParentPortLike {+ postMessage(message: DbSlimmingProcessMessage): void;+ on(event: 'message', listener: (event: { data: unknown }) => void): void;+}++const processPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;+if (!processPort) throw new Error('database cleanup process requires an Electron parent port');++let started = false;+let releaseCommit: (() => void) | null = null;++function post(message: DbSlimmingProcessMessage): void {+ processPort!.postMessage(message);+}++function postLog(level: 'info' | 'warn' | 'error', message: string, meta?: unknown): void {+ try {+ post({ type: 'log', level, message, meta });+ } catch {+ post({ type: 'log', level, message });+ }+}++async function run(input: DbSlimmingProcessInput): Promise<void> {+ await runDbSlimmingMaintenance({+ ...input,+ loadVectorExtension: (db) => {+ if (!input.sqliteVecExtensionPath || !fs.existsSync(input.sqliteVecExtensionPath)) {+ return false;+ }+ try {+ db.loadExtension(input.sqliteVecExtensionPath);+ return true;+ } catch (error) {+ postLog('warn', 'database cleanup process could not load sqlite-vec', {+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ }+ },+ onProgress: (progress) => post({ type: 'progress', progress }),+ beforeReplacement: () =>+ new Promise<void>((resolve) => {+ releaseCommit = resolve;+ post({ type: 'commit-ready' });+ }),+ log: {+ info: (message, meta) => postLog('info', message, meta),+ warn: (message, meta) => postLog('warn', message, meta),+ error: (message, meta) => postLog('error', message, meta),+ },+ }).then(+ (outcome) => post({ type: 'result', outcome }),+ (error) =>+ post({+ type: 'error',+ error: {+ message: error instanceof Error ? error.message : String(error),+ stack: error instanceof Error ? error.stack : undefined,+ },+ }),+ );+}++processPort.on('message', (event) => {+ const command = event.data as Partial<DbSlimmingProcessCommand> | undefined;+ if (command?.type === 'commit') {+ const resolve = releaseCommit;+ releaseCommit = null;+ resolve?.();+ return;+ }+ if (command?.type !== 'start' || started || !command.input) return;+ started = true;+ void run(command.input);+});++post({ type: 'ready' });diff --git a/apps/desktop/src/main/localDb/dbSlimmingProcessProtocol.ts b/apps/desktop/src/main/localDb/dbSlimmingProcessProtocol.tsnew file mode 100644index 0000000000..05797462d8--- /dev/null+++ b/apps/desktop/src/main/localDb/dbSlimmingProcessProtocol.ts@@ -0,0 +1,27 @@+import type { DbSlimmingMaintenanceProgress } from '../../shared/localDbMaintenance';+import type { RunDbSlimmingMaintenanceOutcome } from './dbSlimmingMaintenance';+import type { DbSlimmingRequestRecord } from './maintenanceStore';++export interface DbSlimmingProcessInput {+ userDataDir: string;+ dbFilePath: string;+ request: DbSlimmingRequestRecord;+ sqliteVecExtensionPath?: string;+}++export type DbSlimmingProcessCommand =+ | { type: 'start'; input: DbSlimmingProcessInput }+ | { type: 'commit' };++export type DbSlimmingProcessMessage =+ | { type: 'ready' }+ | { type: 'progress'; progress: DbSlimmingMaintenanceProgress }+ | { type: 'commit-ready' }+ | {+ type: 'log';+ level: 'info' | 'warn' | 'error';+ message: string;+ meta?: unknown;+ }+ | { type: 'result'; outcome: RunDbSlimmingMaintenanceOutcome }+ | { type: 'error'; error: { message: string; stack?: string } };diff --git a/apps/desktop/src/main/localDb/dbSlimmingStartup.ts b/apps/desktop/src/main/localDb/dbSlimmingStartup.tsnew file mode 100644index 0000000000..36a3b0f6a8--- /dev/null+++ b/apps/desktop/src/main/localDb/dbSlimmingStartup.ts@@ -0,0 +1,202 @@+import type Database from 'better-sqlite3';++import type { DbSlimmingResultRecord } from './maintenanceStore';+import type {+ RunDbSlimmingMaintenanceOptions,+ RunDbSlimmingMaintenanceOutcome,+} from './dbSlimmingMaintenance';+import { discardCancelledDbSlimmingMaintenance } from './dbSlimmingMaintenance';+import {+ DbSlimmingCancelledError,+ DbSlimmingWorkerPreReplacementError,+ DbSlimmingWorkerStartupError,+ runDbSlimmingMaintenanceInWorker,+} from './dbSlimmingWorkerClient';+import { beginDbSlimmingStartupProgress } from './dbSlimmingStartupState';+import {+ clearDbSlimmingRequest,+ InvalidDbSlimmingRequestMarkerError,+ readDbSlimmingRequest,+ writeDbSlimmingResult,+} from './maintenanceStore';++interface DbSlimmingStartupLog {+ info(message: string, meta?: unknown): void;+ error(message: string, meta?: unknown): void;+ warn(message: string, meta?: unknown): void;+}++export interface RunPendingDbSlimmingAtStartupOptions {+ userDataDir: string;+ dbFilePath: string;+ ownerId: string;+ leaseKind: 'reader' | 'writer';+ loadVectorExtension: (db: Database.Database) => boolean;+ log: DbSlimmingStartupLog;+ now?: () => number;+ readRequest?: typeof readDbSlimmingRequest;+ runMaintenance?: (+ options: RunDbSlimmingMaintenanceOptions,+ ) => Promise<RunDbSlimmingMaintenanceOutcome>;+}++export type PendingDbSlimmingStartupOutcome =+ | { handled: false; originalDatabaseReady: true }+ | {+ handled: true;+ result: DbSlimmingResultRecord;+ originalDatabaseReady: boolean;+ };++/**+ * Consumes the cross-restart marker only after the schema lease is acquired and+ * before the normal database connection is opened. A reader lease records a+ * safe failure instead of attempting any file replacement.+ */+export async function runPendingDbSlimmingAtStartup(+ options: RunPendingDbSlimmingAtStartupOptions,+): Promise<PendingDbSlimmingStartupOutcome> {+ let request: ReturnType<typeof readDbSlimmingRequest> = null;+ try {+ request = (options.readRequest ?? readDbSlimmingRequest)(options.userDataDir);+ } catch (error) {+ if (!(error instanceof InvalidDbSlimmingRequestMarkerError)) {+ options.log.error('database slimming request marker could not be read', {+ error: error instanceof Error ? error.message : String(error),+ });+ throw error;+ }+ options.log.error('invalid database slimming request marker was discarded', {+ error: error instanceof Error ? error.message : String(error),+ });+ clearDbSlimmingRequest(options.userDataDir);+ return { handled: false, originalDatabaseReady: true };+ }++ if (!request || request.ownerId !== options.ownerId) {+ return { handled: false, originalDatabaseReady: true };+ }++ if (options.leaseKind !== 'writer') {+ if (request.phase !== 'scheduled') {+ options.log.error('database slimming recovery requires the writer lease', {+ requestId: request.id,+ phase: request.phase,+ });+ throw new Error('database slimming recovery requires the writer lease');+ }+ const result: DbSlimmingResultRecord = {+ id: request.id,+ ownerId: request.ownerId,+ status: 'failed',+ finishedAt: (options.now ?? Date.now)(),+ archiveAgeMonths: request.archiveAgeMonths,+ reason: 'database-in-use',+ originalDatabaseRestored: true,+ };+ let resultPersisted = false;+ try {+ writeDbSlimmingResult(options.userDataDir, result);+ resultPersisted = true;+ } catch (error) {+ options.log.warn('database slimming in-use result could not be persisted', {+ requestId: request.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (resultPersisted && !clearDbSlimmingRequest(options.userDataDir)) {+ options.log.error('database slimming in-use request marker could not be cleared', {+ requestId: request.id,+ });+ throw new Error('database slimming request marker could not be cleared');+ }+ options.log.warn('database slimming skipped because this startup does not own the writer lease', {+ requestId: request.id,+ });+ return { handled: true, result, originalDatabaseReady: true };+ }++ const runMaintenance = options.runMaintenance ?? runDbSlimmingMaintenanceInWorker;+ const progressJob = beginDbSlimmingStartupProgress(request, options.now ?? Date.now);+ let maintenance: RunDbSlimmingMaintenanceOutcome;+ try {+ try {+ maintenance = await runMaintenance({+ userDataDir: options.userDataDir,+ dbFilePath: options.dbFilePath,+ request,+ loadVectorExtension: options.loadVectorExtension,+ log: options.log,+ signal: progressJob.signal,+ onProgress: progressJob.update,+ });+ } catch (error) {+ if (error instanceof DbSlimmingCancelledError) {+ try {+ discardCancelledDbSlimmingMaintenance(options.userDataDir, options.dbFilePath, request);+ } catch (cleanupError) {+ options.log.error('database cleanup cancellation could not be committed', {+ requestId: request.id,+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),+ });+ throw cleanupError;+ }+ options.log.info('database cleanup cancelled before replacement', {+ requestId: request.id,+ });+ return { handled: false, originalDatabaseReady: true };+ }+ if (+ !(error instanceof DbSlimmingWorkerStartupError) &&+ !(error instanceof DbSlimmingWorkerPreReplacementError)+ ) {+ throw error;+ }+ const result: DbSlimmingResultRecord = {+ id: request.id,+ ownerId: request.ownerId,+ status: 'failed',+ finishedAt: (options.now ?? Date.now)(),+ archiveAgeMonths: request.archiveAgeMonths,+ reason: 'cleanup-failed',+ originalDatabaseRestored: true,+ };+ let resultPersisted = false;+ try {+ writeDbSlimmingResult(options.userDataDir, result);+ resultPersisted = true;+ } catch (persistError) {+ options.log.warn('database cleanup process failure could not be persisted', {+ requestId: request.id,+ error: persistError instanceof Error ? persistError.message : String(persistError),+ });+ }+ if (resultPersisted) {+ if (error instanceof DbSlimmingWorkerPreReplacementError) {+ try {+ discardCancelledDbSlimmingMaintenance(options.userDataDir, options.dbFilePath, request);+ } catch (cleanupError) {+ options.log.error('failed database cleanup artifacts could not be fully removed', {+ requestId: request.id,+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),+ });+ throw cleanupError;+ }+ } else if (!clearDbSlimmingRequest(options.userDataDir)) {+ options.log.error('database cleanup process failure request marker could not be cleared', {+ requestId: request.id,+ });+ throw new Error('database slimming request marker could not be cleared');+ }+ }+ options.log.error('database cleanup process failed before replacement', {+ requestId: request.id,+ error: error.message,+ });+ return { handled: true, result, originalDatabaseReady: true };+ }+ return { handled: true, ...maintenance };+ } finally {+ progressJob.finish();+ }+}diff --git a/apps/desktop/src/main/localDb/dbSlimmingStartupState.ts b/apps/desktop/src/main/localDb/dbSlimmingStartupState.tsnew file mode 100644index 0000000000..6c592766d2--- /dev/null+++ b/apps/desktop/src/main/localDb/dbSlimmingStartupState.ts@@ -0,0 +1,126 @@+import type {+ DbSlimmingMaintenanceProgress,+ DbSlimmingStartupProgress,+} from '../../shared/localDbMaintenance';+import type { DbSlimmingRequestRecord } from './maintenanceStore';++const ESTIMATED_BYTES_PER_SECOND = 96 * 1024 * 1024;+const MIN_ESTIMATED_TOTAL_MS = 12_000;+const MAX_ESTIMATED_TOTAL_MS = 60 * 60 * 1000;++type ProgressListener = (progress: DbSlimmingStartupProgress | null) => void;++interface ActiveProgressJob {+ state: DbSlimmingStartupProgress;+ abortController: AbortController;+}++export interface DbSlimmingStartupProgressJob {+ signal: AbortSignal;+ update(progress: DbSlimmingMaintenanceProgress): void;+ finish(): void;+}++let activeJob: ActiveProgressJob | null = null;+const listeners = new Set<ProgressListener>();++function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}++function emit(progress: DbSlimmingStartupProgress | null): void {+ for (const listener of listeners) {+ try {+ listener(progress ? { ...progress } : null);+ } catch {+ // A presentation listener must never affect database maintenance.+ }+ }+}++function initialEstimatedTotalMs(databaseBytes: number): number {+ return clamp(+ Math.round((Math.max(0, databaseBytes) / ESTIMATED_BYTES_PER_SECOND) * 1000),+ MIN_ESTIMATED_TOTAL_MS,+ MAX_ESTIMATED_TOTAL_MS,+ );+}++export function beginDbSlimmingStartupProgress(+ request: DbSlimmingRequestRecord,+ now: () => number = Date.now,+): DbSlimmingStartupProgressJob {+ if (activeJob) throw new Error('database cleanup startup progress is already active');+ const startedAt = now();+ const abortController = new AbortController();+ const job: ActiveProgressJob = {+ abortController,+ state: {+ requestId: request.id,+ phase: 'preparing',+ progress: 1,+ cancellable: request.phase === 'scheduled',+ startedAt,+ updatedAt: startedAt,+ estimatedTotalMs: initialEstimatedTotalMs(request.beforeBytes),+ },+ };+ activeJob = job;+ emit(job.state);++ return {+ signal: abortController.signal,+ update(progress) {+ if (activeJob !== job || abortController.signal.aborted) return;+ const updatedAt = now();+ const nextProgress = clamp(Math.max(job.state.progress, progress.progress), 0, 100);+ let estimatedTotalMs = job.state.estimatedTotalMs;+ const elapsedMs = Math.max(0, updatedAt - startedAt);+ if (nextProgress >= 15 && nextProgress < 96 && elapsedMs >= 1_000) {+ const observedTotalMs = (elapsedMs * 100) / nextProgress;+ estimatedTotalMs = clamp(+ Math.round(estimatedTotalMs * 0.7 + observedTotalMs * 0.3),+ elapsedMs + 1_000,+ MAX_ESTIMATED_TOTAL_MS,+ );+ }+ job.state = {+ ...job.state,+ ...progress,+ progress: nextProgress,+ updatedAt,+ estimatedTotalMs,+ };+ emit(job.state);+ },+ finish() {+ if (activeJob !== job) return;+ activeJob = null;+ emit(null);+ },+ };+}++export function getDbSlimmingStartupProgress(): DbSlimmingStartupProgress | null {+ return activeJob ? { ...activeJob.state } : null;+}++export function cancelDbSlimmingStartupProgress(): boolean {+ if (!activeJob || !activeJob.state.cancellable || activeJob.abortController.signal.aborted) {+ return false;+ }+ activeJob.state = {+ ...activeJob.state,+ phase: 'cancelling',+ cancellable: false,+ updatedAt: Date.now(),+ };+ emit(activeJob.state);+ activeJob.abortController.abort();+ return true;+}++export function subscribeDbSlimmingStartupProgress(listener: ProgressListener): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}diff --git a/apps/desktop/src/main/localDb/dbSlimmingWorkerClient.ts b/apps/desktop/src/main/localDb/dbSlimmingWorkerClient.tsnew file mode 100644index 0000000000..26aeb97138--- /dev/null+++ b/apps/desktop/src/main/localDb/dbSlimmingWorkerClient.ts@@ -0,0 +1,371 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { utilityProcess } from 'electron';++import type {+ RunDbSlimmingMaintenanceOptions,+ RunDbSlimmingMaintenanceOutcome,+} from './dbSlimmingMaintenance';+import {+ BETTER_SQLITE_NATIVE_BINDING_ENV,+ resolveBetterSqliteModuleEntry,+ resolveBetterSqliteNativeBinding,+} from './betterSqliteFactory';+import type {+ DbSlimmingProcessCommand,+ DbSlimmingProcessMessage,+} from './dbSlimmingProcessProtocol';+import { resolveSqliteVecExtPath } from './sqliteVecLoader';++const BETTER_SQLITE_MODULE_ENV = 'CINDY_DB_SLIMMING_BETTER_SQLITE_MODULE';+const VACUUM_PROGRESS_START = 58;+const VACUUM_PROGRESS_SPAN = 30;+export const DB_SLIMMING_WORKER_READY_TIMEOUT_MS = 30_000;+export const DB_SLIMMING_WORKER_TERMINATION_TIMEOUT_MS = 10_000;+const DB_SLIMMING_WORKER_INACTIVITY_BASE_MS = 5 * 60_000;+const DB_SLIMMING_WORKER_INACTIVITY_PER_GIB_MS = 2 * 60_000;+const DB_SLIMMING_WORKER_INACTIVITY_MAX_MS = 2 * 60 * 60_000;+const GIB_BYTES = 1024 ** 3;++interface DbSlimmingUtilityProcessLike {+ postMessage(message: DbSlimmingProcessCommand): void;+ on(event: 'message', listener: (message: unknown) => void): void;+ on(event: 'exit', listener: (code: number) => void): void;+ on(event: 'error', listener: (...args: unknown[]) => void): void;+ kill(): boolean;+}++/** The isolated process failed before acknowledging that maintenance could begin. */+export class DbSlimmingWorkerStartupError extends Error {+ constructor(message: string, options?: ErrorOptions) {+ super(message, options);+ this.name = 'DbSlimmingWorkerStartupError';+ }+}++export class DbSlimmingCancelledError extends Error {+ constructor() {+ super('database cleanup was cancelled');+ this.name = 'DbSlimmingCancelledError';+ }+}++/** The utility process stopped while only disposable copies had been touched. */+export class DbSlimmingWorkerPreReplacementError extends Error {+ constructor(message: string, options?: ErrorOptions) {+ super(message, options);+ this.name = 'DbSlimmingWorkerPreReplacementError';+ }+}++/** The caller may fail visibly, but must keep exclusive database access until exit. */+export class DbSlimmingWorkerTerminationUnconfirmedError extends Error {+ constructor(+ readonly terminationConfirmed: Promise<void>,+ options?: ErrorOptions,+ ) {+ super('database cleanup process termination was not confirmed', options);+ this.name = 'DbSlimmingWorkerTerminationUnconfirmedError';+ }+}++/** Keeps an external exclusivity guard alive until the utility process really exits. */+export function deferReleaseUntilDbSlimmingWorkerTermination(+ error: unknown,+ release: () => void,+): boolean {+ if (!(error instanceof DbSlimmingWorkerTerminationUnconfirmedError)) return false;+ void error.terminationConfirmed.then(release);+ return true;+}++/** Allows large databases proportionally more silent native-call time without permitting a hang forever. */+export function dbSlimmingWorkerInactivityTimeoutMs(beforeBytes: number): number {+ const databaseBytes = Number.isFinite(beforeBytes) ? Math.max(0, beforeBytes) : 0;+ return Math.min(+ DB_SLIMMING_WORKER_INACTIVITY_MAX_MS,+ DB_SLIMMING_WORKER_INACTIVITY_BASE_MS ++ Math.ceil((databaseBytes / GIB_BYTES) * DB_SLIMMING_WORKER_INACTIVITY_PER_GIB_MS),+ );+}++function forkDbSlimmingUtilityProcess(): DbSlimmingUtilityProcessLike {+ const env: NodeJS.ProcessEnv = {};+ for (const key of [+ 'PATH',+ 'SystemRoot',+ 'WINDIR',+ 'TEMP',+ 'TMP',+ 'TMPDIR',+ 'LANG',+ 'LC_ALL',+ ] as const) {+ if (process.env[key] !== undefined) env[key] = process.env[key];+ }+ const moduleEntry = resolveBetterSqliteModuleEntry();+ if (moduleEntry) env[BETTER_SQLITE_MODULE_ENV] = moduleEntry;+ const nativeBinding = resolveBetterSqliteNativeBinding();+ if (nativeBinding) env[BETTER_SQLITE_NATIVE_BINDING_ENV] = nativeBinding;+ return utilityProcess.fork(path.join(__dirname, 'dbSlimmingMaintenanceProcess.js'), [], {+ cwd: os.tmpdir(),+ env,+ serviceName: 'cindy-database-cleanup',+ stdio: 'ignore',+ });+}++function isProgressMessage(+ value: unknown,+): value is Extract<DbSlimmingProcessMessage, { type: 'progress' }> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const message = value as Partial<Extract<DbSlimmingProcessMessage, { type: 'progress' }>>;+ const progress = message.progress;+ return (+ message.type === 'progress' &&+ Boolean(progress) &&+ typeof progress!.progress === 'number' &&+ Number.isFinite(progress!.progress) &&+ typeof progress!.cancellable === 'boolean' &&+ [+ 'preparing',+ 'backing-up',+ 'copying',+ 'cleaning',+ 'compacting',+ 'verifying',+ 'finalizing',+ ].includes(String(progress!.phase))+ );+}++/** Keeps DELETE / FTS / VACUUM outside Electron Main and makes long native calls cancellable. */+export function runDbSlimmingMaintenanceInWorker(+ options: RunDbSlimmingMaintenanceOptions,+ fork: () => DbSlimmingUtilityProcessLike = forkDbSlimmingUtilityProcess,+): Promise<RunDbSlimmingMaintenanceOutcome> {+ let child: DbSlimmingUtilityProcessLike;+ try {+ child = fork();+ } catch (error) {+ throw new DbSlimmingWorkerStartupError('database cleanup process could not start', {+ cause: error,+ });+ }++ return new Promise((resolve, reject) => {+ let settled = false;+ let ready = false;+ let exited = false;+ let cancelRequested = false;+ let terminationRequested = false;+ let commitSent = false;+ let timeoutError: Error | null = null;+ let cancellable = options.request.phase === 'scheduled';+ let lastProgress = 0;+ let lastPhase: string | null = null;+ let watchdogTimer: NodeJS.Timeout | null = null;+ let terminationTimer: NodeJS.Timeout | null = null;+ const vacuumPath = `${options.dbFilePath}.slimming-${options.request.id}.work.vacuum`;+ const inactivityTimeoutMs = dbSlimmingWorkerInactivityTimeoutMs(options.request.beforeBytes);+ let confirmTermination!: () => void;+ const terminationConfirmed = new Promise<void>((resolveTermination) => {+ confirmTermination = resolveTermination;+ });+ const terminationUnconfirmedError = (cause: unknown): Error =>+ new DbSlimmingWorkerTerminationUnconfirmedError(terminationConfirmed, { cause });+ const estimatedAfterBytes = Math.max(+ 16 * 1024 * 1024,+ options.request.beforeBytes - (options.request.estimatedMessageBytes ?? options.request.beforeBytes / 2),+ );++ const finish = (complete: () => void): void => {+ if (settled) return;+ settled = true;+ clearInterval(vacuumProgressTimer);+ if (watchdogTimer) clearTimeout(watchdogTimer);+ if (terminationTimer) clearTimeout(terminationTimer);+ options.signal?.removeEventListener('abort', cancel);+ if (!exited && !terminationRequested) {+ try {+ child.kill();+ } catch {+ // The one-shot utility process may already have exited after its result.+ }+ }+ complete();+ };++ const fail = (error: Error): void => {+ finish(() => {+ if (!ready) {+ reject(+ new DbSlimmingWorkerStartupError('database cleanup process failed before ready', {+ cause: error,+ }),+ );+ return;+ }+ if (!commitSent) {+ reject(+ new DbSlimmingWorkerPreReplacementError(+ 'database cleanup process stopped before replacement',+ { cause: error },+ ),+ );+ return;+ }+ reject(error);+ });+ };++ const rejectWithoutAssumingDatabaseSafety = (error: Error): void => {+ finish(() => reject(error));+ };++ const armTerminationConfirmation = (): void => {+ if (settled) return;+ if (terminationTimer) clearTimeout(terminationTimer);+ terminationTimer = setTimeout(() => {+ if (settled || exited) return;+ const cause = timeoutError ?? new Error('database cleanup cancellation did not stop');+ timeoutError = null;+ rejectWithoutAssumingDatabaseSafety(terminationUnconfirmedError(cause));+ }, DB_SLIMMING_WORKER_TERMINATION_TIMEOUT_MS);+ terminationTimer.unref?.();+ };++ const requestTermination = (error: Error): void => {+ if (settled || terminationRequested) return;+ terminationRequested = true;+ timeoutError = error;+ if (watchdogTimer) clearTimeout(watchdogTimer);+ try {+ child.kill();+ } catch (killError) {+ timeoutError = null;+ rejectWithoutAssumingDatabaseSafety(terminationUnconfirmedError(killError));+ return;+ }+ armTerminationConfirmation();+ };++ const armWatchdog = (timeoutMs: number, stage: string): void => {+ if (settled || terminationRequested) return;+ if (watchdogTimer) clearTimeout(watchdogTimer);+ watchdogTimer = setTimeout(() => {+ requestTermination(new Error(`database cleanup process timed out while ${stage}`));+ }, timeoutMs);+ watchdogTimer.unref?.();+ };++ const cancel = (): void => {+ if (settled || !cancellable || cancelRequested) return;+ cancelRequested = true;+ terminationRequested = true;+ if (watchdogTimer) clearTimeout(watchdogTimer);+ try {+ child.kill();+ } catch (error) {+ rejectWithoutAssumingDatabaseSafety(terminationUnconfirmedError(error));+ return;+ }+ armTerminationConfirmation();+ };++ const vacuumProgressTimer = setInterval(() => {+ if (settled || lastPhase !== 'compacting') return;+ try {+ const outputBytes = fs.statSync(vacuumPath).size;+ const fraction = Math.min(0.95, outputBytes / estimatedAfterBytes);+ const progress = VACUUM_PROGRESS_START + fraction * VACUUM_PROGRESS_SPAN;+ if (progress <= lastProgress) return;+ lastProgress = progress;+ armWatchdog(inactivityTimeoutMs, 'compacting the database');+ options.onProgress?.({ phase: 'compacting', progress, cancellable: true });+ } catch {+ // VACUUM INTO creates its output lazily; absence before the first page is normal.+ }+ }, 500);+ vacuumProgressTimer.unref?.();++ child.on('message', (message: unknown) => {+ if (terminationRequested) return;+ if (!message || typeof message !== 'object' || Array.isArray(message)) return;+ const typed = message as DbSlimmingProcessMessage;+ if (typed.type === 'ready') {+ if (ready || cancelRequested) return;+ ready = true;+ armWatchdog(inactivityTimeoutMs, 'running database cleanup');+ child.postMessage({+ type: 'start',+ input: {+ userDataDir: options.userDataDir,+ dbFilePath: options.dbFilePath,+ request: options.request,+ sqliteVecExtensionPath: resolveSqliteVecExtPath(),+ },+ });+ return;+ }+ if (isProgressMessage(typed)) {+ lastProgress = Math.max(lastProgress, typed.progress.progress);+ lastPhase = typed.progress.phase;+ cancellable = typed.progress.cancellable;+ armWatchdog(inactivityTimeoutMs, `running phase ${typed.progress.phase}`);+ options.onProgress?.({ ...typed.progress, progress: lastProgress });+ return;+ }+ if (typed.type === 'commit-ready') {+ if (cancelRequested) return;+ cancellable = false;+ commitSent = true;+ armWatchdog(inactivityTimeoutMs, 'committing the cleaned database');+ child.postMessage({ type: 'commit' });+ return;+ }+ if (typed.type === 'log') {+ options.log[typed.level](typed.message, typed.meta);+ return;+ }+ if (typed.type === 'error') {+ const error = new Error(typed.error.message);+ if (typed.error.stack) error.stack = typed.error.stack;+ fail(error);+ return;+ }+ if (typed.type === 'result') {+ finish(() => resolve(typed.outcome));+ }+ });+ child.on('error', (...args) => {+ // A process error does not prove the child has exited. Keep the writer+ // lease and wait for exit (or the fail-closed termination guard).+ if (terminationRequested) return;+ requestTermination(+ new Error(`database cleanup process error: ${args.map(String).join(' ')}`),+ );+ });+ child.on('exit', (code) => {+ exited = true;+ confirmTermination();+ const pendingTimeout = timeoutError;+ timeoutError = null;+ if (cancelRequested) {+ finish(() => reject(new DbSlimmingCancelledError()));+ return;+ }+ if (pendingTimeout) {+ fail(pendingTimeout);+ return;+ }+ if (!settled) fail(new Error(`database cleanup process exited with code ${code}`));+ });++ options.signal?.addEventListener('abort', cancel, { once: true });+ if (options.signal?.aborted) cancel();+ else armWatchdog(DB_SLIMMING_WORKER_READY_TIMEOUT_MS, 'waiting for readiness');+ });+}diff --git a/apps/desktop/src/main/localDb/dbSlimmingWorkerLogger.ts b/apps/desktop/src/main/localDb/dbSlimmingWorkerLogger.tsnew file mode 100644index 0000000000..909fe9ea91--- /dev/null+++ b/apps/desktop/src/main/localDb/dbSlimmingWorkerLogger.ts@@ -0,0 +1,17 @@+const noop = (): void => undefined;++/** Worker-local logger shim; structured maintenance logs travel through parentPort. */+export function createLogger() {+ return {+ trace: noop,+ debug: noop,+ info: noop,+ warn: noop,+ error: noop,+ fatal: noop,+ };+}++export function maskPath(): string {+ return '<database-path>';+}diff --git a/apps/desktop/src/main/localDb/devDbSlimmingRelaunch.ts b/apps/desktop/src/main/localDb/devDbSlimmingRelaunch.tsnew file mode 100644index 0000000000..49558c167a--- /dev/null+++ b/apps/desktop/src/main/localDb/devDbSlimmingRelaunch.ts@@ -0,0 +1,33 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++const DEV_RELAUNCH_SIGNAL_ENV = 'XDT_DESKTOP_DEV_RELAUNCH_SIGNAL_FILE';++/** Signals the repository dev runner without launching Electron outside Forge/Vite. */+export function writeDbSlimmingDevRelaunchSignal(+ requestId: string,+ options: { signalPath?: string; tempDir?: string } = {},+): boolean {+ const signalPath = options.signalPath ?? process.env[DEV_RELAUNCH_SIGNAL_ENV];+ if (!signalPath || !path.isAbsolute(signalPath)) return false;++ const tempDir = path.resolve(options.tempDir ?? os.tmpdir());+ const resolvedSignalPath = path.resolve(signalPath);+ const relativePath = path.relative(tempDir, resolvedSignalPath);+ if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) return false;++ const candidatePath = `${resolvedSignalPath}.${process.pid}.tmp`;+ try {+ fs.writeFileSync(+ candidatePath,+ `${JSON.stringify({ version: 1, requestId, createdAt: Date.now() })}\n`,+ { mode: 0o600 },+ );+ fs.renameSync(candidatePath, resolvedSignalPath);+ return true;+ } catch {+ fs.rmSync(candidatePath, { force: true });+ return false;+ }+}diff --git a/apps/desktop/src/main/localDb/index.ts b/apps/desktop/src/main/localDb/index.tsindex ee26bd2510..cc0bb46e3e 100644--- a/apps/desktop/src/main/localDb/index.ts+++ b/apps/desktop/src/main/localDb/index.ts@@ -54,7 +54,6 @@ import {readSchemaVersion,} from './migrationRunner';import {- acquireSchemaMigrationWriterLease,acquireSchemaStartupLease,SchemaMigrationReaderLeaseLifecycle,type SchemaMigrationLease,@@ -65,9 +64,12 @@ import {buildSharedDbCompatibilityMessage,} from './sharedDbCompatibilityMessage';import { shouldShowNativeFatalDialog, type EnsureReadyErrorCode } from './fatalDialogPolicy';+import { runPendingDbSlimmingAtStartup } from './dbSlimmingStartup';+import { deferReleaseUntilDbSlimmingWorkerTermination } from './dbSlimmingWorkerClient';import { createLogger } from '../logger';import { recordDesktopDevLocalDbStartupResult } from '../devStartupStatus';+import { t } from '../i18n';const log = createLogger('localDb');@@ -107,6 +109,10 @@ function dbPath(userId: string): string {return path.join(app.getPath('userData'), `${BRAND_IDENTITY.dbFilePrefix}-${userId}.db`);}+export function getDbPathForUser(userId: string): string {+ return dbPath(userId);+}+export type EnsureReadyResult =| { ready: true }| {@@ -185,9 +191,14 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {readerLeaseAcquiredThisCall = startupLease.kind === 'reader' && startupLease.newlyAcquired;if (startupLease.kind === 'writer') startupWriterLease = startupLease.lease;- const releaseSchemaLeasesAfterFailure = (): void => {- startupWriterLease?.release();- startupWriterLease = null;+ const releaseSchemaLeasesAfterFailure = (error?: unknown): void => {+ if (startupWriterLease) {+ const heldWriterLease = startupWriterLease;+ if (!deferReleaseUntilDbSlimmingWorkerTermination(error, () => heldWriterLease.release())) {+ heldWriterLease.release();+ }+ startupWriterLease = null;+ }if (readerLeaseAcquiredThisCall) {schemaMigrationReaderLeaseLifecycle.release();}@@ -201,6 +212,38 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {}),);+ let maintenance: Awaited<ReturnType<typeof runPendingDbSlimmingAtStartup>>;+ try {+ maintenance = await runPendingDbSlimmingAtStartup({+ userDataDir: app.getPath('userData'),+ dbFilePath: filePath,+ ownerId: userId,+ leaseKind: startupLease.kind,+ loadVectorExtension: (maintenanceDb) => loadSqliteVec(maintenanceDb).loaded,+ log,+ });+ } catch (error) {+ const detail = error instanceof Error ? error.message : String(error);+ const message = t('localDbFatal.databaseCleanup.interruptedDescription');+ log.error('database cleanup startup failed unexpectedly', { detail });+ releaseSchemaLeasesAfterFailure(error);+ showFatalDialog(t('localDbFatal.databaseCleanup.interruptedTitle'), message, 'MIGRATE_FAILED');+ return { ready: false, error: { code: 'MIGRATE_FAILED', message } };+ }+ if (maintenance.handled && startupLease.kind === 'writer') {+ resetSqliteVecState();+ }+ if (!maintenance.originalDatabaseReady) {+ const message = t('localDbFatal.databaseCleanup.recoveryFailedDescription');+ showFatalDialog(+ t('localDbFatal.databaseCleanup.recoveryFailedTitle'),+ message,+ 'DB_CORRUPT_NO_BACKUP',+ );+ releaseSchemaLeasesAfterFailure();+ return { ready: false, error: { code: 'DB_CORRUPT_NO_BACKUP', message } };+ }+try {_db = openWithPragmas(filePath);} catch (err) {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/maintenance.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/maintenance.test.tsnew file mode 100644index 0000000000..3f6abe6e9a--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/maintenance.test.ts@@ -0,0 +1,281 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { DbClient } from '../../client/DbClient';+import { archiveCutoffForAge, createLocalDbMaintenanceIpcHandlers } from '../maintenance';+import {+ readDbSlimmingRequest,+ writeDbSlimmingRequest,+ writeDbSlimmingResult,+} from '../../maintenanceStore';++let tmpDir: string;+let dbFilePath: string;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-db-maintenance-ipc-'));+ dbFilePath = path.join(tmpDir, 'cindy-owner.db');+ fs.writeFileSync(dbFilePath, 'database-bytes');+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++function createHarness() {+ let owner = { ownerId: 'owner-1', scopeKey: 'scope-1' };+ let dbClientOwnerId: string | null = owner.ownerId;+ let canSchedule = true;+ const queryOne = vi.fn(async () => ({+ deletedTaskCount: 1,+ archivedTaskCount: 2,+ messageCount: 3,+ estimatedMessageBytes: 4_096,+ }));+ const selectBackupDirectory = vi.fn(async () => path.join(tmpDir, 'backups'));+ const confirmWithoutBackup = vi.fn(async () => true);+ const revealFile = vi.fn(async () => true);+ const relaunch = vi.fn();+ const handlers = createLocalDbMaintenanceIpcHandlers({+ captureOwner: () => ({ ...owner }),+ isOwnerCurrent: (snapshot) =>+ snapshot.ownerId === owner.ownerId && snapshot.scopeKey === owner.scopeKey,+ getDbClient: () => ({ queryOne } as unknown as DbClient),+ getDbClientOwnerId: () => dbClientOwnerId,+ getCurrentDbPath: () => dbFilePath,+ getUserDataDir: () => tmpDir,+ canSchedule: () => canSchedule,+ selectBackupDirectory,+ confirmWithoutBackup,+ revealFile,+ relaunch,+ });+ return {+ handlers,+ confirmWithoutBackup,+ queryOne,+ revealFile,+ relaunch,+ setOwner(next: { ownerId: string; scopeKey: string }) {+ owner = next;+ },+ setDbClientOwnerId(next: string | null) {+ dbClientOwnerId = next;+ },+ setCanSchedule(next: boolean) {+ canSchedule = next;+ },+ };+}++describe('local database maintenance IPC', () => {+ it('accepts only the fixed 7 day, 1 month, 3 month, and 6 month archive thresholds', async () => {+ const { handlers, queryOne } = createHarness();++ for (const archiveAgeMonths of ['7-days', 1, 3, 6] as const) {+ await expect(handlers.scan({ archiveAgeMonths })).resolves.toMatchObject({+ archiveAgeMonths,+ });+ }+ for (const archiveAgeMonths of [0, 1.5, 2, 7, 12, '7-day']) {+ await expect(+ handlers.scan({ archiveAgeMonths: archiveAgeMonths as never }),+ ).rejects.toThrow('[INVALID_PARAMS]');+ }+ expect(queryOne).toHaveBeenCalledTimes(4);+ });++ it('subtracts exactly seven days for the seven day archive threshold', () => {+ expect(archiveCutoffForAge(Date.UTC(2026, 2, 10, 12, 30), '7-days')).toBe(+ Date.UTC(2026, 2, 3, 12, 30),+ );+ });++ it('subtracts natural months and clamps dates at the end of shorter months', () => {+ expect(archiveCutoffForAge(Date.UTC(2026, 2, 31, 12, 30), 1)).toBe(+ Date.UTC(2026, 1, 28, 12, 30),+ );+ expect(archiveCutoffForAge(Date.UTC(2024, 2, 31, 12, 30), 1)).toBe(+ Date.UTC(2024, 1, 29, 12, 30),+ );+ });++ it('invalidates a scan when the owner scope changes before scheduling', async () => {+ const harness = createHarness();+ const scan = await harness.handlers.scan({ archiveAgeMonths: 3 });+ harness.setOwner({ ownerId: 'owner-1', scopeKey: 'scope-2' });++ await expect(+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: true }),+ ).rejects.toThrow('[PRECONDITION_FAILED]');+ expect(harness.relaunch).not.toHaveBeenCalled();+ });++ it('invalidates a custom-directory grant independently from a fresh scan', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-08-26T00:00:00.000Z'));+ const harness = createHarness();+ const directory = await harness.handlers.chooseBackupDirectory();+ expect(directory).toMatchObject({ selected: true });++ vi.advanceTimersByTime(29 * 60 * 1000);+ const scan = await harness.handlers.scan({ archiveAgeMonths: 3 });+ vi.advanceTimersByTime(2 * 60 * 1000);++ await expect(+ harness.handlers.schedule({+ scanId: scan.scanId,+ backupEnabled: true,+ backupDirectoryGrantId: directory.grantId,+ }),+ ).rejects.toThrow('[PRECONDITION_FAILED]');+ expect(harness.relaunch).not.toHaveBeenCalled();+ });++ it('requires a new scan after the scan grant expires', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-08-26T00:00:00.000Z'));+ const harness = createHarness();+ const scan = await harness.handlers.scan({ archiveAgeMonths: 3 });+ vi.advanceTimersByTime(31 * 60 * 1000);++ await expect(+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: true }),+ ).rejects.toThrow('[PRECONDITION_FAILED]');+ expect(harness.relaunch).not.toHaveBeenCalled();+ });++ it('does not schedule file replacement from a passive shared instance', async () => {+ const harness = createHarness();+ const scan = await harness.handlers.scan({ archiveAgeMonths: 3 });+ harness.setCanSchedule(false);++ await expect(+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: true }),+ ).rejects.toThrow('[PRECONDITION_FAILED]');+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(harness.relaunch).not.toHaveBeenCalled();+ });++ it('requires a native Main confirmation before scheduling without a backup', async () => {+ const harness = createHarness();+ harness.confirmWithoutBackup.mockResolvedValue(false);+ const scan = await harness.handlers.scan({ archiveAgeMonths: 3 });++ await expect(+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: false }),+ ).resolves.toEqual({ scheduled: false });++ expect(harness.confirmWithoutBackup).toHaveBeenCalledOnce();+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ expect(harness.relaunch).not.toHaveBeenCalled();+ });++ it('does not show the native no-backup confirmation when a backup is enabled', async () => {+ const harness = createHarness();+ const scan = await harness.handlers.scan({ archiveAgeMonths: '7-days' });++ await expect(+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: true }),+ ).resolves.toEqual({ scheduled: true });++ expect(harness.confirmWithoutBackup).not.toHaveBeenCalled();+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({+ archiveAgeMonths: '7-days',+ backupEnabled: true,+ });+ expect(harness.relaunch).toHaveBeenCalledExactlyOnceWith(scan.scanId);+ });++ it('does not restart or copy the database when the scan found nothing to clean', async () => {+ const harness = createHarness();+ harness.queryOne.mockResolvedValueOnce({+ deletedTaskCount: 0,+ archivedTaskCount: 0,+ messageCount: 0,+ estimatedMessageBytes: 0,+ });+ const scan = await harness.handlers.scan({ archiveAgeMonths: '7-days' });++ await expect(+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: false }),+ ).resolves.toEqual({ scheduled: false });++ expect(harness.confirmWithoutBackup).not.toHaveBeenCalled();+ expect(harness.relaunch).not.toHaveBeenCalled();+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();+ });++ it('does not overwrite another owner pending recovery marker', async () => {+ const harness = createHarness();+ const pending = {+ version: 1 as const,+ id: '9c5c7e99-6a6a-4d21-9152-4034a4959490',+ ownerId: 'owner-2',+ createdAt: 1_000,+ scannedAt: 900,+ archivedBeforeMs: 800,+ archiveAgeMonths: '7-days' as const,+ deletedTaskCount: 1,+ archivedTaskCount: 2,+ messageCount: 3,+ beforeBytes: 4_096,+ backupEnabled: true,+ phase: 'replacement-installed' as const,+ };+ writeDbSlimmingRequest(tmpDir, pending);+ const scan = await harness.handlers.scan({ archiveAgeMonths: '7-days' });++ await expect(+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: true }),+ ).rejects.toThrow('[PRECONDITION_FAILED]');++ expect(readDbSlimmingRequest(tmpDir)).toEqual(pending);+ expect(harness.relaunch).not.toHaveBeenCalled();+ });++ it('never exposes the privileged backup path to Renderer', async () => {+ const harness = createHarness();+ const backupPath = `${dbFilePath}.slimming-backup`;+ fs.writeFileSync(backupPath, 'backup');+ writeDbSlimmingResult(tmpDir, {+ id: '9c5c7e99-6a6a-4d21-9152-4034a4959490',+ ownerId: 'owner-1',+ status: 'completed',+ finishedAt: 3_000,+ archiveAgeMonths: 3,+ deletedTaskCount: 1,+ archivedTaskCount: 2,+ messageCount: 3,+ beforeBytes: 4_096,+ afterBytes: 2_048,+ reclaimedBytes: 2_048,+ backupCreated: true,+ backupLocation: 'database-directory',+ backupPath,+ });++ const result = harness.handlers.getLastResult();++ expect(result).toMatchObject({ status: 'completed', backupCreated: true });+ expect(result).not.toHaveProperty('ownerId');+ expect(result).not.toHaveProperty('backupPath');+ await expect(harness.handlers.openLastBackupDirectory()).resolves.toEqual({ opened: true });+ expect(harness.revealFile).toHaveBeenCalledWith(backupPath);+ });++ it('rechecks the live database owner before granting maintenance access', async () => {+ const harness = createHarness();+ harness.setDbClientOwnerId('owner-2');++ await expect(harness.handlers.scan({ archiveAgeMonths: 3 })).rejects.toThrow(+ '[PRECONDITION_FAILED]',+ );+ expect(harness.queryOne).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/maintenance.ts b/apps/desktop/src/main/localDb/ipc/maintenance.tsnew file mode 100644index 0000000000..055687be43--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/maintenance.ts@@ -0,0 +1,356 @@+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';++import type {+ DbSlimmingArchiveAge,+ DbSlimmingBackupDirectorySelection,+ DbSlimmingResult,+ DbSlimmingScanInput,+ DbSlimmingScanResult,+ DbSlimmingScheduleInput,+ DbSlimmingScheduleResult,+} from '../../../shared/localDbMaintenance';+import {+ DB_SLIMMING_ARCHIVE_AGE_OPTIONS,+} from '../../../shared/localDbMaintenance';+import { throwIpcError } from '../../utils/ipcValidate';+import type { DbClient } from '../client/DbClient';+import {+ dbSlimmingTemporaryBytesRequired,+ dbVolumeFreeBytes,+ estimateDbFilesBytes,+} from '../dbSlimmingMaintenance';+import {+ clearDbSlimmingResult,+ publicDbSlimmingResult,+ readDbSlimmingRequest,+ readDbSlimmingResult,+ type DbSlimmingResultRecord,+ writeDbSlimmingRequest,+} from '../maintenanceStore';++const GRANT_TTL_MS = 30 * 60 * 1000;++interface OwnerSnapshot {+ ownerId: string;+ scopeKey: string;+}++interface ScanGrant extends DbSlimmingScanResult {+ ownerId: string;+ scopeKey: string;+ expiresAt: number;+}++interface DirectoryGrant {+ ownerId: string;+ scopeKey: string;+ directory: string;+ expiresAt: number;+}++interface ScanAggregateRow {+ deletedTaskCount: number | null;+ archivedTaskCount: number | null;+ messageCount: number;+ estimatedMessageBytes: number | null;+}++export interface LocalDbMaintenanceIpcDeps {+ captureOwner(): OwnerSnapshot | null;+ isOwnerCurrent(snapshot: OwnerSnapshot): boolean;+ getDbClient(): DbClient;+ getDbClientOwnerId(): string | null;+ getCurrentDbPath(): string | null;+ getUserDataDir(): string;+ canSchedule(): boolean;+ selectBackupDirectory(): Promise<string | null>;+ confirmWithoutBackup(): Promise<boolean>;+ revealFile(filePath: string): Promise<boolean>;+ relaunch(requestId: string): void;+}++/** Main-owned grants keep Renderer-supplied ids from becoming path or time authorization. */+export function createLocalDbMaintenanceIpcHandlers(deps: LocalDbMaintenanceIpcDeps) {+ const scanGrants = new Map<string, ScanGrant>();+ const directoryGrants = new Map<string, DirectoryGrant>();+ const resultCache = new Map<string, DbSlimmingResultRecord>();+ const pendingScheduleIds = new Set<string>();++ const captureReadyOwner = (): OwnerSnapshot => {+ const owner = deps.captureOwner();+ if (!owner || deps.getDbClientOwnerId() !== owner.ownerId) {+ throwIpcError('PRECONDITION_FAILED', 'database maintenance requires a ready data owner');+ }+ return owner;+ };++ const assertOwnerCurrent = (owner: OwnerSnapshot): void => {+ if (!deps.isOwnerCurrent(owner) || deps.getDbClientOwnerId() !== owner.ownerId) {+ throwIpcError('PRECONDITION_FAILED', 'database owner changed during maintenance request');+ }+ };++ const pruneExpiredGrants = (): void => {+ const now = Date.now();+ for (const [id, grant] of scanGrants) {+ if (grant.expiresAt <= now) scanGrants.delete(id);+ }+ for (const [id, grant] of directoryGrants) {+ if (grant.expiresAt <= now) directoryGrants.delete(id);+ }+ };++ const loadResultForOwner = (ownerId: string): DbSlimmingResultRecord | null => {+ const cached = resultCache.get(ownerId);+ if (cached) return cached;+ const stored = readDbSlimmingResult(deps.getUserDataDir());+ if (!stored || stored.ownerId !== ownerId) return null;+ resultCache.set(ownerId, stored);+ clearDbSlimmingResult(deps.getUserDataDir());+ return stored;+ };++ return {+ async scan(input: DbSlimmingScanInput): Promise<DbSlimmingScanResult> {+ const archiveAgeMonths = validateArchiveAge(input?.archiveAgeMonths);+ const owner = captureReadyOwner();+ const scannedAt = Date.now();+ const archivedBeforeMs = archiveCutoffForAge(scannedAt, archiveAgeMonths);+ const row = await deps.getDbClient().queryOne<ScanAggregateRow>(+ `WITH target_sessions AS (+ SELECT id, status+ FROM sessions+ WHERE ((status = 'deleted' AND updated_at <= ?)+ OR (status = 'archived' AND updated_at <= ?))+ AND EXISTS (SELECT 1 FROM messages WHERE messages.session_id = sessions.id)+ )+ SELECT+ (SELECT COUNT(*) FROM target_sessions WHERE status = 'deleted') AS deletedTaskCount,+ (SELECT COUNT(*) FROM target_sessions WHERE status = 'archived') AS archivedTaskCount,+ (SELECT COUNT(*)+ FROM messages message+ JOIN target_sessions target ON target.id = message.session_id) AS messageCount,+ (SELECT COALESCE(SUM(+ length(CAST(message.id AS BLOB)) ++ length(CAST(message.client_id AS BLOB)) ++ length(CAST(message.role AS BLOB)) ++ length(CAST(message.content AS BLOB)) ++ COALESCE(length(CAST(message.tool_use_id AS BLOB)), 0) ++ COALESCE(length(CAST(message.agent_meta AS BLOB)), 0) ++ COALESCE(length(CAST(message.agent_kind AS BLOB)), 0)+ ), 0)+ FROM messages message+ JOIN target_sessions target ON target.id = message.session_id) AS estimatedMessageBytes`,+ [scannedAt, archivedBeforeMs],+ );+ assertOwnerCurrent(owner);+ const dbFilePath = deps.getCurrentDbPath();+ if (!dbFilePath || !fs.existsSync(dbFilePath)) {+ throwIpcError('PRECONDITION_FAILED', 'database path is unavailable');+ }+ const databaseBytes = estimateDbFilesBytes(dbFilePath);+ const scanId = randomUUID();+ const result: DbSlimmingScanResult = {+ scanId,+ archiveAgeMonths,+ scannedAt,+ archivedBeforeMs,+ deletedTaskCount: row?.deletedTaskCount ?? 0,+ archivedTaskCount: row?.archivedTaskCount ?? 0,+ messageCount: row?.messageCount ?? 0,+ estimatedMessageBytes: row?.estimatedMessageBytes ?? 0,+ databaseBytes,+ temporaryBytesRequired: dbSlimmingTemporaryBytesRequired(databaseBytes),+ databaseVolumeFreeBytes: dbVolumeFreeBytes(dbFilePath),+ };+ pruneExpiredGrants();+ scanGrants.set(scanId, {+ ...result,+ ownerId: owner.ownerId,+ scopeKey: owner.scopeKey,+ expiresAt: Date.now() + GRANT_TTL_MS,+ });+ return result;+ },++ async chooseBackupDirectory(): Promise<DbSlimmingBackupDirectorySelection> {+ const owner = captureReadyOwner();+ const directory = await deps.selectBackupDirectory();+ if (!directory) return { selected: false };+ assertOwnerCurrent(owner);+ const grantId = randomUUID();+ pruneExpiredGrants();+ directoryGrants.set(grantId, {+ ownerId: owner.ownerId,+ scopeKey: owner.scopeKey,+ directory,+ expiresAt: Date.now() + GRANT_TTL_MS,+ });+ return { selected: true, grantId, displayPath: directory };+ },++ async schedule(input: DbSlimmingScheduleInput): Promise<DbSlimmingScheduleResult> {+ if (!input || typeof input !== 'object') {+ throwIpcError('INVALID_PARAMS', 'database maintenance schedule input is required');+ }+ if (typeof input.scanId !== 'string' || typeof input.backupEnabled !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'invalid database maintenance schedule input');+ }+ pruneExpiredGrants();+ if (!deps.canSchedule()) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'database maintenance cannot be scheduled from a shared passive instance',+ );+ }+ const owner = captureReadyOwner();+ const scan = scanGrants.get(input.scanId);+ if (+ !scan ||+ scan.ownerId !== owner.ownerId ||+ scan.scopeKey !== owner.scopeKey ||+ scan.expiresAt <= Date.now()+ ) {+ throwIpcError('PRECONDITION_FAILED', 'database maintenance scan expired; scan again');+ }+ if (scan.messageCount === 0) return { scheduled: false };+ if (pendingScheduleIds.has(scan.scanId)) {+ throwIpcError('PRECONDITION_FAILED', 'database maintenance confirmation is already open');+ }+ pendingScheduleIds.add(scan.scanId);+ try {+ let backupDirectory: string | undefined;+ let directoryGrant: DirectoryGrant | undefined;+ if (input.backupDirectoryGrantId !== undefined) {+ if (!input.backupEnabled || typeof input.backupDirectoryGrantId !== 'string') {+ throwIpcError('INVALID_PARAMS', 'invalid database backup directory selection');+ }+ directoryGrant = directoryGrants.get(input.backupDirectoryGrantId);+ if (+ !directoryGrant ||+ directoryGrant.ownerId !== owner.ownerId ||+ directoryGrant.scopeKey !== owner.scopeKey ||+ directoryGrant.expiresAt <= Date.now()+ ) {+ throwIpcError('PRECONDITION_FAILED', 'database backup directory selection expired');+ }+ backupDirectory = directoryGrant.directory;+ }++ if (!input.backupEnabled && !(await deps.confirmWithoutBackup())) {+ return { scheduled: false };+ }++ pruneExpiredGrants();+ if (!deps.canSchedule()) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'database maintenance cannot be scheduled from a shared passive instance',+ );+ }+ assertOwnerCurrent(owner);+ const liveScan = scanGrants.get(scan.scanId);+ if (+ liveScan !== scan ||+ scan.expiresAt <= Date.now() ||+ (directoryGrant !== undefined &&+ directoryGrants.get(input.backupDirectoryGrantId!) !== directoryGrant)+ ) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'database maintenance authorization expired during confirmation',+ );+ }+ const dbFilePath = deps.getCurrentDbPath();+ if (!dbFilePath || !fs.existsSync(dbFilePath)) {+ throwIpcError('PRECONDITION_FAILED', 'database path is unavailable');+ }+ const userDataDir = deps.getUserDataDir();+ let existingRequest: ReturnType<typeof readDbSlimmingRequest>;+ try {+ existingRequest = readDbSlimmingRequest(userDataDir);+ } catch {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'database maintenance request marker is unavailable',+ );+ }+ if (existingRequest) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'database maintenance recovery is already pending',+ );+ }+ clearDbSlimmingResult(userDataDir);+ resultCache.delete(owner.ownerId);+ writeDbSlimmingRequest(userDataDir, {+ version: 1,+ id: scan.scanId,+ ownerId: owner.ownerId,+ createdAt: Date.now(),+ scannedAt: scan.scannedAt,+ archivedBeforeMs: scan.archivedBeforeMs,+ archiveAgeMonths: scan.archiveAgeMonths,+ deletedTaskCount: scan.deletedTaskCount,+ archivedTaskCount: scan.archivedTaskCount,+ messageCount: scan.messageCount,+ estimatedMessageBytes: scan.estimatedMessageBytes,+ beforeBytes: scan.databaseBytes,+ backupEnabled: input.backupEnabled,+ ...(backupDirectory ? { backupDirectory } : {}),+ phase: 'scheduled',+ });+ scanGrants.delete(scan.scanId);+ if (input.backupDirectoryGrantId) {+ directoryGrants.delete(input.backupDirectoryGrantId);+ }+ deps.relaunch(scan.scanId);+ return { scheduled: true };+ } finally {+ pendingScheduleIds.delete(scan.scanId);+ }+ },++ getLastResult(): DbSlimmingResult | null {+ const owner = captureReadyOwner();+ const result = loadResultForOwner(owner.ownerId);+ return result ? publicDbSlimmingResult(result) : null;+ },++ async openLastBackupDirectory(): Promise<{ opened: boolean }> {+ const owner = captureReadyOwner();+ const result = loadResultForOwner(owner.ownerId);+ if (!result || result.status !== 'completed' || !result.backupPath) {+ return { opened: false };+ }+ return { opened: await deps.revealFile(result.backupPath) };+ },+ };+}++function validateArchiveAge(value: unknown): DbSlimmingArchiveAge {+ if (!DB_SLIMMING_ARCHIVE_AGE_OPTIONS.includes(value as DbSlimmingArchiveAge)) {+ throwIpcError('INVALID_PARAMS', 'invalid database maintenance archive threshold');+ }+ return value as DbSlimmingArchiveAge;+}++/** Uses an exact seven-day duration or calendar months with month-end clamping. */+export function archiveCutoffForAge(+ scannedAt: number,+ archiveAge: DbSlimmingArchiveAge,+): number {+ if (archiveAge === '7-days') {+ return scannedAt - 7 * 24 * 60 * 60 * 1000;+ }+ const cutoff = new Date(scannedAt);+ const dayOfMonth = cutoff.getUTCDate();+ cutoff.setUTCDate(1);+ cutoff.setUTCMonth(cutoff.getUTCMonth() - archiveAge);+ const lastDayOfTargetMonth = new Date(+ Date.UTC(cutoff.getUTCFullYear(), cutoff.getUTCMonth() + 1, 0),+ ).getUTCDate();+ cutoff.setUTCDate(Math.min(dayOfMonth, lastDayOfTargetMonth));+ return cutoff.getTime();+}diff --git a/apps/desktop/src/main/localDb/maintenanceStore.ts b/apps/desktop/src/main/localDb/maintenanceStore.tsnew file mode 100644index 0000000000..4d9f01ca0a--- /dev/null+++ b/apps/desktop/src/main/localDb/maintenanceStore.ts@@ -0,0 +1,341 @@+import fs from 'node:fs';+import path from 'node:path';++import {+ DB_SLIMMING_ARCHIVE_AGE_OPTIONS,+ type DbSlimmingArchiveAge,+ DbSlimmingBackupLocation,+ DbSlimmingFailureReason,+ DbSlimmingResult,+} from '../../shared/localDbMaintenance';+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';++const REQUEST_FILE_NAME = 'db-slimming-request.json';+const RESULT_FILE_NAME = 'db-slimming-result.json';+const BACKUP_INDEX_FILE_NAME = 'db-slimming-backups.json';+const REQUEST_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;++export type DbSlimmingRequestPhase =+ | 'scheduled'+ | 'swap-prepared'+ | 'replacement-installed'+ | 'rollback-completed'+ | 'committed';++/** Cross-restart request owned by main. It never accepts a database path from Renderer. */+export interface DbSlimmingRequestRecord {+ version: 1;+ id: string;+ ownerId: string;+ createdAt: number;+ scannedAt: number;+ archivedBeforeMs: number;+ archiveAgeMonths: DbSlimmingArchiveAge;+ deletedTaskCount: number;+ archivedTaskCount: number;+ messageCount: number;+ estimatedMessageBytes?: number;+ beforeBytes: number;+ backupEnabled: boolean;+ backupDirectory?: string;+ phase: DbSlimmingRequestPhase;+ rollbackFailureReason?: DbSlimmingFailureReason;+}++/** The marker was readable, but its JSON or validated record shape is invalid. */+export class InvalidDbSlimmingRequestMarkerError extends Error {+ constructor(cause?: unknown) {+ super('invalid database slimming request marker');+ this.name = 'InvalidDbSlimmingRequestMarkerError';+ if (cause !== undefined) this.cause = cause;+ }+}++/** Persisted result keeps the privileged backup path out of the Renderer contract. */+export type DbSlimmingResultRecord =+ | (Extract<DbSlimmingResult, { status: 'completed' }> & {+ ownerId: string;+ backupPath?: string;+ })+ | (Extract<DbSlimmingResult, { status: 'failed' }> & { ownerId: string });++interface DbSlimmingBackupIndexRecord {+ version: 1;+ owners: Record<+ string,+ {+ currentPath: string;+ stalePaths: string[];+ }+ >;+}++export function dbSlimmingRequestPath(userDataDir: string): string {+ return path.join(userDataDir, REQUEST_FILE_NAME);+}++export function dbSlimmingResultPath(userDataDir: string): string {+ return path.join(userDataDir, RESULT_FILE_NAME);+}++function dbSlimmingBackupIndexPath(userDataDir: string): string {+ return path.join(userDataDir, BACKUP_INDEX_FILE_NAME);+}++export function readDbSlimmingRequest(userDataDir: string): DbSlimmingRequestRecord | null {+ const raw = readAtomicFileSync(dbSlimmingRequestPath(userDataDir));+ if (raw === null) return null;+ let value: unknown;+ try {+ value = JSON.parse(raw);+ } catch (error) {+ throw new InvalidDbSlimmingRequestMarkerError(error);+ }+ if (!isDbSlimmingRequestRecord(value)) {+ throw new InvalidDbSlimmingRequestMarkerError();+ }+ return value;+}++export function writeDbSlimmingRequest(+ userDataDir: string,+ request: DbSlimmingRequestRecord,+): void {+ atomicWriteFileSync(dbSlimmingRequestPath(userDataDir), JSON.stringify(request));+}++export function clearDbSlimmingRequest(userDataDir: string): boolean {+ return removeAtomicMarker(dbSlimmingRequestPath(userDataDir));+}++export function readDbSlimmingResult(userDataDir: string): DbSlimmingResultRecord | null {+ const raw = readAtomicFileSync(dbSlimmingResultPath(userDataDir));+ if (raw === null) return null;+ const value: unknown = JSON.parse(raw);+ if (!isDbSlimmingResultRecord(value)) {+ throw new Error('invalid database slimming result marker');+ }+ return value;+}++export function writeDbSlimmingResult(userDataDir: string, result: DbSlimmingResultRecord): void {+ atomicWriteFileSync(dbSlimmingResultPath(userDataDir), JSON.stringify(result));+}++export function clearDbSlimmingResult(userDataDir: string): boolean {+ return removeAtomicMarker(dbSlimmingResultPath(userDataDir));+}++export function publicDbSlimmingResult(record: DbSlimmingResultRecord): DbSlimmingResult {+ if (record.status === 'failed') {+ const { ownerId: _ownerId, ...result } = record;+ return result;+ }+ const { ownerId: _ownerId, backupPath: _backupPath, ...result } = record;+ return result;+}++export function adoptDbSlimmingBackup(+ userDataDir: string,+ ownerId: string,+ backupPath: string,+): void {+ if (!ownerId || !isSlimmingBackupPath(backupPath)) {+ throw new Error('invalid database slimming backup index input');+ }+ const index = readDbSlimmingBackupIndex(userDataDir);+ const previous = index.owners[ownerId];+ const stalePaths = [+ ...(previous?.stalePaths ?? []),+ ...(previous && !pathsEqual(previous.currentPath, backupPath)+ ? [previous.currentPath]+ : []),+ ].filter((candidate, position, all) =>+ !pathsEqual(candidate, backupPath) &&+ all.findIndex((other) => pathsEqual(other, candidate)) === position,+ );+ index.owners[ownerId] = { currentPath: backupPath, stalePaths };+ writeDbSlimmingBackupIndex(userDataDir, index);++ const remaining = stalePaths.filter((candidate) => !removeBackupFamily(candidate));+ if (remaining.length !== stalePaths.length) {+ index.owners[ownerId] = { currentPath: backupPath, stalePaths: remaining };+ try {+ writeDbSlimmingBackupIndex(userDataDir, index);+ } catch {+ // The first index write already made the new verified backup authoritative.+ // Keeping already-removed paths in stalePaths is safe and lets a future+ // adoption retry the idempotent cleanup without invalidating the backup.+ }+ }+}++function readDbSlimmingBackupIndex(userDataDir: string): DbSlimmingBackupIndexRecord {+ const raw = readAtomicFileSync(dbSlimmingBackupIndexPath(userDataDir));+ if (raw === null) return { version: 1, owners: {} };+ const value: unknown = JSON.parse(raw);+ if (!isDbSlimmingBackupIndexRecord(value)) {+ throw new Error('invalid database slimming backup index');+ }+ return value;+}++function writeDbSlimmingBackupIndex(+ userDataDir: string,+ index: DbSlimmingBackupIndexRecord,+): void {+ atomicWriteFileSync(dbSlimmingBackupIndexPath(userDataDir), JSON.stringify(index));+}++function removeBackupFamily(filePath: string): boolean {+ try {+ for (const candidate of [filePath, `${filePath}-wal`, `${filePath}-shm`, `${filePath}-journal`]) {+ fs.rmSync(candidate, { force: true, maxRetries: 3, retryDelay: 20 });+ }+ return true;+ } catch {+ return false;+ }+}++function removeAtomicMarker(filePath: string): boolean {+ for (const candidate of [filePath, `${filePath}.bak`]) {+ for (let attempt = 0; ; attempt += 1) {+ try {+ fs.rmSync(candidate, { force: true });+ break;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (attempt >= 3 || !['EBUSY', 'EACCES', 'EPERM'].includes(code ?? '')) break;+ Atomics.wait(+ new Int32Array(new SharedArrayBuffer(4)),+ 0,+ 0,+ 20 * (attempt + 1),+ );+ }+ }+ }+ return !fs.existsSync(filePath) && !fs.existsSync(`${filePath}.bak`);+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function isFiniteNumber(value: unknown): value is number {+ return typeof value === 'number' && Number.isFinite(value);+}++function isDbSlimmingRequestRecord(value: unknown): value is DbSlimmingRequestRecord {+ if (!isRecord(value)) return false;+ if (+ value.version !== 1 ||+ typeof value.id !== 'string' ||+ !REQUEST_ID_PATTERN.test(value.id) ||+ typeof value.ownerId !== 'string' ||+ value.ownerId.length === 0 ||+ !isFiniteNumber(value.createdAt) ||+ !isFiniteNumber(value.scannedAt) ||+ !isFiniteNumber(value.archivedBeforeMs) ||+ !isArchiveAge(value.archiveAgeMonths) ||+ !Number.isInteger(value.deletedTaskCount) ||+ !Number.isInteger(value.archivedTaskCount) ||+ !Number.isInteger(value.messageCount) ||+ (value.estimatedMessageBytes !== undefined &&+ (!isFiniteNumber(value.estimatedMessageBytes) || value.estimatedMessageBytes < 0)) ||+ !isFiniteNumber(value.beforeBytes) ||+ typeof value.backupEnabled !== 'boolean' ||+ ![+ 'scheduled',+ 'swap-prepared',+ 'replacement-installed',+ 'rollback-completed',+ 'committed',+ ].includes(+ String(value.phase),+ )+ ) {+ return false;+ }+ const rollbackFailureIsValid =+ value.phase === 'rollback-completed'+ ? isFailureReason(value.rollbackFailureReason)+ : value.rollbackFailureReason === undefined;+ return (+ rollbackFailureIsValid &&+ (value.backupDirectory === undefined ||+ (typeof value.backupDirectory === 'string' && path.isAbsolute(value.backupDirectory)))+ );+}++function isDbSlimmingResultRecord(value: unknown): value is DbSlimmingResultRecord {+ if (!isRecord(value)) return false;+ if (+ typeof value.id !== 'string' ||+ !REQUEST_ID_PATTERN.test(value.id) ||+ typeof value.ownerId !== 'string' ||+ !isFiniteNumber(value.finishedAt) ||+ !isArchiveAge(value.archiveAgeMonths)+ ) {+ return false;+ }+ if (value.status === 'failed') {+ return (+ isFailureReason(value.reason) && typeof value.originalDatabaseRestored === 'boolean'+ );+ }+ if (value.status !== 'completed') return false;+ return (+ Number.isInteger(value.deletedTaskCount) &&+ Number.isInteger(value.archivedTaskCount) &&+ Number.isInteger(value.messageCount) &&+ isFiniteNumber(value.beforeBytes) &&+ isFiniteNumber(value.afterBytes) &&+ isFiniteNumber(value.reclaimedBytes) &&+ typeof value.backupCreated === 'boolean' &&+ (value.backupLocation === undefined || isBackupLocation(value.backupLocation)) &&+ (value.backupPath === undefined ||+ (typeof value.backupPath === 'string' && path.isAbsolute(value.backupPath)))+ );+}++function isDbSlimmingBackupIndexRecord(value: unknown): value is DbSlimmingBackupIndexRecord {+ if (!isRecord(value) || value.version !== 1 || !isRecord(value.owners)) return false;+ return Object.entries(value.owners).every(([ownerId, entry]) => {+ if (!ownerId || !isRecord(entry) || typeof entry.currentPath !== 'string') return false;+ if (!isSlimmingBackupPath(entry.currentPath) || !Array.isArray(entry.stalePaths)) return false;+ return entry.stalePaths.every(+ (candidate) => typeof candidate === 'string' && isSlimmingBackupPath(candidate),+ );+ });+}++function isFailureReason(value: unknown): value is DbSlimmingFailureReason {+ return [+ 'backup-failed',+ 'cleanup-failed',+ 'database-in-use',+ 'insufficient-space',+ 'integrity-check-failed',+ 'replacement-failed',+ 'recovery-failed',+ ].includes(String(value));+}++function isBackupLocation(value: unknown): value is DbSlimmingBackupLocation {+ return value === 'database-directory' || value === 'custom-directory';+}++function isArchiveAge(value: unknown): value is DbSlimmingArchiveAge {+ return DB_SLIMMING_ARCHIVE_AGE_OPTIONS.includes(value as DbSlimmingArchiveAge);+}++function pathsEqual(left: string, right: string): boolean {+ if (process.platform === 'win32') return left.toLowerCase() === right.toLowerCase();+ return left === right;+}++function isSlimmingBackupPath(filePath: string): boolean {+ return path.isAbsolute(filePath) && path.basename(filePath).endsWith('.slimming-backup');+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 342b51542e..b1ef6c8791 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -148,6 +148,7 @@ import {import { isDataOwnerPushStamp, type DataOwnerPushStamp } from '../shared/dataOwnerPush';import type { VoiceInputSyncErrorResult } from '../shared/voiceInputData';import type { UtilityTextFailure } from '../shared/utilityTextResult';+import { DB_SLIMMING_STARTUP_PROGRESS_CHANGED_CHANNEL } from '../shared/localDbMaintenance';import type { BrowserBackendHealth, BrowserBackendRecoveryResult } from '../shared/browserBackend';import type {ReviewBranchDiffData,@@ -431,6 +432,9 @@ function createIpcFanOut(channel: string): FanOut {// Stage 2 C1: cc-agent:* push channel fanout 全部退役 (renderer 已切到 maker:event 等),// 老 7 个 fanOut + fanOutUserMessagePersisted 一起拿掉。const fanOutUpdateStatus = createIpcFanOut('update-status');+const fanOutDbSlimmingStartupProgress = createIpcFanOut(+ DB_SLIMMING_STARTUP_PROGRESS_CHANGED_CHANNEL,+);const fanOutUpdateChannelSettings = createIpcFanOut('update-channel-settings');const fanOutWindowBackdropMaterialChanged = createIpcFanOut(WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,@@ -4851,6 +4855,40 @@ contextBridge.exposeInMainWorld('electronAPI', {userId: string,): Promise<{ ready: true } | { ready: false; error: { code: string; message: string } }> =>ipcRenderer.invoke('local-db:ensure-ready', userId),+ maintenance: {+ scan: (+ input: import('../shared/localDbMaintenance').DbSlimmingScanInput,+ ): Promise<import('../shared/localDbMaintenance').DbSlimmingScanResult> =>+ ipcRenderer.invoke('local-db:maintenance:scan', input),+ chooseBackupDirectory: (): Promise<+ import('../shared/localDbMaintenance').DbSlimmingBackupDirectorySelection+ > => ipcRenderer.invoke('local-db:maintenance:choose-backup-directory'),+ schedule: (+ input: import('../shared/localDbMaintenance').DbSlimmingScheduleInput,+ ): Promise<import('../shared/localDbMaintenance').DbSlimmingScheduleResult> =>+ ipcRenderer.invoke('local-db:maintenance:schedule', input),+ getLastResult: (): Promise<+ import('../shared/localDbMaintenance').DbSlimmingResult | null+ > => ipcRenderer.invoke('local-db:maintenance:last-result'),+ openLastBackupDirectory: (): Promise<{ opened: boolean }> =>+ ipcRenderer.invoke('local-db:maintenance:open-last-backup-directory'),+ getStartupProgress: (): Promise<+ import('../shared/localDbMaintenance').DbSlimmingStartupProgress | null+ > => ipcRenderer.invoke('local-db:maintenance:startup-progress'),+ cancelStartup: (): Promise<+ import('../shared/localDbMaintenance').DbSlimmingStartupCancelResult+ > => ipcRenderer.invoke('local-db:maintenance:cancel-startup'),+ onStartupProgress: (+ callback: (+ progress: import('../shared/localDbMaintenance').DbSlimmingStartupProgress | null,+ ) => void,+ ): (() => void) =>+ fanOutDbSlimmingStartupProgress((progress) => {+ callback(+ progress as import('../shared/localDbMaintenance').DbSlimmingStartupProgress | null,+ );+ }),+ },sessions: {list: (limit?: number, status?: string, options?: unknown): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:list', limit, status, options),diff --git a/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx b/apps/desktop/src/renderer/components/auth/LocalDbGate.tsxindex 94d126414e..be1193cf79 100644--- a/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx+++ b/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx@@ -1,12 +1,16 @@import { useEffect, useRef, useState } from 'react';import { Outlet, useNavigate } from 'react-router-dom';+import { useTranslation } from 'react-i18next';import { useAppShellCover } from '@/contexts/AppShellCoverContext';import { useAuth } from '@/contexts/AuthContext';import { LocalDbFatalScreen } from '@/components/error/LocalDbFatalScreen';import { createLogger } from '@/lib/logger';+import { toast } from '@/lib/toast';+import { formatBytes } from '@/features/cc-agent/workdir-browse/lib/fileMeta';const log = createLogger('LocalDbGate');+const shownDbSlimmingResultIds = new Set<string>();/*** 路由层 localDb 就绪门(前身 MigrationGate;chat-data 云端迁移已随主 server@@ -36,6 +40,7 @@ const MAX_DECISION_RETRIES = 2;const DECISION_RETRY_DELAY_MS = 1_000;export function LocalDbGate() {+ const { t } = useTranslation();const { dataOwnerId, mode, logout, exitLocalMode } = useAuth();const { reportLocalDbGate } = useAppShellCover();const navigate = useNavigate();@@ -80,6 +85,31 @@ export function LocalDbGate() {rendererUptimeMs: Math.round(performance.now()),});+ try {+ const maintenanceResult = await window.electronAPI.localDb.maintenance.getLastResult();+ if (+ maintenanceResult &&+ !shownDbSlimmingResultIds.has(maintenanceResult.id)+ ) {+ shownDbSlimmingResultIds.add(maintenanceResult.id);+ if (maintenanceResult.status === 'completed') {+ toast.success(+ t('settings.about.storage.dbSlimmingToastCompleted', {+ size: formatBytes(maintenanceResult.reclaimedBytes),+ }),+ );+ } else {+ toast.error(+ t(`settings.about.storage.dbSlimmingFailure.${maintenanceResult.reason}`, {+ defaultValue: t('settings.about.storage.dbSlimmingFailure.unknown'),+ }),+ );+ }+ }+ } catch (error) {+ log.warn('database slimming result read failed (non-fatal)', error);+ }+// Signal main "user logged in + localDb is open" so account integrations can// come online after provider discovery. Gated and idempotent in main — re-mounts// and account switches are no-ops after the first call.@@ -115,7 +145,7 @@ export function LocalDbGate() {};// 依赖 user.id——切账号 blank;同账号 refresh 不因对象引用变化卸载 Outlet。// retryNonce 驱动失败后的有限重试重跑。- }, [dataOwnerId, retryNonce]);+ }, [dataOwnerId, retryNonce, t]);useEffect(() => {if (!dataOwnerId || decision.phase === 'checking') {diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 629b1730a1..3a18791e81 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -357,6 +357,8 @@ interface MessageStreamProps {workingDir: string;messages: ChatMessage[];historyLoaded: boolean;+ /** The task shell remains, but all prior message content was intentionally cleared. */+ historyCleared?: boolean;taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>;/** Kept for API compatibility. v2 — no longer threaded into render items* (AgentActionsBlock + ThinkingCard manage their own per-block expand@@ -733,6 +735,19 @@ function ForkOriginMarker({ onClick }: { onClick?: () => void }) {);}+function HistoryClearedMarker() {+ const { t } = useTranslation();+ return (+ <div className="flex items-center gap-4 py-3" role="status">+ <div className="h-px flex-1 bg-[var(--border-default)]" />+ <span className="shrink-0 text-12 text-[var(--text-tertiary)]">+ {t('settings.about.storage.dbSlimmingHistoryCleared')}+ </span>+ <div className="h-px flex-1 bg-[var(--border-default)]" />+ </div>+ );+}+function areLocalFileRefsEqual(a: readonly KnownLocalFileRef[],b: readonly KnownLocalFileRef[],@@ -3019,6 +3034,7 @@ export function MessageStream({workingDir,messages,historyLoaded,+ historyCleared = false,taskUpdates,isSessionStreaming = false,continuationTurnClientId = null,@@ -5878,6 +5894,9 @@ export function MessageStream({maxWidth: contentWidth ?? 880,}}>+ {historyLoaded && historyCleared && (+ <HistoryClearedMarker />+ )}{/* F-SYNC-2: Loading spinner at top */}{isLoadingMore && (<div className="flex items-center justify-center pb-4">diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex 70bb822017..46bafbfd57 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -33,6 +33,7 @@ import { useDeviceLinkRemoteProjects } from '@/features/device-link/useDeviceLinimport { pluginScheduleNavigationState } from '@/features/scheduler/lib/pluginScheduleCreateIntent';import { FeatureSidebarSlotProvider } from '@/features/feature-context';import { useAppShortcut } from '@/hooks/useAppShortcut';+import { isAppInteractionLocked } from '@/lib/appInteractionLock';import { useCloseShortcutShellOwner } from '@/hooks/useCloseWindowShortcut';import {addOrFocusSingletonTab,@@ -1025,6 +1026,7 @@ export function MainLayout() {useEffect(() => {return window.electronAPI.onApplicationMenuCommand((command) => {+ if (isAppInteractionLocked()) return;switch (command) {case 'open-about':navigate('/settings?tab=about');@@ -1148,6 +1150,7 @@ export function MainLayout() {useEffect(() => {return subscribeWorkLouderCodexAction((action) => {+ if (isAppInteractionLocked()) return true;if (action.type === 'keyboard') {const target =document.activeElement instanceof HTMLElement ? document.activeElement : document.body;diff --git a/apps/desktop/src/renderer/components/login/loginDesignTokens.ts b/apps/desktop/src/renderer/components/login/loginDesignTokens.tsindex 62de46c9c0..0fea61d796 100644--- a/apps/desktop/src/renderer/components/login/loginDesignTokens.ts+++ b/apps/desktop/src/renderer/components/login/loginDesignTokens.ts@@ -250,6 +250,14 @@ export const SPLASH_PANEL = {progress: { x: 90, y: 346, width: 501, height: 16, radius: 12 },/** 明细行 20px Regular @(41,375) 599×23(379:574,与副文案同栏宽居中) */stats: { x: 41, y: 375, width: 599, height: 23, fontSize: 20 },+ /** 启动数据库清理:阶段标题下依次为进度、时间、取消入口和安全提示。 */+ databaseCleanup: {+ progressY: 160,+ statsY: 190,+ actionY: 235,+ actionHeight: 50,+ hint: { x: 70, y: 315, width: 540, height: 48, fontSize: 16, lineHeight: 22 },+ },} as const;/**diff --git a/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx b/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsxindex b4f0da0cae..9e135678e3 100644--- a/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx+++ b/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx@@ -16,13 +16,29 @@* 点击用 ref 标志,不产生任何视觉变化。*/-import { useEffect, useRef, useState } from 'react';+import { useEffect, useId, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { Check, ChevronDown } from 'lucide-react';+import * as AlertDialog from '@radix-ui/react-alert-dialog';+import * as Select from '@radix-ui/react-select';import { cn } from '@/lib/utils';import { toast } from '@/lib/toast';+import { mapIpcErrorToI18nKey } from '@/utils/ipcError';import { getAllDraftAttachmentUrls } from '@/lib/composerDraftStore';+import { acquireAppInteractionLock } from '@/lib/appInteractionLock';import { formatBytes } from '@/features/cc-agent/workdir-browse/lib/fileMeta';+import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';+import { Spinner } from '@/components/ui/spinner';+import { Switch } from '@/components/ui/switch';+import {+ DB_SLIMMING_ARCHIVE_AGE_OPTIONS,+ DB_SLIMMING_DEFAULT_ARCHIVE_AGE,+ type DbSlimmingArchiveAge,+ type DbSlimmingBackupDirectorySelection,+ type DbSlimmingResult,+ type DbSlimmingScanResult,+} from '../../../shared/localDbMaintenance';type StatsResult = Awaited<ReturnType<typeof window.electronAPI.cindyMediaStorage.stats>>;type ScanResult = Awaited<ReturnType<typeof window.electronAPI.cindyMediaStorage.scan>>;@@ -255,6 +271,10 @@ export function StorageManagementCard() {<Divider />+ <DatabaseSlimmingSection />++ <Divider />+{/* 清理:扫描 → 报数确认 → 执行 → 结果 */}<div className="flex flex-col gap-2 px-[18px] py-4"><div className="flex items-center justify-between gap-3">@@ -382,6 +402,499 @@ export function StorageManagementCard() {);}+type DbSlimmingPhase =+ | { kind: 'idle' }+ | { kind: 'scanned'; scan: DbSlimmingScanResult }+ | { kind: 'done'; result: DbSlimmingResult };++function DatabaseSlimmingSection() {+ const { t } = useTranslation();+ const [archiveAge, setArchiveAge] = useState<DbSlimmingArchiveAge>(+ DB_SLIMMING_DEFAULT_ARCHIVE_AGE,+ );+ const [backupEnabled, setBackupEnabled] = useState(true);+ const [backupDirectory, setBackupDirectory] =+ useState<DbSlimmingBackupDirectorySelection>({ selected: false });+ const [phase, setPhase] = useState<DbSlimmingPhase>({ kind: 'idle' });+ const [scanLoading, setScanLoading] = useState(false);+ const [reportOpen, setReportOpen] = useState(false);+ const [executionLocked, setExecutionLocked] = useState(false);+ const busyRef = useRef(false);+ const interactionLockReleaseRef = useRef<(() => void) | null>(null);++ const acquireInteractionLock = () => {+ if (!interactionLockReleaseRef.current) {+ interactionLockReleaseRef.current = acquireAppInteractionLock();+ }+ };++ const releaseInteractionLock = () => {+ interactionLockReleaseRef.current?.();+ interactionLockReleaseRef.current = null;+ };++ useEffect(() => {+ return () => {+ interactionLockReleaseRef.current?.();+ interactionLockReleaseRef.current = null;+ };+ }, []);++ useEffect(() => {+ let cancelled = false;+ void window.electronAPI.localDb.maintenance.getLastResult().then(+ (result) => {+ if (!cancelled && result) setPhase({ kind: 'done', result });+ },+ () => undefined,+ );+ return () => {+ cancelled = true;+ };+ }, []);++ const invalidateScan = () => {+ setReportOpen(false);+ releaseInteractionLock();+ setPhase((current) => (current.kind === 'scanned' ? { kind: 'idle' } : current));+ };++ const handleArchiveAgeChange = (raw: string) => {+ const parsed = raw === '7-days' ? raw : Number(raw);+ if (!DB_SLIMMING_ARCHIVE_AGE_OPTIONS.includes(parsed as DbSlimmingArchiveAge)) return;+ setArchiveAge(parsed as DbSlimmingArchiveAge);+ invalidateScan();+ };++ const handleChooseBackupDirectory = async () => {+ if (busyRef.current) return;+ busyRef.current = true;+ try {+ const selection = await window.electronAPI.localDb.maintenance.chooseBackupDirectory();+ if (selection.selected) setBackupDirectory(selection);+ } catch {+ toast.error(t('settings.about.storage.dbSlimmingBackupDirectoryFailed'));+ } finally {+ busyRef.current = false;+ }+ };++ const handleScan = async () => {+ if (busyRef.current) return;+ busyRef.current = true;+ acquireInteractionLock();+ setReportOpen(false);+ setScanLoading(true);+ let completed = false;+ try {+ const scan = await window.electronAPI.localDb.maintenance.scan({+ archiveAgeMonths: archiveAge,+ });+ setPhase({ kind: 'scanned', scan });+ setReportOpen(true);+ completed = true;+ } catch (error) {+ toast.error(+ t(+ mapIpcErrorToI18nKey(error, {+ fallback: 'settings.about.storage.dbSlimmingScanFailed',+ }),+ ),+ );+ } finally {+ busyRef.current = false;+ if (!completed) releaseInteractionLock();+ setScanLoading(false);+ }+ };++ const handleSchedule = async () => {+ if (phase.kind !== 'scanned' || busyRef.current || executionLocked) return;+ busyRef.current = true;+ acquireInteractionLock();+ setReportOpen(false);+ setExecutionLocked(true);+ try {+ const result = await window.electronAPI.localDb.maintenance.schedule({+ scanId: phase.scan.scanId,+ backupEnabled,+ ...(backupEnabled && backupDirectory.grantId+ ? { backupDirectoryGrantId: backupDirectory.grantId }+ : {}),+ });+ if (!result.scheduled) {+ busyRef.current = false;+ setExecutionLocked(false);+ setReportOpen(true);+ }+ } catch (error) {+ busyRef.current = false;+ setExecutionLocked(false);+ setReportOpen(true);+ toast.error(+ t(+ mapIpcErrorToI18nKey(error, {+ fallback: 'settings.about.storage.dbSlimmingScheduleFailed',+ }),+ ),+ );+ }+ };++ const handleReportOpenChange = (open: boolean) => {+ setReportOpen(open);+ if (!open) releaseInteractionLock();+ };++ const handleOpenBackup = async () => {+ try {+ const result = await window.electronAPI.localDb.maintenance.openLastBackupDirectory();+ if (!result.opened) toast.info(t('settings.about.storage.dbSlimmingBackupMissing'));+ } catch {+ toast.error(t('settings.about.storage.dbSlimmingBackupOpenFailed'));+ }+ };++ const scanned = phase.kind === 'scanned' ? phase.scan : null;+ const insufficientSpace = Boolean(+ scanned &&+ scanned.databaseVolumeFreeBytes !== null &&+ scanned.databaseVolumeFreeBytes < scanned.temporaryBytesRequired,+ );++ return (+ <div className="flex flex-col gap-3 px-[18px] py-4" aria-busy={scanLoading}>+ <div className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 flex-col gap-1">+ <span className="text-13 text-[var(--settings-section-sublabel)]">+ {t('settings.about.storage.dbSlimmingLabel')}+ </span>+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">+ {t('settings.about.storage.dbSlimmingDescription')}+ </p>+ </div>+ <CardButton onClick={handleScan} disabled={scanLoading} busy={scanLoading}>+ {scanLoading && <Spinner size={12} />}+ {t('settings.about.storage.dbSlimmingScanButton')}+ </CardButton>+ </div>++ <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 rounded-lg border border-[var(--settings-theme-card-border)] px-3 py-2.5">+ <label+ htmlFor="db-slimming-archive-age"+ className="text-12 text-[var(--settings-section-sublabel)]"+ >+ {t('settings.about.storage.dbSlimmingArchiveAgeLabel')}+ </label>+ <div className="flex items-center">+ <Select.Root+ value={String(archiveAge)}+ onValueChange={handleArchiveAgeChange}+ disabled={scanLoading}+ >+ <Select.Trigger+ id="db-slimming-archive-age"+ aria-label={t('settings.about.storage.dbSlimmingArchiveAgeLabel')}+ className={cn(+ 'flex h-8 min-w-[104px] items-center justify-between gap-2 rounded-full border px-3 text-12 outline-none transition-colors',+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] text-[var(--settings-input-text)]',+ 'hover:bg-[var(--settings-menu-bg-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ )}+ >+ <Select.Value />+ <Select.Icon asChild>+ <ChevronDown+ size={13}+ className="shrink-0 text-[var(--settings-eye-icon)]"+ aria-hidden="true"+ />+ </Select.Icon>+ </Select.Trigger>+ <Select.Portal>+ <Select.Content+ position="popper"+ side="bottom"+ align="end"+ sideOffset={6}+ className={cn(+ 'z-[10010] min-w-[var(--radix-select-trigger-width)] rounded-xl p-1.5',+ 'border border-[var(--settings-input-border)] bg-[var(--settings-theme-card-bg)] shadow-[var(--shadow-menu)]',+ )}+ >+ <Select.Viewport className="flex flex-col gap-0.5">+ {DB_SLIMMING_ARCHIVE_AGE_OPTIONS.map((age) => (+ <Select.Item+ key={age}+ value={String(age)}+ className={cn(+ 'flex h-8 cursor-pointer select-none items-center justify-between gap-2 rounded-lg px-2.5 text-12 outline-none transition-colors',+ 'text-[var(--settings-input-text)] data-[highlighted]:bg-[var(--settings-menu-bg-hover)]',+ 'data-[state=checked]:bg-[var(--settings-menu-bg-selected)] data-[state=checked]:font-medium data-[state=checked]:text-[var(--settings-menu-text-selected)]',+ )}+ >+ <Select.ItemText>+ {t(+ age === '7-days'+ ? 'settings.about.storage.dbSlimmingArchiveAgeOption7Days'+ : `settings.about.storage.dbSlimmingArchiveAgeOption${age}`,+ )}+ </Select.ItemText>+ <Select.ItemIndicator>+ <Check+ size={14}+ className="shrink-0 text-[var(--settings-theme-icon-active)]"+ />+ </Select.ItemIndicator>+ </Select.Item>+ ))}+ </Select.Viewport>+ </Select.Content>+ </Select.Portal>+ </Select.Root>+ </div>++ <label+ htmlFor="db-slimming-backup-enabled"+ className="flex min-w-0 cursor-pointer flex-col gap-0.5"+ >+ <span className="text-12 text-[var(--settings-section-sublabel)]">+ {t('settings.about.storage.dbSlimmingBackupLabel')}+ </span>+ <span className="truncate text-11 text-[var(--settings-section-sublabel)] opacity-70">+ {backupDirectory.selected && backupDirectory.displayPath+ ? backupDirectory.displayPath+ : t('settings.about.storage.dbSlimmingBackupDefaultLocation')}+ </span>+ </label>+ <Switch+ id="db-slimming-backup-enabled"+ checked={backupEnabled}+ onCheckedChange={(checked) => setBackupEnabled(checked)}+ aria-label={t('settings.about.storage.dbSlimmingBackupLabel')}+ />++ {backupEnabled && (+ <div className="col-span-2 flex justify-end gap-2">+ {backupDirectory.selected && (+ <CardButton+ onClick={() => setBackupDirectory({ selected: false })}+ >+ {t('settings.about.storage.dbSlimmingUseDefaultDirectoryButton')}+ </CardButton>+ )}+ <CardButton onClick={handleChooseBackupDirectory}>+ {t('settings.about.storage.dbSlimmingChooseDirectoryButton')}+ </CardButton>+ </div>+ )}+ </div>++ {phase.kind === 'done' && (+ <div className="flex flex-col gap-1.5 text-12 leading-[1.5] text-[var(--settings-section-sublabel)]">+ {phase.result.status === 'completed' ? (+ <>+ <p>+ {t('settings.about.storage.dbSlimmingResultCompleted', {+ size: formatBytes(phase.result.reclaimedBytes),+ messages: phase.result.messageCount,+ tasks: phase.result.deletedTaskCount + phase.result.archivedTaskCount,+ })}+ </p>+ {phase.result.backupCreated && (+ <div>+ <CardButton onClick={handleOpenBackup}>+ {t('settings.about.storage.dbSlimmingOpenBackupButton')}+ </CardButton>+ </div>+ )}+ </>+ ) : (+ <p>+ {t(`settings.about.storage.dbSlimmingFailure.${phase.result.reason}`, {+ defaultValue: t('settings.about.storage.dbSlimmingFailure.unknown'),+ })}+ </p>+ )}+ </div>+ )}++ <DatabaseCleanupDialog+ scanLoading={scanLoading}+ reportOpen={reportOpen}+ executionLocked={executionLocked}+ scanned={scanned}+ insufficientSpace={insufficientSpace}+ backupEnabled={backupEnabled}+ onReportOpenChange={handleReportOpenChange}+ onConfirm={handleSchedule}+ />+ </div>+ );+}++interface DatabaseCleanupDialogProps {+ scanLoading: boolean;+ reportOpen: boolean;+ executionLocked: boolean;+ scanned: DbSlimmingScanResult | null;+ insufficientSpace: boolean;+ backupEnabled: boolean;+ onReportOpenChange: (open: boolean) => void;+ onConfirm: () => void;+}++function DatabaseCleanupDialog({+ scanLoading,+ reportOpen,+ executionLocked,+ scanned,+ insufficientSpace,+ backupEnabled,+ onReportOpenChange,+ onConfirm,+}: DatabaseCleanupDialogProps) {+ const { t } = useTranslation();+ const bodyId = useId();+ const confirmButtonRef = useRef<HTMLButtonElement>(null);+ const reportVisible = reportOpen && scanned !== null;+ const mode = scanLoading+ ? 'scanning'+ : executionLocked+ ? 'executing'+ : reportVisible+ ? 'report'+ : 'closed';+ const open = mode !== 'closed';+ const busy = mode === 'scanning' || mode === 'executing';++ useEffect(() => {+ if (mode !== 'report') return;+ const frame = requestAnimationFrame(() => confirmButtonRef.current?.focus());+ return () => cancelAnimationFrame(frame);+ }, [mode]);++ return (+ <AlertDialog.Root+ open={open}+ onOpenChange={(nextOpen) => {+ if (!nextOpen && mode === 'report') onReportOpenChange(false);+ }}+ >+ <AlertDialog.Portal>+ <AlertDialog.Overlay+ className="fixed inset-0 z-[10020] bg-[var(--overlay-modal)]"+ style={{ ...WINDOW_DRAG_STYLE, zIndex: 10020 }}+ >+ <AlertDialog.Content+ className={cn(+ 'fixed inset-0 z-[10020] m-auto flex h-fit min-h-[180px] w-full max-w-[640px] flex-col',+ 'rounded-xl border border-[var(--settings-theme-card-border)]',+ 'bg-[var(--confirm-bg)] p-4 shadow-[var(--confirm-shadow)]',+ mode === 'report' ? 'select-text' : 'select-none',+ )}+ style={{ ...WINDOW_NO_DRAG_STYLE, zIndex: 10020 }}+ aria-describedby={mode === 'report' ? bodyId : undefined}+ aria-busy={busy || undefined}+ onEscapeKeyDown={(event) => {+ if (busy) event.preventDefault();+ }}+ >+ {busy ? (+ <AlertDialog.Title className="flex flex-1 items-center justify-center gap-3 text-14 font-medium text-[var(--confirm-title)]">+ <Spinner size={18} />+ <span role="status" aria-live="assertive">+ {mode === 'scanning'+ ? t('settings.about.storage.dbSlimmingScanLoading')+ : t('settings.about.storage.dbSlimmingExecutionLoading')}+ </span>+ </AlertDialog.Title>+ ) : (+ scanned && (+ <>+ <AlertDialog.Title className="shrink-0 text-lg font-medium text-[var(--confirm-title)]">+ {t('settings.about.storage.dbSlimmingScanResultTitle')}+ </AlertDialog.Title>+ <div+ id={bodyId}+ className="mt-3 flex min-h-0 flex-1 select-text flex-col gap-1.5 overflow-y-auto overscroll-contain"+ >+ <ReportLine+ visible+ text={t('settings.about.storage.dbSlimmingReportTasks', {+ deleted: scanned.deletedTaskCount,+ archived: scanned.archivedTaskCount,+ })}+ />+ <ReportLine+ visible+ text={t('settings.about.storage.dbSlimmingReportMessages', {+ count: scanned.messageCount,+ size: formatBytes(scanned.estimatedMessageBytes),+ })}+ />+ <ReportLine+ visible+ text={t('settings.about.storage.dbSlimmingReportSpace', {+ database: formatBytes(scanned.databaseBytes),+ temporary: formatBytes(scanned.temporaryBytesRequired),+ free:+ scanned.databaseVolumeFreeBytes === null+ ? t('settings.about.storage.dbSlimmingSpaceUnknown')+ : formatBytes(scanned.databaseVolumeFreeBytes),+ })}+ />+ {insufficientSpace && (+ <p className="text-12 leading-[1.5] text-[hsl(var(--destructive))]">+ {t('settings.about.storage.dbSlimmingInsufficientSpace')}+ </p>+ )}+ <p className="mt-2 text-12 leading-[1.5] text-[var(--settings-section-sublabel)] opacity-70">+ {backupEnabled+ ? t('settings.about.storage.dbSlimmingConfirmDescriptionWithBackup')+ : t('settings.about.storage.dbSlimmingConfirmDescriptionWithoutBackup')}+ </p>+ </div>+ <div className="mt-6 flex shrink-0 justify-end gap-2.5">+ <AlertDialog.Cancel asChild>+ <button+ type="button"+ className={cn(+ 'inline-flex min-w-[96px] items-center justify-center rounded-full border px-6 py-2.5 text-13 font-medium',+ 'border-[var(--confirm-btn-secondary-border)] text-[var(--confirm-btn-secondary-text)]',+ 'transition-colors hover:bg-[var(--confirm-btn-secondary-hover)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ )}+ >+ {t('settings.about.storage.cancelButton')}+ </button>+ </AlertDialog.Cancel>+ <button+ ref={confirmButtonRef}+ type="button"+ disabled={insufficientSpace || scanned.messageCount === 0}+ onClick={onConfirm}+ className={cn(+ 'inline-flex min-w-[96px] items-center justify-center rounded-full px-6 py-2.5 text-13 font-medium',+ 'bg-[hsl(var(--destructive))] text-[var(--accent-pure-cta-fg)]',+ 'transition-colors hover:opacity-90',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ )}+ >+ {t('settings.about.storage.dbSlimmingConfirmButton')}+ </button>+ </div>+ </>+ )+ )}+ </AlertDialog.Content>+ </AlertDialog.Overlay>+ </AlertDialog.Portal>+ </AlertDialog.Root>+ );+}+function ReportLine({ visible, text }: { visible: boolean; text: string }) {if (!visible) return null;return <p className="text-12 leading-[1.5] text-[var(--settings-section-sublabel)]">{text}</p>;@@ -391,18 +904,25 @@ function CardButton({children,onClick,emphasis = false,+ disabled = false,+ busy = false,}: {children: React.ReactNode;onClick: () => void;emphasis?: boolean;+ disabled?: boolean;+ busy?: boolean;}) {return (<buttontype="button"onClick={onClick}+ disabled={disabled}+ aria-busy={busy || undefined}className={cn(- 'shrink-0 rounded-full px-2.5 py-1 text-12 font-medium transition-colors',+ 'inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-12 font-medium transition-colors','border border-[var(--settings-theme-card-border)]',+ 'disabled:cursor-not-allowed disabled:opacity-50',emphasis? 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)] border-transparent hover:opacity-90': 'text-[var(--settings-section-title)] hover:bg-[var(--settings-theme-card-border)]/40',diff --git a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsxindex 9925514e52..5b376003f2 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const { toast } = vi.hoisted(() => ({@@ -39,13 +39,39 @@ function storageApi() {};}+function maintenanceApi() {+ return {+ getLastResult: vi.fn(async () => null),+ scan: vi.fn(async (input: { archiveAgeMonths: '7-days' | 1 | 3 | 6 }) => ({+ scanId: 'scan-1',+ archiveAgeMonths: input.archiveAgeMonths,+ scannedAt: 1_000,+ archivedBeforeMs: 500,+ deletedTaskCount: 1,+ archivedTaskCount: 2,+ messageCount: 3,+ estimatedMessageBytes: 100,+ databaseBytes: 1_000,+ temporaryBytesRequired: 2_000,+ databaseVolumeFreeBytes: 10_000,+ })),+ chooseBackupDirectory: vi.fn(async () => ({+ selected: true as const,+ grantId: 'directory-grant',+ displayPath: 'D:\\Backups',+ })),+ schedule: vi.fn(async () => ({ scheduled: true as const })),+ openLastBackupDirectory: vi.fn(async () => ({ opened: true })),+ };+}+beforeEach(() => {toast.success.mockReset();toast.error.mockReset();toast.info.mockReset();Object.defineProperty(window, 'electronAPI', {configurable: true,- value: { cindyMediaStorage: storageApi() },+ value: { cindyMediaStorage: storageApi(), localDb: { maintenance: maintenanceApi() } },});});@@ -157,3 +183,223 @@ describe('StorageManagementCard fixed cache directories', () => {});});});++describe('StorageManagementCard database cleanup', () => {+ it('maps serialized IPC scan failures to localized messages', async () => {+ vi.mocked(window.electronAPI.localDb.maintenance.scan).mockRejectedValueOnce(+ new Error(+ 'Error invoking remote method: Error: [PRECONDITION_FAILED] active database owner changed',+ ),+ );+ render(<StorageManagementCard />);++ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.dbSlimmingScanButton' }),+ );++ await waitFor(() => {+ expect(toast.error).toHaveBeenCalledWith('ipcError.PRECONDITION_FAILED');+ });+ expect(toast.error).not.toHaveBeenCalledWith(+ expect.stringContaining('active database owner changed'),+ );+ });++ it('maps serialized IPC scheduling failures to localized messages', async () => {+ vi.mocked(window.electronAPI.localDb.maintenance.schedule).mockRejectedValueOnce(+ new Error(+ 'Error invoking remote method: Error: [PRECONDITION_FAILED] active database owner changed',+ ),+ );+ render(<StorageManagementCard />);++ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.dbSlimmingScanButton' }),+ );+ await screen.findByRole('alertdialog', {+ name: 'settings.about.storage.dbSlimmingScanResultTitle',+ });+ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.dbSlimmingConfirmButton' }),+ );++ await waitFor(() => {+ expect(toast.error).toHaveBeenCalledWith('ipcError.PRECONDITION_FAILED');+ });+ expect(toast.error).not.toHaveBeenCalledWith(+ expect.stringContaining('active database owner changed'),+ );+ });++ it('offers only 7 days, 1 month, 3 months, and 6 months, defaulting to 7 days', async () => {+ render(<StorageManagementCard />);++ const threshold = screen.getByRole('combobox');+ expect(threshold.textContent).toContain(+ 'settings.about.storage.dbSlimmingArchiveAgeOption7Days',+ );+ fireEvent.click(threshold);+ const options = screen.getAllByRole('option');+ expect(options.map((option) => option.textContent)).toEqual([+ 'settings.about.storage.dbSlimmingArchiveAgeOption7Days',+ 'settings.about.storage.dbSlimmingArchiveAgeOption1',+ 'settings.about.storage.dbSlimmingArchiveAgeOption3',+ 'settings.about.storage.dbSlimmingArchiveAgeOption6',+ ]);+ fireEvent.click(options[0]!);+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');+ fireEvent.click(screen.getByText('settings.about.storage.dbSlimmingBackupLabel'));+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false');+ fireEvent.click(screen.getByText('settings.about.storage.dbSlimmingBackupLabel'));+ const scanButton = screen.getByRole('button', {+ name: 'settings.about.storage.dbSlimmingScanButton',+ });+ fireEvent.click(scanButton);++ await waitFor(() => {+ expect(window.electronAPI.localDb.maintenance.scan).toHaveBeenCalledWith({+ archiveAgeMonths: '7-days',+ });+ });+ await waitFor(() => expect(scanButton.getAttribute('aria-busy')).toBeNull());+ expect(+ await screen.findByRole('alertdialog', {+ name: 'settings.about.storage.dbSlimmingScanResultTitle',+ }),+ ).toBeTruthy();+ });++ it('locks the full window while a database scan is running, then shows results in a dialog', async () => {+ let resolveScan!: (value: Awaited<ReturnType<ReturnType<typeof maintenanceApi>['scan']>>) => void;+ vi.mocked(window.electronAPI.localDb.maintenance.scan).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveScan = resolve;+ }),+ );+ render(<StorageManagementCard />);++ const scanButton = screen.getByRole('button', {+ name: 'settings.about.storage.dbSlimmingScanButton',+ });+ fireEvent.click(scanButton);++ await waitFor(() => {+ expect(scanButton.getAttribute('aria-busy')).toBe('true');+ expect((scanButton as HTMLButtonElement).disabled).toBe(true);+ });+ const persistentDialog = screen.getByRole('alertdialog', {+ name: 'settings.about.storage.dbSlimmingScanLoading',+ });+ expect(persistentDialog.className).not.toContain('animate-confirm');+ expect(persistentDialog.parentElement?.className ?? '').not.toContain('animate-confirm');+ expect(document.body.dataset.appInteractionLocked).toBe('1');++ await act(async () => {+ resolveScan({+ scanId: 'scan-busy',+ archiveAgeMonths: '7-days',+ scannedAt: 1_000,+ archivedBeforeMs: 500,+ deletedTaskCount: 1,+ archivedTaskCount: 2,+ messageCount: 3,+ estimatedMessageBytes: 100,+ databaseBytes: 1_000,+ temporaryBytesRequired: 2_000,+ databaseVolumeFreeBytes: 10_000,+ });+ });+ await waitFor(() => expect((scanButton as HTMLButtonElement).disabled).toBe(false));+ const report = await screen.findByText('settings.about.storage.dbSlimmingReportTasks');+ const resultDialog = report.closest('[role="alertdialog"]');+ expect(resultDialog).toBe(persistentDialog);+ const confirmButton = screen.getByRole('button', {+ name: 'settings.about.storage.dbSlimmingConfirmButton',+ });+ await waitFor(() => expect(document.activeElement).toBe(confirmButton));+ expect(+ screen.queryByRole('alertdialog', {+ name: 'settings.about.storage.dbSlimmingScanLoading',+ }),+ ).toBeNull();+ expect(document.body.dataset.appInteractionLocked).toBe('1');+ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.cancelButton' }),+ );+ await waitFor(() => expect(document.body.dataset.appInteractionLocked).toBeUndefined());+ });++ it('passes only main-issued scan and directory grants and stays locked while restarting', async () => {+ render(<StorageManagementCard />);++ fireEvent.click(+ screen.getByRole('button', {+ name: 'settings.about.storage.dbSlimmingChooseDirectoryButton',+ }),+ );+ await waitFor(() => {+ expect(window.electronAPI.localDb.maintenance.chooseBackupDirectory).toHaveBeenCalledWith();+ });+ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.dbSlimmingScanButton' }),+ );+ await screen.findByText('settings.about.storage.dbSlimmingReportTasks');+ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.dbSlimmingConfirmButton' }),+ );++ await waitFor(() => {+ expect(window.electronAPI.localDb.maintenance.schedule).toHaveBeenCalledWith({+ scanId: 'scan-1',+ backupEnabled: true,+ backupDirectoryGrantId: 'directory-grant',+ });+ });+ expect(+ await screen.findByRole('alertdialog', {+ name: 'settings.about.storage.dbSlimmingExecutionLoading',+ }),+ ).toBeTruthy();+ expect(document.body.dataset.appInteractionLocked).toBe('1');+ });++ it('restores the locked scan result when restart scheduling is cancelled', async () => {+ vi.mocked(window.electronAPI.localDb.maintenance.schedule).mockResolvedValueOnce({+ scheduled: false,+ });+ render(<StorageManagementCard />);++ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.dbSlimmingScanButton' }),+ );+ await screen.findByRole('alertdialog', {+ name: 'settings.about.storage.dbSlimmingScanResultTitle',+ });+ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.dbSlimmingConfirmButton' }),+ );++ await waitFor(() => {+ expect(window.electronAPI.localDb.maintenance.schedule).toHaveBeenCalledWith({+ scanId: 'scan-1',+ backupEnabled: true,+ });+ expect(+ screen.queryByRole('alertdialog', {+ name: 'settings.about.storage.dbSlimmingExecutionLoading',+ }),+ ).toBeNull();+ });+ expect(+ await screen.findByRole('alertdialog', {+ name: 'settings.about.storage.dbSlimmingScanResultTitle',+ }),+ ).toBeTruthy();+ expect(document.body.dataset.appInteractionLocked).toBe('1');+ fireEvent.click(+ screen.getByRole('button', { name: 'settings.about.storage.cancelButton' }),+ );+ await waitFor(() => expect(document.body.dataset.appInteractionLocked).toBeUndefined());+ });+});diff --git a/apps/desktop/src/renderer/components/splash/SplashScreen.tsx b/apps/desktop/src/renderer/components/splash/SplashScreen.tsxindex 2b30a3bfb7..0553f5b075 100644--- a/apps/desktop/src/renderer/components/splash/SplashScreen.tsx+++ b/apps/desktop/src/renderer/components/splash/SplashScreen.tsx@@ -1,5 +1,9 @@import { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import type {+ DbSlimmingStartupPhase,+ DbSlimmingStartupProgress,+} from '../../../shared/localDbMaintenance';import { cn } from '@/lib/utils';import {@@ -15,7 +19,12 @@ import { useReducedMotion } from '@/hooks/useReducedMotion';import { WindowControls } from '@/components/title-bar/WindowControls';import { desktopScale } from '@/components/login/loginScale';import { useViewportSize } from '@/components/login/LoginStage';-import { LoginPanel, LoginPrimaryButton, LoginTitleBlock } from '@/components/login/LoginControls';+import {+ LoginPanel,+ LoginPrimaryButton,+ LoginTextLink,+ LoginTitleBlock,+} from '@/components/login/LoginControls';import {LOGIN_COLORS,LOGIN_GROUP,@@ -89,6 +98,27 @@ function splashTitleFor(}}+function dbCleanupPhaseTranslationKey(phase: DbSlimmingStartupPhase): string {+ switch (phase) {+ case 'preparing':+ return 'splash.databaseCleanup.phase.preparing';+ case 'backing-up':+ return 'splash.databaseCleanup.phase.backingUp';+ case 'copying':+ return 'splash.databaseCleanup.phase.copying';+ case 'cleaning':+ return 'splash.databaseCleanup.phase.cleaning';+ case 'compacting':+ return 'splash.databaseCleanup.phase.compacting';+ case 'verifying':+ return 'splash.databaseCleanup.phase.verifying';+ case 'finalizing':+ return 'splash.databaseCleanup.phase.finalizing';+ case 'cancelling':+ return 'splash.databaseCleanup.phase.cancelling';+ }+}+export function SplashScreen() {const { t } = useTranslation();const splash = useSplash();@@ -97,10 +127,41 @@ export function SplashScreen() {const reducedMotion = useReducedMotion();const handoff = useLoginHandoff();const [shellCoverFading, setShellCoverFading] = useState(false);+ const [dbCleanupProgress, setDbCleanupProgress] =+ useState<DbSlimmingStartupProgress | null>(null);+ const [dbCleanupNow, setDbCleanupNow] = useState(() => Date.now());+ const [dbCleanupCancelPending, setDbCleanupCancelPending] = useState(false);const prevCoverHeldRef = useRef(coverHeld);const { width, height } = useViewportSize();const { scale } = desktopScale(width, height);+ useEffect(() => {+ const maintenance = window.electronAPI?.localDb?.maintenance;+ if (!maintenance?.onStartupProgress || !maintenance.getStartupProgress) return;+ let disposed = false;+ const applyProgress = (progress: DbSlimmingStartupProgress | null) => {+ if (disposed) return;+ setDbCleanupProgress(progress);+ setDbCleanupNow(Date.now());+ if (!progress || progress.phase !== 'cancelling') setDbCleanupCancelPending(false);+ };+ const unsubscribe = maintenance.onStartupProgress(applyProgress);+ void maintenance.getStartupProgress().then(applyProgress, () => {+ // Startup presentation is best-effort; ensureReady remains the source of truth.+ });+ return () => {+ disposed = true;+ unsubscribe();+ };+ }, []);++ useEffect(() => {+ if (!dbCleanupProgress) return;+ setDbCleanupNow(Date.now());+ const timer = window.setInterval(() => setDbCleanupNow(Date.now()), 1_000);+ return () => window.clearInterval(timer);+ }, [dbCleanupProgress?.requestId]);+// dev fixture 只改显示 phase(附录 A splash 行;PROD 恒 null)。const fixture = readSplashPhaseFixture();const realPhase = splash.phase;@@ -161,7 +222,7 @@ export function SplashScreen() {useEffect(() => {const root = document.documentElement;- if (splashLifecycleActive || shellCoverVisible) {+ if (splashLifecycleActive || shellCoverVisible || dbCleanupProgress) {root.setAttribute('data-splash-active', '1');} else {root.removeAttribute('data-splash-active');@@ -169,7 +230,7 @@ export function SplashScreen() {return () => {root.removeAttribute('data-splash-active');};- }, [shellCoverVisible, splashLifecycleActive]);+ }, [dbCleanupProgress, shellCoverVisible, splashLifecycleActive]);// handoff 推进锚之一:Splash 开始退场(fading_out/done/skipped)即上报。const splashExitReportedRef = useRef(false);@@ -187,17 +248,26 @@ export function SplashScreen() {// dev fixture 激活时冻结停留:真实生命周期跑完也不退场,供状态遍历/视觉走查// (readSplashPhaseFixture 在 PROD 恒 null,本分支不可达)。- if (!fixture && (realPhase === 'splash_done' || realPhase === 'splash_skipped') && !shellCoverVisible) {+ if (+ !fixture &&+ (realPhase === 'splash_done' || realPhase === 'splash_skipped') &&+ !shellCoverVisible &&+ !dbCleanupProgress+ ) {return null;}const isMac = window.electronAPI?.platform === 'darwin';- const title = splashTitleFor(displayPhase, t, step, totalSteps);+ const title = dbCleanupProgress+ ? t('splash.databaseCleanup.title')+ : splashTitleFor(displayPhase, t, step, totalSteps);// 进度条仅更新下载态面板形态(updating/downloading);fixture 模式按显示 phase。- const isDownloading = fixture- ? displayPhase === 'splash_updating' || displayPhase === 'splash_downloading'- : realIsDownloading;+ const isDownloading =+ !dbCleanupProgress &&+ (fixture+ ? displayPhase === 'splash_updating' || displayPhase === 'splash_downloading'+ : realIsDownloading);// fixture 冻结走查没有真实下载遥测,给进度行一组演示数据看排版// (dev-only:readSplashPhaseFixture 在 PROD 恒 null,本分支不可达)。const statsProgress = fixture && !realIsDownloading ? 31 : downloadProgress;@@ -222,13 +292,38 @@ export function SplashScreen() {? 'spawn': null;const isEnvFailed = displayPhase === 'splash_failed';- const showSpinner = dialogKind === null && !isEnvFailed;+ const showSpinner = !dbCleanupProgress && dialogKind === null && !isEnvFailed;+ const dbCleanupPercent = dbCleanupProgress+ ? Math.round(Math.min(100, Math.max(0, dbCleanupProgress.progress)))+ : 0;+ const dbCleanupElapsedMs = dbCleanupProgress+ ? Math.max(0, dbCleanupNow - dbCleanupProgress.startedAt)+ : 0;+ const dbCleanupRemainingMs = dbCleanupProgress+ ? Math.max(0, dbCleanupProgress.estimatedTotalMs - dbCleanupElapsedMs)+ : 0;+ const formatDbCleanupDuration = (milliseconds: number): string => {+ const seconds = Math.max(1, Math.ceil(milliseconds / 1_000));+ if (seconds < 60) return t('splash.databaseCleanup.duration.seconds', { count: seconds });+ return t('splash.databaseCleanup.duration.minutes', { count: Math.ceil(seconds / 60) });+ };+ const requestDbCleanupCancel = (): void => {+ const maintenance = window.electronAPI?.localDb?.maintenance;+ if (!maintenance?.cancelStartup || !dbCleanupProgress?.cancellable) return;+ setDbCleanupCancelPending(true);+ void maintenance.cancelStartup().then(+ (result) => {+ if (!result.cancelled) setDbCleanupCancelPending(false);+ },+ () => setDbCleanupCancelPending(false),+ );+ };return (<divclassName={cn('fixed inset-0 z-[9999] overflow-hidden',- (realPhase === 'fading_out' || shellCoverFading) && !fixture+ (realPhase === 'fading_out' || shellCoverFading) && !fixture && !dbCleanupProgress? 'pointer-events-none opacity-0': 'opacity-100',)}@@ -245,7 +340,7 @@ export function SplashScreen() {>{/* Toolbar:z-10(关闭/最小化,仅 Windows 原生 chrome) */}<div className="relative z-10 flex h-[46px] shrink-0 items-center justify-end px-2">- {!isMac && (+ {!isMac && !dbCleanupProgress && (<div style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}><WindowControls /></div>@@ -289,7 +384,9 @@ export function SplashScreen() {// 距 spinner(y=188)/主按钮(y=300)均有余量。subtitleMaxLines={3}subtitle={- dialogKind === 'manifest'+ dbCleanupProgress+ ? `${t(dbCleanupPhaseTranslationKey(dbCleanupProgress.phase))} · ${dbCleanupPercent}%`+ : dialogKind === 'manifest'? t('splash.manifestFailed.description'): dialogKind === 'download'? t('splash.downloadFailed.description')@@ -380,6 +477,91 @@ export function SplashScreen() {</>)}+ {dbCleanupProgress && (+ <>+ <div+ role="progressbar"+ aria-label={t('splash.databaseCleanup.progressLabel')}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={dbCleanupPercent}+ data-testid="database-cleanup-progress-track"+ className="absolute overflow-hidden"+ style={{+ left: SPLASH_PANEL.progress.x,+ top: SPLASH_PANEL.databaseCleanup.progressY,+ width: SPLASH_PANEL.progress.width,+ height: SPLASH_PANEL.progress.height,+ borderRadius: SPLASH_PANEL.progress.radius,+ background: LOGIN_COLORS.splashProgressTrack,+ }}+ >+ <div+ data-testid="database-cleanup-progress-fill"+ className="h-full transition-[width] duration-300 motion-reduce:transition-none"+ style={{+ width: `${dbCleanupPercent}%`,+ borderRadius: SPLASH_PANEL.progress.radius,+ background: LOGIN_COLORS.splashProgressFill,+ }}+ />+ </div>+ <div+ data-testid="database-cleanup-time"+ className="absolute flex items-center justify-center"+ style={{+ left: SPLASH_PANEL.stats.x,+ top: SPLASH_PANEL.databaseCleanup.statsY,+ width: SPLASH_PANEL.stats.width,+ height: SPLASH_PANEL.stats.height,+ fontSize: SPLASH_PANEL.stats.fontSize,+ color: LOGIN_COLORS.secondaryText,+ }}+ >+ {dbCleanupProgress.phase === 'finalizing'+ ? t('splash.databaseCleanup.elapsedFinalizing', {+ elapsed: formatDbCleanupDuration(dbCleanupElapsedMs),+ })+ : t('splash.databaseCleanup.elapsedAndRemaining', {+ elapsed: formatDbCleanupDuration(dbCleanupElapsedMs),+ remaining: formatDbCleanupDuration(dbCleanupRemainingMs),+ })}+ </div>+ <LoginTextLink+ testId="database-cleanup-cancel"+ top={SPLASH_PANEL.databaseCleanup.actionY}+ height={SPLASH_PANEL.databaseCleanup.actionHeight}+ disabled={!dbCleanupProgress.cancellable || dbCleanupCancelPending}+ onClick={requestDbCleanupCancel}+ >+ {dbCleanupProgress.phase === 'cancelling' || dbCleanupCancelPending+ ? t('splash.databaseCleanup.cancellingAction')+ : dbCleanupProgress.phase === 'finalizing'+ ? t('splash.databaseCleanup.finalizingAction')+ : t('splash.databaseCleanup.cancelAction')}+ </LoginTextLink>+ <div+ data-testid="database-cleanup-safety-hint"+ className="absolute flex items-center justify-center text-center"+ style={{+ left: SPLASH_PANEL.databaseCleanup.hint.x,+ top: SPLASH_PANEL.databaseCleanup.hint.y,+ width: SPLASH_PANEL.databaseCleanup.hint.width,+ height: SPLASH_PANEL.databaseCleanup.hint.height,+ fontSize: SPLASH_PANEL.databaseCleanup.hint.fontSize,+ lineHeight: `${SPLASH_PANEL.databaseCleanup.hint.lineHeight}px`,+ color: LOGIN_COLORS.secondaryText,+ }}+ >+ {dbCleanupProgress.phase === 'finalizing'+ ? t('splash.databaseCleanup.finalizingHint')+ : dbCleanupProgress.phase === 'cancelling'+ ? t('splash.databaseCleanup.cancellingHint')+ : t('splash.databaseCleanup.cancelHint')}+ </div>+ </>+ )}+{/* failed(379:655):主按钮「重试」540×80@70,300 → checkEnvironment(useSplash onTipsClick 现网动作,零删改) */}{isEnvFailed && (diff --git a/apps/desktop/src/renderer/components/splash/__tests__/SplashScreen.test.tsx b/apps/desktop/src/renderer/components/splash/__tests__/SplashScreen.test.tsxindex 1f7f8405cc..8507233a49 100644--- a/apps/desktop/src/renderer/components/splash/__tests__/SplashScreen.test.tsx+++ b/apps/desktop/src/renderer/components/splash/__tests__/SplashScreen.test.tsx@@ -4,8 +4,9 @@ import { readFileSync } from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';-import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { DbSlimmingStartupProgress } from '../../../../shared/localDbMaintenance';/*** SplashScreen wave4 统一面板版测试(implementation-plan Step 3b WHAT1/WHAT3)。@@ -98,6 +99,42 @@ function renderSplash(phase: string) {return render(<SplashScreen />);}+function installDatabaseCleanupApi(+ progress: DbSlimmingStartupProgress,+ cancelStartup = vi.fn(async () => ({ cancelled: true })),+) {+ let listener: ((next: DbSlimmingStartupProgress | null) => void) | null = null;+ (+ window as unknown as {+ electronAPI: {+ platform: string;+ localDb: {+ maintenance: {+ getStartupProgress: () => Promise<DbSlimmingStartupProgress | null>;+ cancelStartup: () => Promise<{ cancelled: boolean }>;+ onStartupProgress: (+ callback: (next: DbSlimmingStartupProgress | null) => void,+ ) => () => void;+ };+ };+ };+ }+ ).electronAPI = {+ platform: 'win32',+ localDb: {+ maintenance: {+ getStartupProgress: vi.fn(async () => progress),+ cancelStartup,+ onStartupProgress: vi.fn((callback) => {+ listener = callback;+ return vi.fn();+ }),+ },+ },+ };+ return { cancelStartup, emit: (next: DbSlimmingStartupProgress | null) => listener?.(next) };+}+function panel(): HTMLElement {return screen.getByTestId('splash-panel');}@@ -323,6 +360,26 @@ describe('SplashScreen wave4 统一面板', () => {'spawnFailed.title','spawnFailed.description','spawnFailed.confirm',+ 'databaseCleanup.title',+ 'databaseCleanup.progressLabel',+ 'databaseCleanup.phase.preparing',+ 'databaseCleanup.phase.backingUp',+ 'databaseCleanup.phase.copying',+ 'databaseCleanup.phase.cleaning',+ 'databaseCleanup.phase.compacting',+ 'databaseCleanup.phase.verifying',+ 'databaseCleanup.phase.finalizing',+ 'databaseCleanup.phase.cancelling',+ 'databaseCleanup.elapsedAndRemaining',+ 'databaseCleanup.elapsedFinalizing',+ 'databaseCleanup.duration.seconds',+ 'databaseCleanup.duration.minutes',+ 'databaseCleanup.cancelAction',+ 'databaseCleanup.cancellingAction',+ 'databaseCleanup.finalizingAction',+ 'databaseCleanup.cancelHint',+ 'databaseCleanup.cancellingHint',+ 'databaseCleanup.finalizingHint',];for (const locale of ['zh-CN', 'zh-TW', 'en', 'ja', 'ko']) {const json = JSON.parse(@@ -408,4 +465,50 @@ describe('SplashScreen wave4 统一面板', () => {view.rerender(<SplashScreen />);expect(view.container.firstElementChild).toBeNull();});++ it('shows startup database cleanup progress, time estimate, and a safe cancel action', async () => {+ const progress: DbSlimmingStartupProgress = {+ requestId: 'request-1',+ phase: 'compacting',+ progress: 72,+ cancellable: true,+ startedAt: Date.now() - 5_000,+ updatedAt: Date.now(),+ estimatedTotalMs: 15_000,+ };+ const api = installDatabaseCleanupApi(progress);+ mocks.coverHeld = true;+ renderSplash('splash_done');++ expect(await screen.findByText('splash.databaseCleanup.title')).toBeTruthy();+ expect(screen.getByText('splash.databaseCleanup.phase.compacting · 72%')).toBeTruthy();+ expect(screen.getByTestId('database-cleanup-progress-fill').style.width).toBe('72%');+ expect(screen.getByTestId('database-cleanup-time').textContent).toBe(+ 'splash.databaseCleanup.elapsedAndRemaining',+ );+ expect(screen.queryByTestId('window-controls')).toBeNull();+ fireEvent.click(screen.getByTestId('database-cleanup-cancel'));+ await waitFor(() => expect(api.cancelStartup).toHaveBeenCalledTimes(1));+ });++ it('disables cancellation while the compacted database is being installed', async () => {+ installDatabaseCleanupApi({+ requestId: 'request-1',+ phase: 'finalizing',+ progress: 96,+ cancellable: false,+ startedAt: Date.now() - 5_000,+ updatedAt: Date.now(),+ estimatedTotalMs: 6_000,+ });+ mocks.coverHeld = true;+ renderSplash('splash_done');++ const cancel = await screen.findByTestId('database-cleanup-cancel');+ expect((cancel as HTMLButtonElement).disabled).toBe(true);+ expect(cancel.textContent).toBe('splash.databaseCleanup.finalizingAction');+ expect(screen.getByTestId('database-cleanup-safety-hint').textContent).toBe(+ 'splash.databaseCleanup.finalizingHint',+ );+ });});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 18274696b5..f87128a281 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -4125,6 +4125,7 @@ export function CCAgentSessionView({workingDir={session?.workingDir ?? ''}messages={messages}historyLoaded={historyLoaded}+ historyCleared={Boolean(session?.clearedAt)}taskUpdates={taskUpdates}isSessionStreaming={isStreaming}continuationTurnClientId={continuationTurnClientId}diff --git a/apps/desktop/src/renderer/hooks/__tests__/useAppShortcut.interactionLock.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useAppShortcut.interactionLock.test.tsxnew file mode 100644index 0000000000..561ed9ceb1--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useAppShortcut.interactionLock.test.tsx@@ -0,0 +1,42 @@+// @vitest-environment jsdom++import { cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.mock('../../../shared/appShortcuts', () => ({+ formatAppShortcutCombo: () => '',+ matchesKeyboardEvent: () => true,+}));++vi.mock('../../lib/appShortcutStore', () => ({+ getAppShortcutCombos: () => [{}],+ getAppShortcutPlatform: () => 'win32',+ subscribeAppShortcuts: () => () => undefined,+}));++import { useAppShortcut } from '../useAppShortcut';+import { acquireAppInteractionLock } from '../../lib/appInteractionLock';++afterEach(cleanup);++describe('useAppShortcut interaction lock', () => {+ it('consumes matching shortcuts without invoking handlers while the app is locked', () => {+ const handler = vi.fn(() => true);+ function Harness() {+ useAppShortcut('toggle-sidebar', handler);+ return null;+ }+ render(<Harness />);++ const release = acquireAppInteractionLock();+ try {+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true });+ window.dispatchEvent(event);++ expect(handler).not.toHaveBeenCalled();+ expect(event.defaultPrevented).toBe(true);+ } finally {+ release();+ }+ });+});diff --git a/apps/desktop/src/renderer/hooks/useAppShortcut.ts b/apps/desktop/src/renderer/hooks/useAppShortcut.tsindex 867bc849c6..f15d4b412b 100644--- a/apps/desktop/src/renderer/hooks/useAppShortcut.ts+++ b/apps/desktop/src/renderer/hooks/useAppShortcut.ts@@ -10,6 +10,7 @@ import {getAppShortcutPlatform,subscribeAppShortcuts,} from '../lib/appShortcutStore';+import { isAppInteractionLocked } from '../lib/appInteractionLock';export interface UseAppShortcutOptions {/** false 时不挂监听 (如 BrowserTabBody 仅 active tab 响应)。默认 true。 */@@ -53,6 +54,12 @@ export function useAppShortcut(const combos = getAppShortcutCombos(id);if (combos.length === 0) return;if (!combos.some((combo) => matchesKeyboardEvent(event, combo))) return;+ if (isAppInteractionLocked()) {+ event.preventDefault();+ event.stopPropagation();+ if (stopImmediate) event.stopImmediatePropagation();+ return;+ }if (!handlerRef.current(event)) return;event.preventDefault();event.stopPropagation();diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ee830e2bf6..e0ca6cffc7 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,6 +1,7 @@{"ipcError": {"INVALID_PARAMS": "Invalid input. Please check and try again.",+ "PRECONDITION_FAILED": "This action is unavailable in the current state. Please try again.","SESSION_RUNNING": "This session is currently running a task. Please try again shortly.","PI_IMAGE_INPUT_UNSUPPORTED": "Image input is not enabled for the current Pi model. Switch to a model that supports images. For a custom model, enable “Supports image input” in provider settings, then start a new Pi task.","CREDENTIAL_SWITCH_BUSY": "Another Codex task is still running, so this provider switch was not applied (the session keeps its previous provider). Try again after those tasks finish.",@@ -39,6 +40,12 @@"details": "Error details"},"localDbFatal": {+ "databaseCleanup": {+ "interruptedTitle": "Database Cleanup Was Interrupted",+ "interruptedDescription": "Database cleanup stopped unexpectedly. Restart Cindy so it can recover safely from the saved maintenance state.",+ "recoveryFailedTitle": "The Local Database Couldn't Be Recovered Safely",+ "recoveryFailedDescription": "Database cleanup recovery failed. Cindy stopped opening the local database to avoid overwriting the original data."+ },"updateReady": {"title": "Update required to continue","description": "Your local data was upgraded by a newer version of Cindy and can't be opened by this version. The new version is downloaded and ready — restart to install it and get back in.",@@ -843,7 +850,52 @@"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.",+ "chatAttachmentsClearFailed": "Could not clean up the message attachment cache. Try again.",+ "dbSlimmingBackupDirectoryDialogTitle": "Choose database cleanup backup folder",+ "dbSlimmingLabel": "Database cleanup",+ "dbSlimmingDescription": "Scan message history in soft-deleted tasks and long-archived tasks. After confirmation, Cindy restarts and compacts the database before opening it. Files and generated media on disk are not deleted.",+ "dbSlimmingScanButton": "Scan database",+ "dbSlimmingScanLoading": "Scanning the database…",+ "dbSlimmingScanResultTitle": "Database scan results",+ "dbSlimmingExecutionLoading": "Preparing database cleanup. Cindy will restart shortly…",+ "dbSlimmingArchiveAgeLabel": "Clean tasks archived for more than",+ "dbSlimmingArchiveAgeOption7Days": "7 days",+ "dbSlimmingArchiveAgeOption1": "1 month",+ "dbSlimmingArchiveAgeOption3": "3 months",+ "dbSlimmingArchiveAgeOption6": "6 months",+ "dbSlimmingBackupLabel": "Back up database before cleanup",+ "dbSlimmingBackupDefaultLocation": "Database folder (keeps only the latest cleanup backup)",+ "dbSlimmingUseDefaultDirectoryButton": "Use default folder",+ "dbSlimmingChooseDirectoryButton": "Choose backup folder",+ "dbSlimmingBackupDirectoryFailed": "Could not choose a backup folder. Try again.",+ "dbSlimmingScanFailed": "Could not scan the database. Try again.",+ "dbSlimmingScheduleFailed": "Could not schedule database cleanup. Scan again and retry.",+ "dbSlimmingBackupMissing": "The latest cleanup backup could not be found.",+ "dbSlimmingBackupOpenFailed": "Could not open the cleanup backup location. Try again.",+ "dbSlimmingReportTasks": "Will clean {{deleted}} soft-deleted tasks and {{archived}} archived tasks",+ "dbSlimmingReportMessages": "Estimated message content to clean: {{count}} messages (about {{size}})",+ "dbSlimmingReportSpace": "Database: {{database}}; temporary space needed: at least {{temporary}}; available: {{free}}",+ "dbSlimmingSpaceUnknown": "unknown",+ "dbSlimmingInsufficientSpace": "There is not enough disk space to safely create a working copy and compact the database.",+ "dbSlimmingConfirmButton": "Confirm database cleanup",+ "dbSlimmingConfirmTitle": "Restart and clean up the database?",+ "dbSlimmingConfirmDescriptionWithBackup": "Cindy will restart gracefully, then back up, clean history, compact, and verify the database before opening it. Data is cleaned only after the backup is written and verified.",+ "dbSlimmingConfirmDescriptionWithoutBackup": "Cindy will restart gracefully, then clean and compact the database before opening it. No backup will be created, and cleaned history cannot be recovered.",+ "dbSlimmingRestartButton": "Restart and clean up database",+ "dbSlimmingResultCompleted": "Removed {{messages}} messages from {{tasks}} tasks and reduced the database by {{size}}.",+ "dbSlimmingOpenBackupButton": "Open cleanup backup",+ "dbSlimmingToastCompleted": "Database cleanup complete; freed {{size}}",+ "dbSlimmingHistoryCleared": "History has been cleared",+ "dbSlimmingFailure": {+ "backup-failed": "The database backup could not be created or retained. No history was cleaned.",+ "cleanup-failed": "Database cleanup did not finish. The original database is unchanged.",+ "database-in-use": "Another instance is using the database, so cleanup was not run.",+ "insufficient-space": "There was not enough disk space to clean up the database.",+ "integrity-check-failed": "The database integrity check failed. The original database was restored.",+ "replacement-failed": "The compacted database could not be installed. The original database was restored.",+ "recovery-failed": "Database recovery failed. Cindy stopped opening the database to protect the original data.",+ "unknown": "Database cleanup did not finish. 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",@@ -5240,6 +5292,32 @@"envFailed": "Environment setup failed — click to retry"},"downloadStats": "{{percent}}% · {{speed}} MB/s · {{done}} MB / {{total}} MB",+ "databaseCleanup": {+ "title": "Cleaning up the database",+ "progressLabel": "Database cleanup progress",+ "phase": {+ "preparing": "Preparing cleanup",+ "backingUp": "Backing up the database",+ "copying": "Creating a cleanup working copy",+ "cleaning": "Deleting expired messages",+ "compacting": "Compacting the database",+ "verifying": "Verifying the database",+ "finalizing": "Safely replacing the database",+ "cancelling": "Cancelling cleanup"+ },+ "elapsedAndRemaining": "Elapsed {{elapsed}} · About {{remaining}} remaining",+ "elapsedFinalizing": "Elapsed {{elapsed}} · Almost done",+ "duration": {+ "seconds": "{{count}} sec",+ "minutes": "{{count}} min"+ },+ "cancelAction": "Cancel cleanup and open Cindy",+ "cancellingAction": "Cancelling cleanup…",+ "finalizingAction": "Finishing up…",+ "cancelHint": "You can cancel safely. Cindy will keep the original database and continue starting.",+ "cancellingHint": "Stopping cleanup. The original database will not be changed.",+ "finalizingHint": "Safely replacing the database. Do not close Cindy."+ },"envFailed": {"title": "Environment initialization failed","retry": "Retry"diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2903a8f6a0..a39fe9e687 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,6 +1,7 @@{"ipcError": {"INVALID_PARAMS": "パラメータが無効です。確認して再試行してください。",+ "PRECONDITION_FAILED": "現在の状態ではこの操作を実行できません。しばらくしてから再試行してください。","SESSION_RUNNING": "このセッションは現在タスクを実行中です。しばらくしてからもう一度お試しください。","PI_IMAGE_INPUT_UNSUPPORTED": "現在の Pi モデルでは画像入力が有効になっていません。画像に対応するモデルへ切り替えてください。カスタムモデルの場合は、プロバイダー設定で「画像入力に対応」を有効にしてから、新しい Pi タスクを開始してください。","CREDENTIAL_SWITCH_BUSY": "他の Codex タスクが実行中のため、今回のプロバイダー切り替えは適用されませんでした(セッションは元のプロバイダーのままです)。他のタスクが終わってからもう一度お試しください。",@@ -39,6 +40,12 @@"details": "エラー詳細"},"localDbFatal": {+ "databaseCleanup": {+ "interruptedTitle": "データベースのクリーンアップが中断されました",+ "interruptedDescription": "データベースのクリーンアップが予期せず中断されました。Cindy を再起動してください。保存されたメンテナンス状態に基づいて安全に復旧します。",+ "recoveryFailedTitle": "ローカルデータベースを安全に復旧できませんでした",+ "recoveryFailedDescription": "データベースのクリーンアップから復旧できませんでした。元のデータが上書きされないように、Cindy はローカルデータベースを開く処理を停止しました。"+ },"updateReady": {"title": "続行にはアップデートが必要です","description": "ローカルデータは新しいバージョンの Cindy によって更新されているため、現在のバージョンでは開けません。新しいバージョンのダウンロードは完了しています。再起動してインストールすると復旧します。",@@ -843,7 +850,52 @@"chatAttachmentsClearConfirmDescription": "メッセージ添付ファイルのキャッシュディレクトリ内のファイルだけを削除し、メッセージデータベースは参照しません。履歴内の一部の添付ファイルを開けなくなる場合があり、この操作は元に戻せません。","chatAttachmentsClearConfirmButton": "添付ファイルキャッシュを削除","chatAttachmentsCleared": "メッセージ添付ファイルのキャッシュをクリーンアップしました",- "chatAttachmentsClearFailed": "メッセージ添付ファイルのキャッシュをクリーンアップできませんでした。もう一度お試しください。",+ "chatAttachmentsClearFailed": "メッセージ添付ファイルのキャッシュをクリーンアップできませんでした。もう一度お試しください。",+ "dbSlimmingBackupDirectoryDialogTitle": "データベースのクリーンアップ用バックアップ先を選択",+ "dbSlimmingLabel": "データベースのクリーンアップ",+ "dbSlimmingDescription": "論理削除されたタスクと長期間アーカイブされたタスクのメッセージ履歴をスキャンします。確認後に Cindy を再起動し、データベースを開く前に履歴を削除して圧縮します。ディスク上の添付ファイルや生成メディアは削除しません。",+ "dbSlimmingScanButton": "データベースをスキャン",+ "dbSlimmingScanLoading": "データベースをスキャンしています…",+ "dbSlimmingScanResultTitle": "データベースのスキャン結果",+ "dbSlimmingExecutionLoading": "データベースのクリーンアップを準備しています。Cindy はまもなく再起動します…",+ "dbSlimmingArchiveAgeLabel": "次の期間を超えてアーカイブされているタスクを整理",+ "dbSlimmingArchiveAgeOption7Days": "7 日",+ "dbSlimmingArchiveAgeOption1": "1 か月",+ "dbSlimmingArchiveAgeOption3": "3 か月",+ "dbSlimmingArchiveAgeOption6": "6 か月",+ "dbSlimmingBackupLabel": "クリーンアップ前にデータベースをバックアップ",+ "dbSlimmingBackupDefaultLocation": "データベースのフォルダ(最新のクリーンアップ用バックアップのみ保持)",+ "dbSlimmingUseDefaultDirectoryButton": "既定のフォルダを使用",+ "dbSlimmingChooseDirectoryButton": "バックアップ先を選択",+ "dbSlimmingBackupDirectoryFailed": "バックアップ先を選択できませんでした。もう一度お試しください。",+ "dbSlimmingScanFailed": "データベースをスキャンできませんでした。もう一度お試しください。",+ "dbSlimmingScheduleFailed": "データベースのクリーンアップを予約できませんでした。再スキャンしてお試しください。",+ "dbSlimmingBackupMissing": "最新のクリーンアップ用バックアップが見つかりません。",+ "dbSlimmingBackupOpenFailed": "クリーンアップ用バックアップの場所を開けませんでした。もう一度お試しください。",+ "dbSlimmingReportTasks": "論理削除タスク {{deleted}} 件、アーカイブ済みタスク {{archived}} 件を削除します",+ "dbSlimmingReportMessages": "削除予定のメッセージ内容:{{count}} 件(約 {{size}})",+ "dbSlimmingReportSpace": "データベース {{database}}、必要な一時領域は最低 {{temporary}}、空き容量 {{free}}",+ "dbSlimmingSpaceUnknown": "不明",+ "dbSlimmingInsufficientSpace": "作業コピーを安全に作成してデータベースを圧縮するための空き容量がありません。",+ "dbSlimmingConfirmButton": "データベースのクリーンアップを確認",+ "dbSlimmingConfirmTitle": "再起動してデータベースをクリーンアップしますか?",+ "dbSlimmingConfirmDescriptionWithBackup": "Cindy を正常に再起動し、次回起動時にデータベースを開く前にバックアップ、履歴削除、圧縮、整合性確認を行います。バックアップの書き込みと検証が完了するまでデータは削除しません。",+ "dbSlimmingConfirmDescriptionWithoutBackup": "Cindy を正常に再起動し、次回起動時にデータベースを開く前に履歴を削除して圧縮します。今回はバックアップを作成しないため、削除した履歴は復元できません。",+ "dbSlimmingRestartButton": "再起動してデータベースをクリーンアップ",+ "dbSlimmingResultCompleted": "{{tasks}} 件のタスクから {{messages}} 件のメッセージを削除し、データベースを {{size}} 縮小しました。",+ "dbSlimmingOpenBackupButton": "クリーンアップ用バックアップを開く",+ "dbSlimmingToastCompleted": "データベースのクリーンアップが完了し、{{size}} 解放しました",+ "dbSlimmingHistoryCleared": "履歴は削除されました",+ "dbSlimmingFailure": {+ "backup-failed": "データベースのバックアップを作成または保持できなかったため、履歴は削除していません。",+ "cleanup-failed": "データベースのクリーンアップは完了しませんでした。元のデータベースは変更されていません。",+ "database-in-use": "別のインスタンスがデータベースを使用しているため、クリーンアップを実行しませんでした。",+ "insufficient-space": "空き容量が不足しているため、データベースのクリーンアップを実行しませんでした。",+ "integrity-check-failed": "整合性確認に失敗したため、元のデータベースを復元しました。",+ "replacement-failed": "圧縮後のデータベースを配置できなかったため、元のデータベースを復元しました。",+ "recovery-failed": "データベースの復元に失敗しました。元データを保護するため、Cindy はデータベースを開いていません。",+ "unknown": "データベースのクリーンアップは完了しませんでした。もう一度お試しください。"+ },"cleanupLabel": "ディスククリーンアップ","cleanupDescription": "どのセッションからも参照されていないメディアファイル、上限を超えたキャッシュ、不要になったフォルダをスキャンします。まず件数を表示し、確認後にのみ削除します。入力欄の下書きや送信待ちメッセージ内の画像は自動的に保護されます。","scanButton": "スキャン",@@ -5238,6 +5290,32 @@"envFailed": "環境の初期化に失敗しました。クリックして再試行してください"},"downloadStats": "{{percent}}% · {{speed}} MB/s · {{done}} MB / {{total}} MB",+ "databaseCleanup": {+ "title": "データベースをクリーンアップ中",+ "progressLabel": "データベースのクリーンアップ進行状況",+ "phase": {+ "preparing": "クリーンアップを準備中",+ "backingUp": "データベースをバックアップ中",+ "copying": "クリーンアップ用の作業コピーを作成中",+ "cleaning": "期限切れメッセージを削除中",+ "compacting": "データベースを圧縮中",+ "verifying": "データベースを検証中",+ "finalizing": "データベースを安全に置き換え中",+ "cancelling": "クリーンアップをキャンセル中"+ },+ "elapsedAndRemaining": "経過 {{elapsed}} · 残り約 {{remaining}}",+ "elapsedFinalizing": "経過 {{elapsed}} · まもなく完了",+ "duration": {+ "seconds": "{{count}} 秒",+ "minutes": "{{count}} 分"+ },+ "cancelAction": "キャンセルして Cindy を開く",+ "cancellingAction": "キャンセル中…",+ "finalizingAction": "完了処理中…",+ "cancelHint": "安全にキャンセルできます。元のデータベースを保持して Cindy の起動を続けます。",+ "cancellingHint": "クリーンアップを停止中です。元のデータベースは変更されません。",+ "finalizingHint": "データベースを安全に置き換えています。Cindy を終了しないでください。"+ },"envFailed": {"title": "環境の初期化に失敗しました","retry": "再試行"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex cfe90709d4..ffb9e35390 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,6 +1,7 @@{"ipcError": {"INVALID_PARAMS": "매개변수가 잘못되었습니다. 확인 후 다시 시도하세요.",+ "PRECONDITION_FAILED": "현재 상태에서는 이 작업을 수행할 수 없습니다. 잠시 후 다시 시도하세요.","SESSION_RUNNING": "이 세션은 현재 작업을 실행 중입니다. 잠시 후 다시 시도해 주세요.","PI_IMAGE_INPUT_UNSUPPORTED": "현재 Pi 모델에는 이미지 입력이 활성화되어 있지 않습니다. 이미지를 지원하는 모델로 전환하세요. 사용자 지정 모델이라면 제공자 설정에서 ‘이미지 입력 지원’을 켠 다음 새 Pi 작업을 시작하세요.","CREDENTIAL_SWITCH_BUSY": "다른 Codex 작업이 실행 중이어서 이번 제공자 전환은 적용되지 않았습니다(세션은 기존 제공자를 유지합니다). 다른 작업이 끝난 후 다시 시도해 주세요.",@@ -39,6 +40,12 @@"details": "오류 정보"},"localDbFatal": {+ "databaseCleanup": {+ "interruptedTitle": "데이터베이스 정리가 중단되었습니다",+ "interruptedDescription": "데이터베이스 정리가 예기치 않게 중단되었습니다. Cindy를 다시 시작하면 저장된 유지 관리 상태를 바탕으로 안전하게 복구합니다.",+ "recoveryFailedTitle": "로컬 데이터베이스를 안전하게 복구할 수 없습니다",+ "recoveryFailedDescription": "데이터베이스 정리 복구에 실패했습니다. 원본 데이터를 덮어쓰지 않도록 Cindy가 로컬 데이터베이스 열기를 중단했습니다."+ },"updateReady": {"title": "계속하려면 업데이트가 필요합니다","description": "로컬 데이터가 더 새로운 버전의 Cindy에 의해 업그레이드되어 현재 버전에서는 열 수 없습니다. 새 버전 다운로드가 완료되었으니 재시작하여 설치하면 복구됩니다.",@@ -843,7 +850,52 @@"chatAttachmentsClearConfirmDescription": "메시지 첨부 파일 캐시 디렉터리의 파일만 삭제하며 메시지 데이터베이스는 조회하지 않습니다. 메시지 기록의 일부 첨부 파일을 열 수 없게 될 수 있으며 이 작업은 되돌릴 수 없습니다.","chatAttachmentsClearConfirmButton": "첨부 파일 캐시 정리","chatAttachmentsCleared": "메시지 첨부 파일 캐시를 정리했습니다",- "chatAttachmentsClearFailed": "메시지 첨부 파일 캐시를 정리할 수 없습니다. 다시 시도해 주세요.",+ "chatAttachmentsClearFailed": "메시지 첨부 파일 캐시를 정리할 수 없습니다. 다시 시도해 주세요.",+ "dbSlimmingBackupDirectoryDialogTitle": "데이터베이스 정리 백업 폴더 선택",+ "dbSlimmingLabel": "데이터베이스 정리",+ "dbSlimmingDescription": "소프트 삭제된 작업과 오래 보관된 작업의 메시지 기록을 검사합니다. 확인 후 Cindy를 다시 시작하고 데이터베이스를 열기 전에 기록을 정리하고 압축합니다. 디스크의 첨부 파일과 생성 미디어는 삭제하지 않습니다.",+ "dbSlimmingScanButton": "데이터베이스 검사",+ "dbSlimmingScanLoading": "데이터베이스를 검사하는 중…",+ "dbSlimmingScanResultTitle": "데이터베이스 검사 결과",+ "dbSlimmingExecutionLoading": "데이터베이스 정리를 준비하고 있습니다. Cindy가 곧 다시 시작됩니다…",+ "dbSlimmingArchiveAgeLabel": "보관 후 다음 기간이 지난 작업 정리",+ "dbSlimmingArchiveAgeOption7Days": "7일",+ "dbSlimmingArchiveAgeOption1": "1개월",+ "dbSlimmingArchiveAgeOption3": "3개월",+ "dbSlimmingArchiveAgeOption6": "6개월",+ "dbSlimmingBackupLabel": "정리 전 데이터베이스 백업",+ "dbSlimmingBackupDefaultLocation": "데이터베이스 폴더(최근 정리 백업만 유지)",+ "dbSlimmingUseDefaultDirectoryButton": "기본 폴더 사용",+ "dbSlimmingChooseDirectoryButton": "백업 폴더 선택",+ "dbSlimmingBackupDirectoryFailed": "백업 폴더를 선택할 수 없습니다. 다시 시도해 주세요.",+ "dbSlimmingScanFailed": "데이터베이스를 검사할 수 없습니다. 다시 시도해 주세요.",+ "dbSlimmingScheduleFailed": "데이터베이스 정리를 예약할 수 없습니다. 다시 검사한 후 시도해 주세요.",+ "dbSlimmingBackupMissing": "최근 정리 백업을 찾을 수 없습니다.",+ "dbSlimmingBackupOpenFailed": "정리 백업 위치를 열 수 없습니다. 다시 시도해 주세요.",+ "dbSlimmingReportTasks": "소프트 삭제 작업 {{deleted}}개와 보관된 작업 {{archived}}개를 정리합니다",+ "dbSlimmingReportMessages": "정리할 메시지 내용: {{count}}개(약 {{size}})",+ "dbSlimmingReportSpace": "데이터베이스 {{database}}, 필요한 임시 공간 최소 {{temporary}}, 사용 가능 {{free}}",+ "dbSlimmingSpaceUnknown": "알 수 없음",+ "dbSlimmingInsufficientSpace": "작업 복사본을 안전하게 만들고 데이터베이스를 압축할 디스크 공간이 부족합니다.",+ "dbSlimmingConfirmButton": "데이터베이스 정리 확인",+ "dbSlimmingConfirmTitle": "다시 시작하고 데이터베이스를 정리할까요?",+ "dbSlimmingConfirmDescriptionWithBackup": "Cindy가 정상적으로 다시 시작된 후 다음 시작 시 데이터베이스를 열기 전에 백업, 기록 정리, 압축, 무결성 검사를 수행합니다. 백업 작성과 검증이 끝난 후에만 데이터를 정리합니다.",+ "dbSlimmingConfirmDescriptionWithoutBackup": "Cindy가 정상적으로 다시 시작된 후 다음 시작 시 데이터베이스를 열기 전에 기록을 정리하고 압축합니다. 이번에는 백업을 만들지 않으며 정리한 기록은 복구할 수 없습니다.",+ "dbSlimmingRestartButton": "다시 시작하고 데이터베이스 정리",+ "dbSlimmingResultCompleted": "{{tasks}}개 작업에서 메시지 {{messages}}개를 정리하고 데이터베이스를 {{size}} 줄였습니다.",+ "dbSlimmingOpenBackupButton": "정리 백업 열기",+ "dbSlimmingToastCompleted": "데이터베이스 정리 완료, {{size}} 확보",+ "dbSlimmingHistoryCleared": "기록이 정리되었습니다",+ "dbSlimmingFailure": {+ "backup-failed": "데이터베이스 백업을 만들거나 유지할 수 없어 기록을 정리하지 않았습니다.",+ "cleanup-failed": "데이터베이스 정리가 완료되지 않았습니다. 원본 데이터베이스는 변경되지 않았습니다.",+ "database-in-use": "다른 인스턴스가 데이터베이스를 사용 중이어서 정리를 실행하지 않았습니다.",+ "insufficient-space": "디스크 공간이 부족해 데이터베이스 정리를 실행하지 않았습니다.",+ "integrity-check-failed": "데이터베이스 무결성 검사에 실패해 원본 데이터베이스를 복원했습니다.",+ "replacement-failed": "압축된 데이터베이스를 설치할 수 없어 원본 데이터베이스를 복원했습니다.",+ "recovery-failed": "데이터베이스 복구에 실패했습니다. 원본 데이터를 보호하기 위해 Cindy가 데이터베이스를 열지 않았습니다.",+ "unknown": "데이터베이스 정리가 완료되지 않았습니다. 다시 시도해 주세요."+ },"cleanupLabel": "디스크 정리","cleanupDescription": "어떤 세션에서도 참조하지 않는 미디어 파일, 한도를 초과한 캐시, 사용하지 않는 폴더를 검사합니다. 먼저 수치를 보여주고 확인 후에만 삭제합니다. 입력창 초안과 대기 중인 메시지의 이미지는 자동으로 보호됩니다.","scanButton": "검사",@@ -5238,6 +5290,32 @@"envFailed": "환경 초기화에 실패했습니다. 클릭하여 다시 시도하세요"},"downloadStats": "{{percent}}% · {{speed}} MB/s · {{done}} MB / {{total}} MB",+ "databaseCleanup": {+ "title": "데이터베이스 정리 중",+ "progressLabel": "데이터베이스 정리 진행률",+ "phase": {+ "preparing": "정리 준비 중",+ "backingUp": "데이터베이스 백업 중",+ "copying": "정리용 작업 복사본 생성 중",+ "cleaning": "만료된 메시지 삭제 중",+ "compacting": "데이터베이스 압축 중",+ "verifying": "데이터베이스 확인 중",+ "finalizing": "데이터베이스를 안전하게 교체 중",+ "cancelling": "정리 취소 중"+ },+ "elapsedAndRemaining": "경과 {{elapsed}} · 약 {{remaining}} 남음",+ "elapsedFinalizing": "경과 {{elapsed}} · 곧 완료",+ "duration": {+ "seconds": "{{count}}초",+ "minutes": "{{count}}분"+ },+ "cancelAction": "취소하고 Cindy 열기",+ "cancellingAction": "정리 취소 중…",+ "finalizingAction": "마무리 중…",+ "cancelHint": "안전하게 취소할 수 있습니다. 원본 데이터베이스를 유지하고 Cindy를 계속 시작합니다.",+ "cancellingHint": "정리를 중지하고 있습니다. 원본 데이터베이스는 변경되지 않습니다.",+ "finalizingHint": "데이터베이스를 안전하게 교체하고 있습니다. Cindy를 종료하지 마세요."+ },"envFailed": {"title": "환경 초기화에 실패했습니다","retry": "다시 시도"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex adcb5a0438..b52c065ca5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,6 +1,7 @@{"ipcError": {"INVALID_PARAMS": "参数无效,请检查后重试。",+ "PRECONDITION_FAILED": "当前状态下无法执行此操作,请稍后重试。","SESSION_RUNNING": "当前任务正在运行,请稍后再试。","PI_IMAGE_INPUT_UNSUPPORTED": "当前 Pi 模型未启用图片输入。请切换到支持图片的模型;如果这是自定义模型,请在供应商设置中开启“支持图片输入”,然后新建 Pi 任务。","CREDENTIAL_SWITCH_BUSY": "Codex 正在其它任务中运行,本次来源切换未生效(本任务仍使用原来源)。等它结束后再试。",@@ -39,6 +40,12 @@"details": "错误详情"},"localDbFatal": {+ "databaseCleanup": {+ "interruptedTitle": "数据库清理中断",+ "interruptedDescription": "数据库清理异常中断。请重新启动 Cindy,系统会根据维护记录安全恢复。",+ "recoveryFailedTitle": "本地数据库无法安全恢复",+ "recoveryFailedDescription": "数据库清理恢复失败,Cindy 已停止打开本地数据库以避免覆盖原始数据。"+ },"updateReady": {"title": "需要更新后才能继续","description": "本地数据已由更新版本的 Cindy 升级,当前版本无法打开。新版本已下载就绪,重启安装后即可恢复使用。",@@ -842,9 +849,54 @@"chatAttachmentsClearConfirmTitle": "清理消息附件缓存?","chatAttachmentsClearConfirmDescription": "只会删除消息附件缓存目录中的文件,不会读取消息数据库。清理后,历史消息中的部分附件可能无法打开,且无法恢复。","chatAttachmentsClearConfirmButton": "清理附件缓存",- "chatAttachmentsCleared": "消息附件缓存已清理",- "chatAttachmentsClearFailed": "无法清理消息附件缓存,请重试",- "cleanupLabel": "磁盘清理",+ "chatAttachmentsCleared": "消息附件缓存已清理",+ "chatAttachmentsClearFailed": "无法清理消息附件缓存,请重试",+ "dbSlimmingBackupDirectoryDialogTitle": "选择数据库清理备份目录",+ "dbSlimmingLabel": "数据库清理",+ "dbSlimmingDescription": "扫描软删除任务和长时间归档任务中的历史消息,确认后重启 Cindy,在数据库打开前清理并压缩。不会删除磁盘附件或生成媒体。",+ "dbSlimmingScanButton": "扫描数据库",+ "dbSlimmingScanLoading": "正在扫描数据库,请稍候…",+ "dbSlimmingScanResultTitle": "数据库扫描结果",+ "dbSlimmingExecutionLoading": "正在准备数据库清理,Cindy 即将重启…",+ "dbSlimmingArchiveAgeLabel": "清理归档时间超过",+ "dbSlimmingArchiveAgeOption7Days": "7 天",+ "dbSlimmingArchiveAgeOption1": "1 个月",+ "dbSlimmingArchiveAgeOption3": "3 个月",+ "dbSlimmingArchiveAgeOption6": "6 个月",+ "dbSlimmingBackupLabel": "清理前备份数据库",+ "dbSlimmingBackupDefaultLocation": "数据库所在目录(只保留最近一次清理备份)",+ "dbSlimmingUseDefaultDirectoryButton": "使用默认目录",+ "dbSlimmingChooseDirectoryButton": "选择备份目录",+ "dbSlimmingBackupDirectoryFailed": "无法选择备份目录,请重试",+ "dbSlimmingScanFailed": "无法扫描数据库,请重试",+ "dbSlimmingScheduleFailed": "无法安排数据库清理,请重新扫描后重试",+ "dbSlimmingBackupMissing": "没有找到最近一次清理备份",+ "dbSlimmingBackupOpenFailed": "无法打开清理备份位置,请重试",+ "dbSlimmingReportTasks": "将清理软删除任务 {{deleted}} 个、归档任务 {{archived}} 个",+ "dbSlimmingReportMessages": "预计清理 {{count}} 条消息内容(约 {{size}})",+ "dbSlimmingReportSpace": "数据库 {{database}};临时空间至少需要 {{temporary}};当前可用 {{free}}",+ "dbSlimmingSpaceUnknown": "未知",+ "dbSlimmingInsufficientSpace": "当前磁盘空间不足,无法安全创建工作副本并压缩数据库。",+ "dbSlimmingConfirmButton": "确认数据库清理",+ "dbSlimmingConfirmTitle": "重启并清理数据库?",+ "dbSlimmingConfirmDescriptionWithBackup": "Cindy 将优雅重启,并在下次启动、数据库打开前完成备份、历史清理、压缩和完整性校验。备份写入并校验通过后才会清理数据。",+ "dbSlimmingConfirmDescriptionWithoutBackup": "Cindy 将优雅重启,并在下次启动、数据库打开前清理和压缩。本次不创建备份,清除的历史内容无法恢复。",+ "dbSlimmingRestartButton": "重启并清理数据库",+ "dbSlimmingResultCompleted": "已清除 {{tasks}} 个任务中的 {{messages}} 条消息,数据库缩小 {{size}}。",+ "dbSlimmingOpenBackupButton": "打开清理备份",+ "dbSlimmingToastCompleted": "数据库清理完成,已释放 {{size}}",+ "dbSlimmingHistoryCleared": "历史内容已清除",+ "dbSlimmingFailure": {+ "backup-failed": "未能创建或保留数据库备份,未清理历史内容。",+ "cleanup-failed": "数据库清理未完成,原数据库保持不变。",+ "database-in-use": "数据库正被其他实例使用,未执行清理。",+ "insufficient-space": "磁盘空间不足,未执行数据库清理。",+ "integrity-check-failed": "数据库完整性校验未通过,已恢复原数据库。",+ "replacement-failed": "无法安装压缩后的数据库,已恢复原数据库。",+ "recovery-failed": "数据库恢复失败,Cindy 已停止打开数据库以保护原始数据。",+ "unknown": "数据库清理未完成,请重试。"+ },+ "cleanupLabel": "磁盘清理","cleanupDescription": "扫描没有被任何任务引用的媒体文件、超限缓存与废弃目录。先报数,确认后才删除;输入框草稿和排队消息里的图片会被自动保护。","scanButton": "扫描","scanFailed": "扫描失败",@@ -5230,6 +5282,32 @@"envFailed": "环境初始化失败,点击重试"},"downloadStats": "{{percent}}% · {{speed}} MB/s · {{done}} MB / {{total}} MB",+ "databaseCleanup": {+ "title": "正在清理数据库",+ "progressLabel": "数据库清理进度",+ "phase": {+ "preparing": "正在准备清理",+ "backingUp": "正在备份数据库",+ "copying": "正在创建清理工作副本",+ "cleaning": "正在删除过期消息",+ "compacting": "正在压缩数据库",+ "verifying": "正在校验数据库",+ "finalizing": "正在安全替换数据库",+ "cancelling": "正在取消清理"+ },+ "elapsedAndRemaining": "已用 {{elapsed}} · 约剩余 {{remaining}}",+ "elapsedFinalizing": "已用 {{elapsed}} · 即将完成",+ "duration": {+ "seconds": "{{count}} 秒",+ "minutes": "{{count}} 分钟"+ },+ "cancelAction": "取消清理并进入 Cindy",+ "cancellingAction": "正在取消清理…",+ "finalizingAction": "正在完成,请稍候…",+ "cancelHint": "可随时取消;取消后会保留原数据库并继续启动 Cindy。",+ "cancellingHint": "正在停止清理,原数据库不会被修改。",+ "finalizingHint": "正在安全替换数据库,请勿关闭 Cindy。"+ },"envFailed": {"title": "环境初始化失败","retry": "重试"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 61d97563d8..3ffdd860dc 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1,6 +1,7 @@{"ipcError": {"INVALID_PARAMS": "引數無效,請檢查後重試。",+ "PRECONDITION_FAILED": "目前狀態下無法執行此操作,請稍後再試。","SESSION_RUNNING": "當前任務正在執行,請稍後再試。","PI_IMAGE_INPUT_UNSUPPORTED": "當前 Pi 模型未啟用圖片輸入。請切換到支援圖片的模型;如果這是自定義模型,請在供應商設定中開啟“支援圖片輸入”,然後新建 Pi 任務。","CREDENTIAL_SWITCH_BUSY": "Codex 正在其它任務中執行,本次來源切換未生效(本任務仍使用原來源)。等它結束後再試。",@@ -39,6 +40,12 @@"details": "錯誤詳情"},"localDbFatal": {+ "databaseCleanup": {+ "interruptedTitle": "資料庫清理中斷",+ "interruptedDescription": "資料庫清理異常中斷。請重新啟動 Cindy,系統會根據維護記錄安全復原。",+ "recoveryFailedTitle": "無法安全復原本地資料庫",+ "recoveryFailedDescription": "資料庫清理復原失敗,Cindy 已停止開啟本地資料庫,以避免覆寫原始資料。"+ },"updateReady": {"title": "需要更新後才能繼續","description": "本地資料已由更新版本的 Cindy 升級,當前版本無法開啟。新版本已下載就緒,重啟安裝後即可恢復使用。",@@ -842,9 +849,54 @@"chatAttachmentsClearConfirmTitle": "清理訊息附件快取?","chatAttachmentsClearConfirmDescription": "只會刪除訊息附件快取目錄中的檔案,不會讀取訊息資料庫。清理後,歷史訊息中的部分附件可能無法開啟,且無法復原。","chatAttachmentsClearConfirmButton": "清理附件快取",- "chatAttachmentsCleared": "訊息附件快取已清理",- "chatAttachmentsClearFailed": "無法清理訊息附件快取,請重試",- "cleanupLabel": "磁碟清理",+ "chatAttachmentsCleared": "訊息附件快取已清理",+ "chatAttachmentsClearFailed": "無法清理訊息附件快取,請重試",+ "dbSlimmingBackupDirectoryDialogTitle": "選擇資料庫清理備份目錄",+ "dbSlimmingLabel": "資料庫清理",+ "dbSlimmingDescription": "掃描軟刪除任務和長時間封存任務中的歷史訊息,確認後重新啟動 Cindy,在資料庫開啟前清理並壓縮。不會刪除磁碟附件或生成媒體。",+ "dbSlimmingScanButton": "掃描資料庫",+ "dbSlimmingScanLoading": "正在掃描資料庫,請稍候…",+ "dbSlimmingScanResultTitle": "資料庫掃描結果",+ "dbSlimmingExecutionLoading": "正在準備資料庫清理,Cindy 即將重新啟動…",+ "dbSlimmingArchiveAgeLabel": "清理封存時間超過",+ "dbSlimmingArchiveAgeOption7Days": "7 天",+ "dbSlimmingArchiveAgeOption1": "1 個月",+ "dbSlimmingArchiveAgeOption3": "3 個月",+ "dbSlimmingArchiveAgeOption6": "6 個月",+ "dbSlimmingBackupLabel": "清理前備份資料庫",+ "dbSlimmingBackupDefaultLocation": "資料庫所在目錄(只保留最近一次清理備份)",+ "dbSlimmingUseDefaultDirectoryButton": "使用預設目錄",+ "dbSlimmingChooseDirectoryButton": "選擇備份目錄",+ "dbSlimmingBackupDirectoryFailed": "無法選擇備份目錄,請重試",+ "dbSlimmingScanFailed": "無法掃描資料庫,請重試",+ "dbSlimmingScheduleFailed": "無法安排資料庫清理,請重新掃描後重試",+ "dbSlimmingBackupMissing": "找不到最近一次清理備份",+ "dbSlimmingBackupOpenFailed": "無法開啟清理備份位置,請重試",+ "dbSlimmingReportTasks": "將清理軟刪除任務 {{deleted}} 個、封存任務 {{archived}} 個",+ "dbSlimmingReportMessages": "預計清理 {{count}} 則訊息內容(約 {{size}})",+ "dbSlimmingReportSpace": "資料庫 {{database}};暫存空間至少需要 {{temporary}};目前可用 {{free}}",+ "dbSlimmingSpaceUnknown": "未知",+ "dbSlimmingInsufficientSpace": "目前磁碟空間不足,無法安全建立工作副本並壓縮資料庫。",+ "dbSlimmingConfirmButton": "確認資料庫清理",+ "dbSlimmingConfirmTitle": "重新啟動並清理資料庫?",+ "dbSlimmingConfirmDescriptionWithBackup": "Cindy 將正常重新啟動,並在下次啟動、資料庫開啟前完成備份、歷史清理、壓縮和完整性檢查。備份寫入並通過檢查後才會清理資料。",+ "dbSlimmingConfirmDescriptionWithoutBackup": "Cindy 將正常重新啟動,並在下次啟動、資料庫開啟前清理和壓縮。本次不建立備份,清除的歷史內容無法復原。",+ "dbSlimmingRestartButton": "重新啟動並清理資料庫",+ "dbSlimmingResultCompleted": "已清除 {{tasks}} 個任務中的 {{messages}} 則訊息,資料庫縮小 {{size}}。",+ "dbSlimmingOpenBackupButton": "開啟清理備份",+ "dbSlimmingToastCompleted": "資料庫清理完成,已釋放 {{size}}",+ "dbSlimmingHistoryCleared": "歷史內容已清除",+ "dbSlimmingFailure": {+ "backup-failed": "未能建立或保留資料庫備份,未清理歷史內容。",+ "cleanup-failed": "資料庫清理未完成,原資料庫保持不變。",+ "database-in-use": "資料庫正被其他執行個體使用,未執行清理。",+ "insufficient-space": "磁碟空間不足,未執行資料庫清理。",+ "integrity-check-failed": "資料庫完整性檢查未通過,已復原原資料庫。",+ "replacement-failed": "無法安裝壓縮後的資料庫,已復原原資料庫。",+ "recovery-failed": "資料庫復原失敗,Cindy 已停止開啟資料庫以保護原始資料。",+ "unknown": "資料庫清理未完成,請重試。"+ },+ "cleanupLabel": "磁碟清理","cleanupDescription": "掃描沒有被任何任務引用的媒體檔案、超限快取與廢棄目錄。先報數,確認後才刪除;輸入框草稿和排隊訊息裡的圖片會被自動保護。","scanButton": "掃描","scanFailed": "掃描失敗",@@ -5230,6 +5282,32 @@"envFailed": "環境初始化失敗,點選重試"},"downloadStats": "{{percent}}% · {{speed}} MB/s · {{done}} MB / {{total}} MB",+ "databaseCleanup": {+ "title": "正在清理資料庫",+ "progressLabel": "資料庫清理進度",+ "phase": {+ "preparing": "正在準備清理",+ "backingUp": "正在備份資料庫",+ "copying": "正在建立清理工作副本",+ "cleaning": "正在刪除過期訊息",+ "compacting": "正在壓縮資料庫",+ "verifying": "正在驗證資料庫",+ "finalizing": "正在安全替換資料庫",+ "cancelling": "正在取消清理"+ },+ "elapsedAndRemaining": "已用 {{elapsed}} · 約剩 {{remaining}}",+ "elapsedFinalizing": "已用 {{elapsed}} · 即將完成",+ "duration": {+ "seconds": "{{count}} 秒",+ "minutes": "{{count}} 分鐘"+ },+ "cancelAction": "取消清理並進入 Cindy",+ "cancellingAction": "正在取消清理…",+ "finalizingAction": "即將完成,請稍候…",+ "cancelHint": "可隨時取消;取消後會保留原資料庫並繼續啟動 Cindy。",+ "cancellingHint": "正在停止清理,原資料庫不會被修改。",+ "finalizingHint": "正在安全替換資料庫,請勿關閉 Cindy。"+ },"envFailed": {"title": "環境初始化失敗","retry": "重試"diff --git a/apps/desktop/src/renderer/lib/appInteractionLock.ts b/apps/desktop/src/renderer/lib/appInteractionLock.tsnew file mode 100644index 0000000000..0cd2e28ec3--- /dev/null+++ b/apps/desktop/src/renderer/lib/appInteractionLock.ts@@ -0,0 +1,26 @@+const activeLocks = new Set<symbol>();++function syncInteractionLockMarker(): void {+ if (activeLocks.size > 0) {+ document.body.dataset.appInteractionLocked = '1';+ return;+ }+ delete document.body.dataset.appInteractionLocked;+}++export function acquireAppInteractionLock(): () => void {+ const token = Symbol('app-interaction-lock');+ activeLocks.add(token);+ syncInteractionLockMarker();+ let released = false;+ return () => {+ if (released) return;+ released = true;+ activeLocks.delete(token);+ syncInteractionLockMarker();+ };+}++export function isAppInteractionLocked(): boolean {+ return activeLocks.size > 0;+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 3d5f12119c..82fcaba8c5 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4246,6 +4246,32 @@ interface ElectronAPI {};}>;+ maintenance: {+ scan: (+ input: import('../shared/localDbMaintenance').DbSlimmingScanInput,+ ) => Promise<import('../shared/localDbMaintenance').DbSlimmingScanResult>;+ chooseBackupDirectory: () => Promise<+ import('../shared/localDbMaintenance').DbSlimmingBackupDirectorySelection+ >;+ schedule: (+ input: import('../shared/localDbMaintenance').DbSlimmingScheduleInput,+ ) => Promise<import('../shared/localDbMaintenance').DbSlimmingScheduleResult>;+ getLastResult: () => Promise<+ import('../shared/localDbMaintenance').DbSlimmingResult | null+ >;+ openLastBackupDirectory: () => Promise<{ opened: boolean }>;+ getStartupProgress: () => Promise<+ import('../shared/localDbMaintenance').DbSlimmingStartupProgress | null+ >;+ cancelStartup: () => Promise<+ import('../shared/localDbMaintenance').DbSlimmingStartupCancelResult+ >;+ onStartupProgress: (+ callback: (+ progress: import('../shared/localDbMaintenance').DbSlimmingStartupProgress | null,+ ) => void,+ ) => () => void;+ };sessions: {list: (limit?: number,diff --git a/apps/desktop/src/shared/localDbMaintenance.ts b/apps/desktop/src/shared/localDbMaintenance.tsnew file mode 100644index 0000000000..d6651fbb1a--- /dev/null+++ b/apps/desktop/src/shared/localDbMaintenance.ts@@ -0,0 +1,103 @@+export const DB_SLIMMING_ARCHIVE_AGE_OPTIONS = ['7-days', 1, 3, 6] as const;+export type DbSlimmingArchiveAge = (typeof DB_SLIMMING_ARCHIVE_AGE_OPTIONS)[number];+export const DB_SLIMMING_DEFAULT_ARCHIVE_AGE: DbSlimmingArchiveAge = '7-days';+export const DB_SLIMMING_STARTUP_PROGRESS_CHANGED_CHANNEL =+ 'local-db:maintenance:startup-progress-changed';++export type DbSlimmingBackupLocation = 'database-directory' | 'custom-directory';++export interface DbSlimmingScanInput {+ /** Legacy wire key retained so existing numeric month requests stay readable. */+ archiveAgeMonths: DbSlimmingArchiveAge;+}++export interface DbSlimmingScanResult {+ scanId: string;+ archiveAgeMonths: DbSlimmingArchiveAge;+ scannedAt: number;+ archivedBeforeMs: number;+ deletedTaskCount: number;+ archivedTaskCount: number;+ messageCount: number;+ estimatedMessageBytes: number;+ databaseBytes: number;+ temporaryBytesRequired: number;+ databaseVolumeFreeBytes: number | null;+}++export interface DbSlimmingBackupDirectorySelection {+ selected: boolean;+ grantId?: string;+ displayPath?: string;+}++export interface DbSlimmingScheduleInput {+ scanId: string;+ backupEnabled: boolean;+ backupDirectoryGrantId?: string;+}++export type DbSlimmingScheduleResult = { scheduled: true } | { scheduled: false };++export type DbSlimmingStartupPhase =+ | 'preparing'+ | 'backing-up'+ | 'copying'+ | 'cleaning'+ | 'compacting'+ | 'verifying'+ | 'finalizing'+ | 'cancelling';++export interface DbSlimmingMaintenanceProgress {+ phase: Exclude<DbSlimmingStartupPhase, 'cancelling'>;+ progress: number;+ cancellable: boolean;+}++/** Renderer-safe startup projection. It intentionally contains no database or backup path. */+export interface DbSlimmingStartupProgress+ extends Omit<DbSlimmingMaintenanceProgress, 'phase'> {+ requestId: string;+ phase: DbSlimmingStartupPhase;+ startedAt: number;+ updatedAt: number;+ estimatedTotalMs: number;+}++export interface DbSlimmingStartupCancelResult {+ cancelled: boolean;+}++export type DbSlimmingFailureReason =+ | 'backup-failed'+ | 'cleanup-failed'+ | 'database-in-use'+ | 'insufficient-space'+ | 'integrity-check-failed'+ | 'replacement-failed'+ | 'recovery-failed';++export type DbSlimmingResult =+ | {+ id: string;+ status: 'completed';+ finishedAt: number;+ archiveAgeMonths: DbSlimmingArchiveAge;+ deletedTaskCount: number;+ archivedTaskCount: number;+ messageCount: number;+ beforeBytes: number;+ afterBytes: number;+ reclaimedBytes: number;+ backupCreated: boolean;+ backupLocation?: DbSlimmingBackupLocation;+ }+ | {+ id: string;+ status: 'failed';+ finishedAt: number;+ archiveAgeMonths: DbSlimmingArchiveAge;+ reason: DbSlimmingFailureReason;+ originalDatabaseRestored: boolean;+ };diff --git a/apps/desktop/vite.db-slimming-worker.config.ts b/apps/desktop/vite.db-slimming-worker.config.tsnew file mode 100644index 0000000000..9a79b0f218--- /dev/null+++ b/apps/desktop/vite.db-slimming-worker.config.ts@@ -0,0 +1,42 @@+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { defineConfig } from 'vite';++const configDir = path.dirname(fileURLToPath(import.meta.url));++export default defineConfig({+ resolve: {+ alias: [+ {+ find: /^better-sqlite3$/,+ replacement: path.join(+ configDir,+ 'src',+ 'main',+ 'localDb',+ 'dbSlimmingBetterSqlite.ts',+ ),+ },+ {+ find: /^\.\.\/logger$/,+ replacement: path.join(+ configDir,+ 'src',+ 'main',+ 'localDb',+ 'dbSlimmingWorkerLogger.ts',+ ),+ },+ ],+ conditions: ['node'],+ mainFields: ['module', 'jsnext:main', 'jsnext'],+ },+ build: {+ rollupOptions: {+ external: [+ 'sqlite-vec',+ 'drizzle-orm/better-sqlite3',+ ],+ },+ },+});diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex ac8e125936..9db34d31e0 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -203,6 +203,10 @@ Cindy 在 X 上发出的那条公开回复。zh-CN 取「回帖」以强调它应用异常终止。此前只出现在内部日志里, 随日志上报进入用户可见文案, 因此登记。ko 取音译「크래시」而非「충돌」——后者在韩语里更常指冲突/碰撞(如合并冲突), 会与 merge conflict 语境混读。proposed。+### Database cleanup++设置 → 存储空间内主动备份、清理非活跃任务消息并压缩本地数据库的功能名称。先登记为 proposed,待实际使用后再固化。+### ReleaseCindyDev 内部设置中的正式业务服务器环境标签,五语固定保留英文 Release。它表示 App 当前连接哪套服务,不代表安装包发行版本、OTA 通道或 cn / global 区域;因 release 也是普通英文单词,关闭全局大小写扫描,具体 UI key 由 Mobile 定向测试约束。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex a97bc18fc8..dd4d6d3e14 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -1794,6 +1794,18 @@"ko": "로컬 모델"},"note": "用户机器上运行的开源权重模型(经 Ollama / LM Studio 等本机 runtime)。刻意不用「本地模型」——「本地模式」已废弃,指未登录 Cindy 账号;「本机」强调权重和推理都在用户这台电脑上。设置页本机模型分组、Ollama 详情副标题使用。proposed:等本机模型入口上线后再固化。"+ },+ {+ "id": "database-cleanup",+ "status": "proposed",+ "en": "Database cleanup",+ "translations": {+ "zh-CN": "数据库清理",+ "zh-TW": "資料庫清理",+ "ja": "データベースのクリーンアップ",+ "ko": "데이터베이스 정리"+ },+ "note": "设置 → 存储空间内主动备份、清理非活跃任务消息并压缩本地数据库的功能名称。先登记为 proposed,待实际使用后再固化。"}]}diff --git a/scripts/desktop-dev-runner.mjs b/scripts/desktop-dev-runner.mjsindex 162a2d2405..531c5ff8cf 100644--- a/scripts/desktop-dev-runner.mjs+++ b/scripts/desktop-dev-runner.mjs@@ -5,6 +5,7 @@*/import { spawn } from 'node:child_process';import fs from 'node:fs';+import os from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -27,39 +28,88 @@ const invocation = resolvePnpmInvocation([devScript], {npmExecPath: usablePnpmExecPath(process.env.npm_execpath, fs.existsSync),});const { command, args } = invocation;+const relaunchSignalPath = path.join(+ os.tmpdir(),+ `cindy-desktop-dev-relaunch-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.json`,+);+const restartedRequestIds = new Set();-const child = spawn(command, args, {- cwd: rootDir,- env: { ...process.env, COREPACK_ENABLE_AUTO_PIN: '0', ...(invocation.env ?? {}) },- stdio: 'inherit',- windowsHide: false,- shell: invocation.shell,- windowsVerbatimArguments: invocation.windowsVerbatimArguments,-});+startChild();-child.once('error', (error) => {- writeFailedStatus({ exitCode: null, error: error.message });- console.error(`desktop-dev-runner: ${error.message}`);- process.exit(1);-});+function startChild() {+ const child = spawn(command, args, {+ cwd: rootDir,+ env: {+ ...process.env,+ COREPACK_ENABLE_AUTO_PIN: '0',+ XDT_DESKTOP_DEV_RELAUNCH_SIGNAL_FILE: relaunchSignalPath,+ ...(invocation.env ?? {}),+ },+ stdio: 'inherit',+ windowsHide: false,+ shell: invocation.shell,+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,+ });-child.once('exit', (code, signal) => {- const statusPath = process.env.XDT_DESKTOP_DEV_STARTUP_STATUS_FILE;- const existing = statusPath ? readStatus(statusPath) : null;- if (statusPath) {- if (existing?.state === 'ready' || existing?.state === 'abandoned' || !existing) {- fs.rmSync(statusPath, { force: true });- } else if (existing.state !== 'failed') {- writeFailedStatus({ exitCode: code, signal });+ child.once('error', (error) => {+ fs.rmSync(relaunchSignalPath, { force: true });+ writeFailedStatus({ exitCode: null, error: error.message });+ console.error(`desktop-dev-runner: ${error.message}`);+ process.exit(1);+ });++ child.once('exit', (code, signal) => {+ const relaunchRequest = consumeRelaunchRequest();+ if (relaunchRequest && !restartedRequestIds.has(relaunchRequest.requestId)) {+ restartedRequestIds.add(relaunchRequest.requestId);+ console.log(+ `desktop-dev-runner: restarting Forge/Vite for database cleanup ${relaunchRequest.requestId}`,+ );+ startChild();+ return;+ }+ if (relaunchRequest) {+ console.error(+ `desktop-dev-runner: refused repeated database cleanup relaunch ${relaunchRequest.requestId}`,+ );+ }++ const statusPath = process.env.XDT_DESKTOP_DEV_STARTUP_STATUS_FILE;+ const existing = statusPath ? readStatus(statusPath) : null;+ if (statusPath) {+ if (existing?.state === 'ready' || existing?.state === 'abandoned' || !existing) {+ fs.rmSync(statusPath, { force: true });+ } else if (existing.state !== 'failed') {+ writeFailedStatus({ exitCode: code, signal });+ }}- }- if (signal && process.platform !== 'win32') {- process.kill(process.pid, signal);- return;+ if (signal && process.platform !== 'win32') {+ process.kill(process.pid, signal);+ return;+ }+ process.exit(code ?? 1);+ });+}++function consumeRelaunchRequest() {+ try {+ const value = JSON.parse(fs.readFileSync(relaunchSignalPath, 'utf8'));+ if (+ value?.version !== 1 ||+ typeof value.requestId !== 'string' ||+ value.requestId.length === 0 ||+ value.requestId.length > 128+ ) {+ return null;+ }+ return { requestId: value.requestId };+ } catch {+ return null;+ } finally {+ fs.rmSync(relaunchSignalPath, { force: true });}- process.exit(code ?? 1);-});+}function readStatus(statusPath) {try {