Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 支持清理活跃任务历史 (#3547)

DavidShenXD81a38db43d01
diff --git a/apps/desktop/src/main/__tests__/dbSlimmingIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/dbSlimmingIpcSecurity.test.ts
index 147db33b1e..8b088ba5f7 100644
--- a/apps/desktop/src/main/__tests__/dbSlimmingIpcSecurity.test.ts
+++ b/apps/desktop/src/main/__tests__/dbSlimmingIpcSecurity.test.ts
@@ -33,7 +33,7 @@ describe('database slimming IPC security wiring', () => {
}
});
- it('keeps unexpected maintenance details in Main and requires native no-backup consent', () => {
+ it('keeps unexpected maintenance details in Main and requires native destructive consent', () => {
const source = fs.readFileSync(
path.resolve(__dirname, '..', 'bootstrap-electron.ts'),
'utf8',
@@ -46,6 +46,8 @@ describe('database slimming IPC security wiring', () => {
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('confirmActiveTaskCleanup: async ({ backupEnabled }) =>');
+ expect(source).toContain('dbSlimmingIncludeActiveConfirmDescription');
expect(source).toContain('await dialog.showMessageBox');
});
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index fbd003d73a..9adc7e542d 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -7516,6 +7516,34 @@ const registerIpcHandlers = () => {
: await dialog.showOpenDialog(options);
return result.canceled ? null : result.filePaths[0] ?? null;
},
+ confirmActiveTaskCleanup: async ({ backupEnabled }) => {
+ const activeTaskWarning = t(
+ 'settings.about.storage.dbSlimmingIncludeActiveConfirmDescription',
+ );
+ const detail = backupEnabled
+ ? activeTaskWarning
+ : `${activeTaskWarning}\n\n${t(
+ 'settings.about.storage.dbSlimmingConfirmDescriptionWithoutBackup',
+ )}`;
+ const options: Electron.MessageBoxOptions = {
+ type: 'warning',
+ title: t('settings.about.storage.dbSlimmingIncludeActiveConfirmTitle'),
+ message: t('settings.about.storage.dbSlimmingIncludeActiveConfirmTitle'),
+ detail,
+ 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;
+ },
confirmWithoutBackup: async () => {
const options: Electron.MessageBoxOptions = {
type: 'warning',
diff --git a/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts b/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts
index 0fc0c8ad07..a0bff6a676 100644
--- a/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts
@@ -144,10 +144,13 @@ function createCleanupFixture(): void {
`);
for (const [id, status, updatedAt] of [
['deleted-old', 'deleted', 500],
+ ['deleted-recent', 'deleted', 1_500],
['deleted-new', 'deleted', 2_500],
['archived-boundary', 'archived', 1_000],
['archived-new', 'archived', 1_001],
['active-old', 'active', 100],
+ ['active-recent', 'active', 1_500],
+ ['active-updated-after-scan', 'active', 100],
] as const) {
insertSession.run(id, `title-${id}`, status, updatedAt);
db.prepare('INSERT INTO messages (id, session_id, content) VALUES (?, ?, ?)').run(
@@ -170,6 +173,7 @@ function createCleanupFixture(): void {
`content-${id}`,
);
}
+ db.prepare("UPDATE sessions SET cleared_at = 50 WHERE id = 'active-old'").run();
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(
@@ -208,6 +212,13 @@ function createCleanupFixture(): void {
'keep the external-file ownership ledger intact',
);
}
+ for (const sessionId of ['active-old', 'active-recent', 'active-updated-after-scan']) {
+ 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.pragma('journal_mode = WAL');
db.close();
}
@@ -268,6 +279,7 @@ describe('runDbSlimmingMaintenance', () => {
expect(outcome.originalDatabaseReady).toBe(true);
expect(outcome.result).toMatchObject({
status: 'completed',
+ activeTaskCount: 0,
deletedTaskCount: 1,
archivedTaskCount: 1,
messageCount: 2,
@@ -291,16 +303,22 @@ describe('runDbSlimmingMaintenance', () => {
db.prepare('SELECT id FROM messages ORDER BY id').all().map((row) => (row as { id: string }).id),
).toEqual([
'message-active-old',
+ 'message-active-recent',
+ 'message-active-updated-after-scan',
'message-archived-new',
'message-deleted-new',
+ 'message-deleted-recent',
]);
- expect(db.prepare('SELECT count(*) AS count FROM messages_fts').get()).toEqual({ count: 3 });
+ expect(db.prepare('SELECT count(*) AS count FROM messages_fts').get()).toEqual({ count: 6 });
expect(
db.prepare('SELECT message_id FROM messages_fts_rows ORDER BY message_id').all(),
).toEqual([
{ message_id: 'message-active-old' },
+ { message_id: 'message-active-recent' },
+ { message_id: 'message-active-updated-after-scan' },
{ message_id: 'message-archived-new' },
{ message_id: 'message-deleted-new' },
+ { message_id: 'message-deleted-recent' },
]);
expect(db.prepare('SELECT count(*) AS count FROM messages_fts_delete_audit').get()).toEqual({
count: 0,
@@ -312,13 +330,16 @@ describe('runDbSlimmingMaintenance', () => {
expect(
db.prepare('SELECT message_id FROM messages_fts_rows ORDER BY message_id').all(),
).toEqual([
+ { message_id: 'message-active-recent' },
+ { message_id: 'message-active-updated-after-scan' },
{ message_id: 'message-archived-new' },
{ message_id: 'message-deleted-new' },
+ { message_id: 'message-deleted-recent' },
]);
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 session_pr_refs').get()).toEqual({ count: 5 });
+ expect(db.prepare('SELECT count(*) AS count FROM session_goals').get()).toEqual({ count: 5 });
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 });
@@ -354,13 +375,160 @@ describe('runDbSlimmingMaintenance', () => {
});
expect(
db.prepare(`
- SELECT list_preview, list_preview_role, list_message_count
+ SELECT sdk_session_id, list_preview, list_preview_role, list_message_count,
+ cleared_at, codex_plan_json
FROM sessions WHERE id = 'active-old'
`).get(),
).toEqual({
+ sdk_session_id: 'native-id',
list_preview: 'stale preview',
list_preview_role: 'assistant',
list_message_count: 1,
+ cleared_at: 50,
+ codex_plan_json: '{}',
+ });
+ } finally {
+ db.close();
+ }
+ });
+
+ it('cleans only tasks older than the selected cutoff and keeps every recent status intact', async () => {
+ createCleanupFixture();
+ const cleanedTurnChangeSetDir = path.join(tmpDir, 'turn-change-sets', 'active-old');
+ const retainedTurnChangeSetDir = path.join(
+ tmpDir,
+ 'turn-change-sets',
+ 'active-updated-after-scan',
+ );
+ for (const directory of [cleanedTurnChangeSetDir, retainedTurnChangeSetDir]) {
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(path.join(directory, 'index.json'), '{}');
+ }
+ const dbBeforeScanExecution = createBetterSqliteDatabase(dbFilePath, { fileMustExist: true });
+ try {
+ dbBeforeScanExecution
+ .prepare("UPDATE sessions SET updated_at = 2500 WHERE id = 'active-updated-after-scan'")
+ .run();
+ } finally {
+ dbBeforeScanExecution.close();
+ }
+ const beforeBytes = estimateDbFilesBytes(dbFilePath);
+
+ const outcome = await runDbSlimmingMaintenance({
+ userDataDir: tmpDir,
+ dbFilePath,
+ request: request({
+ beforeBytes,
+ includeActiveTasks: true,
+ activeTaskCount: 2,
+ }),
+ now: () => 3_000,
+ log,
+ });
+
+ expect(outcome.result).toMatchObject({
+ status: 'completed',
+ activeTaskCount: 1,
+ deletedTaskCount: 1,
+ archivedTaskCount: 1,
+ messageCount: 3,
+ });
+ expect(fs.existsSync(cleanedTurnChangeSetDir)).toBe(false);
+ expect(fs.existsSync(retainedTurnChangeSetDir)).toBe(true);
+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();
+ 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-recent',
+ 'message-active-updated-after-scan',
+ 'message-archived-new',
+ 'message-deleted-new',
+ 'message-deleted-recent',
+ ]);
+ expect(db.prepare('SELECT count(*) AS count FROM messages_fts').get()).toEqual({ count: 5 });
+ expect(
+ db.prepare('SELECT message_id FROM messages_fts_rows ORDER BY message_id').all(),
+ ).toEqual([
+ { message_id: 'message-active-recent' },
+ { message_id: 'message-active-updated-after-scan' },
+ { message_id: 'message-archived-new' },
+ { message_id: 'message-deleted-new' },
+ { message_id: 'message-deleted-recent' },
+ ]);
+ expect(db.prepare('SELECT count(*) AS count FROM sessions').get()).toEqual({ count: 9 });
+ expect(
+ db.prepare('SELECT session_id FROM session_pr_refs ORDER BY session_id').all(),
+ ).toEqual([
+ { session_id: 'active-recent' },
+ { session_id: 'active-updated-after-scan' },
+ { session_id: 'archived-boundary' },
+ { session_id: 'deleted-old' },
+ ]);
+ expect(
+ db.prepare('SELECT session_id FROM session_goals ORDER BY session_id').all(),
+ ).toEqual([
+ { session_id: 'active-recent' },
+ { session_id: 'active-updated-after-scan' },
+ { session_id: 'archived-boundary' },
+ { session_id: 'deleted-old' },
+ ]);
+ expect(
+ db.prepare(`
+ SELECT status, updated_at, sdk_session_id, list_preview, list_preview_role,
+ list_message_count, cleared_at, codex_plan_json, summary
+ FROM sessions WHERE id = 'active-old'
+ `).get(),
+ ).toEqual({
+ status: 'active',
+ updated_at: 2_000,
+ sdk_session_id: null,
+ list_preview: null,
+ list_preview_role: null,
+ list_message_count: null,
+ cleared_at: 2_000,
+ codex_plan_json: null,
+ summary: null,
+ });
+ expect(
+ db.prepare(`
+ SELECT updated_at, sdk_session_id, list_preview, list_preview_role,
+ list_message_count, cleared_at, codex_plan_json, summary
+ FROM sessions WHERE id = 'active-updated-after-scan'
+ `).get(),
+ ).toEqual({
+ updated_at: 2_500,
+ sdk_session_id: 'native-id',
+ list_preview: 'stale preview',
+ list_preview_role: 'assistant',
+ list_message_count: 1,
+ cleared_at: null,
+ codex_plan_json: '{}',
+ summary: 'summary',
+ });
+ expect(
+ db.prepare(`
+ SELECT updated_at, sdk_session_id, list_preview, list_message_count, summary
+ FROM sessions WHERE id = 'active-recent'
+ `).get(),
+ ).toEqual({
+ updated_at: 1_500,
+ sdk_session_id: 'native-id',
+ list_preview: 'stale preview',
+ list_message_count: 1,
+ summary: 'summary',
+ });
+ expect(
+ db.prepare(`
+ SELECT status, updated_at, list_preview, list_message_count
+ FROM sessions WHERE id = 'deleted-recent'
+ `).get(),
+ ).toEqual({
+ status: 'deleted',
+ updated_at: 1_500,
+ list_preview: 'stale preview',
+ list_message_count: 1,
});
} finally {
db.close();
@@ -420,7 +588,7 @@ describe('runDbSlimmingMaintenance', () => {
fileMustExist: true,
});
try {
- expect(backup.prepare('SELECT count(*) AS count FROM messages').get()).toEqual({ count: 5 });
+ expect(backup.prepare('SELECT count(*) AS count FROM messages').get()).toEqual({ count: 8 });
} finally {
backup.close();
}
diff --git a/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts b/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts
index 480c5f86ea..14d8962777 100644
--- a/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts
+++ b/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts
@@ -6,6 +6,10 @@ import type {
DbSlimmingFailureReason,
DbSlimmingMaintenanceProgress,
} from '../../shared/localDbMaintenance';
+import {
+ isSafeTurnChangeSetSessionId,
+ turnChangeSetSessionDirectory,
+} from '../turn-change-set/storagePaths';
import { createBetterSqliteDatabase, restrictDbFilePermissions } from './betterSqliteFactory';
import {
adoptDbSlimmingBackup,
@@ -54,6 +58,8 @@ interface MaintenancePaths {
}
interface TargetCounts {
+ activeTaskCount: number;
+ activeTaskIds: string[];
deletedTaskCount: number;
archivedTaskCount: number;
messageCount: number;
@@ -183,7 +189,7 @@ export async function runDbSlimmingMaintenance(
writeDbSlimmingResult(options.userDataDir, result);
}
try {
- finalizeCommittedCleanup(options.userDataDir, paths);
+ finalizeCommittedCleanup(options.userDataDir, paths, request.activeTaskIds);
} catch (error) {
options.log.warn('database slimming committed cleanup will be retried', {
requestId: request.id,
@@ -219,7 +225,7 @@ export async function runDbSlimmingMaintenance(
try {
writeDbSlimmingRequest(options.userDataDir, request);
committed = true;
- finalizeCommittedCleanup(options.userDataDir, paths);
+ finalizeCommittedCleanup(options.userDataDir, paths, request.activeTaskIds);
} catch (error) {
options.log.warn('database slimming recovery cleanup will be retried', {
requestId: request.id,
@@ -305,7 +311,7 @@ export async function runDbSlimmingMaintenance(
try {
writeDbSlimmingRequest(options.userDataDir, request);
committed = true;
- finalizeCommittedCleanup(options.userDataDir, paths);
+ finalizeCommittedCleanup(options.userDataDir, paths, request.activeTaskIds);
} 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
@@ -318,6 +324,7 @@ export async function runDbSlimmingMaintenance(
}
options.log.info('database slimming completed', {
requestId: request.id,
+ activeTasks: request.activeTaskCount ?? 0,
deletedTasks: request.deletedTaskCount,
archivedTasks: request.archivedTaskCount,
messages: request.messageCount,
@@ -586,13 +593,20 @@ function compactWorkingCopy(
SELECT id, status
FROM sessions
WHERE ((status = 'deleted' AND updated_at <= ?)
- OR (status = 'archived' AND updated_at <= ?))
+ OR (status = 'archived' AND updated_at <= ?)
+ OR (? = 1 AND status = 'active' AND updated_at <= ?))
AND EXISTS (SELECT 1 FROM messages WHERE messages.session_id = sessions.id)`,
- ).run(request.scannedAt, request.archivedBeforeMs);
+ ).run(
+ request.archivedBeforeMs,
+ request.archivedBeforeMs,
+ request.includeActiveTasks === true ? 1 : 0,
+ request.archivedBeforeMs,
+ );
const counts = db
.prepare(
`SELECT
+ SUM(CASE WHEN t.status = 'active' THEN 1 ELSE 0 END) AS activeTaskCount,
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(*)
@@ -601,11 +615,22 @@ function compactWorkingCopy(
FROM temp.db_slimming_targets t`,
)
.get() as {
+ activeTaskCount: number | null;
deletedTaskCount: number | null;
archivedTaskCount: number | null;
messageCount: number;
};
const targetCounts: TargetCounts = {
+ activeTaskCount: counts.activeTaskCount ?? 0,
+ activeTaskIds: (
+ db
+ .prepare(
+ "SELECT id FROM temp.db_slimming_targets WHERE status = 'active' ORDER BY id",
+ )
+ .all() as Array<{ id: string }>
+ )
+ .map(({ id }) => id)
+ .filter(isSafeTurnChangeSetSessionId),
deletedTaskCount: counts.deletedTaskCount ?? 0,
archivedTaskCount: counts.archivedTaskCount ?? 0,
messageCount: counts.messageCount ?? 0,
@@ -685,6 +710,48 @@ function compactWorkingCopy(
WHERE id IN (SELECT id FROM temp.db_slimming_targets)`,
);
}
+ if (request.includeActiveTasks === true) {
+ if (tableExists(activeDb, 'session_goals')) {
+ activeDb.exec(
+ `DELETE FROM session_goals
+ WHERE session_id IN (
+ SELECT id FROM temp.db_slimming_targets WHERE status = 'active'
+ )`,
+ );
+ }
+ if (tableExists(activeDb, 'session_pr_refs')) {
+ activeDb.exec(
+ `DELETE FROM session_pr_refs
+ WHERE session_id IN (
+ SELECT id FROM temp.db_slimming_targets WHERE status = 'active'
+ )`,
+ );
+ }
+ const hasClearedAt = sessionColumns.has('cleared_at');
+ const hasUpdatedAt = sessionColumns.has('updated_at');
+ const activeResetAssignments = [
+ sessionColumns.has('sdk_session_id') ? 'sdk_session_id = NULL' : null,
+ sessionColumns.has('codex_plan_json') ? 'codex_plan_json = NULL' : null,
+ sessionColumns.has('summary') ? 'summary = NULL' : null,
+ hasClearedAt ? 'cleared_at = MAX(COALESCE(cleared_at, 0), ?)' : null,
+ hasUpdatedAt ? 'updated_at = MAX(COALESCE(updated_at, 0), ?)' : null,
+ ].filter((assignment): assignment is string => assignment !== null);
+ const activeResetBoundaryParameters = [
+ ...(hasClearedAt ? [Math.floor(request.scannedAt)] : []),
+ ...(hasUpdatedAt ? [Math.floor(request.scannedAt)] : []),
+ ];
+ if (activeResetAssignments.length > 0) {
+ activeDb
+ .prepare(
+ `UPDATE sessions
+ SET ${activeResetAssignments.join(', ')}
+ WHERE id IN (
+ SELECT id FROM temp.db_slimming_targets WHERE status = 'active'
+ )`,
+ )
+ .run(...activeResetBoundaryParameters);
+ }
+ }
if (messagesFtsDeleteTriggerSql) activeDb.exec(messagesFtsDeleteTriggerSql);
});
cleanup();
@@ -826,6 +893,7 @@ function completedResult(
status: 'completed',
finishedAt,
archiveAgeMonths: request.archiveAgeMonths,
+ activeTaskCount: request.activeTaskCount ?? 0,
deletedTaskCount: request.deletedTaskCount,
archivedTaskCount: request.archivedTaskCount,
messageCount: request.messageCount,
@@ -909,7 +977,17 @@ function tableExists(db: Database.Database, tableName: string): boolean {
);
}
-function finalizeCommittedCleanup(userDataDir: string, paths: MaintenancePaths): void {
+function finalizeCommittedCleanup(
+ userDataDir: string,
+ paths: MaintenancePaths,
+ activeTaskIds: string[] | undefined,
+): void {
+ for (const sessionId of activeTaskIds ?? []) {
+ fs.rmSync(turnChangeSetSessionDirectory(userDataDir, sessionId), {
+ recursive: true,
+ force: true,
+ });
+ }
if (!cleanupAfterCommit(paths)) {
throw new Error('database slimming committed artifacts could not be removed');
}
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/maintenance.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/maintenance.test.ts
index 3f6abe6e9a..22aa3945ad 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/maintenance.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/maintenance.test.ts
@@ -32,12 +32,14 @@ function createHarness() {
let dbClientOwnerId: string | null = owner.ownerId;
let canSchedule = true;
const queryOne = vi.fn(async () => ({
+ activeTaskCount: 0,
deletedTaskCount: 1,
archivedTaskCount: 2,
messageCount: 3,
estimatedMessageBytes: 4_096,
}));
const selectBackupDirectory = vi.fn(async () => path.join(tmpDir, 'backups'));
+ const confirmActiveTaskCleanup = vi.fn(async () => true);
const confirmWithoutBackup = vi.fn(async () => true);
const revealFile = vi.fn(async () => true);
const relaunch = vi.fn();
@@ -51,12 +53,14 @@ function createHarness() {
getUserDataDir: () => tmpDir,
canSchedule: () => canSchedule,
selectBackupDirectory,
+ confirmActiveTaskCleanup,
confirmWithoutBackup,
revealFile,
relaunch,
});
return {
handlers,
+ confirmActiveTaskCleanup,
confirmWithoutBackup,
queryOne,
revealFile,
@@ -90,6 +94,63 @@ describe('local database maintenance IPC', () => {
expect(queryOne).toHaveBeenCalledTimes(4);
});
+ it('defaults active-task cleanup off for legacy callers and rejects non-boolean values', async () => {
+ const { handlers, queryOne } = createHarness();
+
+ const scan = await handlers.scan({ archiveAgeMonths: 3 });
+
+ expect(scan).toMatchObject({ includeActiveTasks: false, activeTaskCount: 0 });
+ expect(queryOne).toHaveBeenLastCalledWith(expect.stringContaining("status = 'active'"), [
+ scan.archivedBeforeMs,
+ scan.archivedBeforeMs,
+ 0,
+ scan.archivedBeforeMs,
+ ]);
+
+ for (const includeActiveTasks of [null, 0, 'true', {}]) {
+ await expect(
+ handlers.scan({ archiveAgeMonths: 3, includeActiveTasks } as never),
+ ).rejects.toThrow('[INVALID_PARAMS]');
+ }
+ expect(queryOne).toHaveBeenCalledTimes(1);
+ });
+
+ it('applies the selected age cutoff to every task status and carries its scope into the marker', async () => {
+ const harness = createHarness();
+ harness.queryOne.mockResolvedValueOnce({
+ activeTaskCount: 4,
+ deletedTaskCount: 1,
+ archivedTaskCount: 2,
+ messageCount: 7,
+ estimatedMessageBytes: 8_192,
+ });
+
+ const scan = await harness.handlers.scan({
+ archiveAgeMonths: '7-days',
+ includeActiveTasks: true,
+ });
+
+ expect(scan).toMatchObject({ includeActiveTasks: true, activeTaskCount: 4 });
+ expect(harness.queryOne).toHaveBeenLastCalledWith(
+ expect.stringContaining("status = 'active'"),
+ [scan.archivedBeforeMs, scan.archivedBeforeMs, 1, scan.archivedBeforeMs],
+ );
+
+ await expect(
+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: true }),
+ ).resolves.toEqual({ scheduled: true });
+ expect(harness.confirmActiveTaskCleanup).toHaveBeenCalledExactlyOnceWith({
+ backupEnabled: true,
+ });
+ expect(readDbSlimmingRequest(tmpDir)).toMatchObject({
+ includeActiveTasks: true,
+ activeTaskCount: 4,
+ deletedTaskCount: 1,
+ archivedTaskCount: 2,
+ messageCount: 7,
+ });
+ });
+
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),
@@ -176,6 +237,43 @@ describe('local database maintenance IPC', () => {
expect(harness.relaunch).not.toHaveBeenCalled();
});
+ it('requires a native Main confirmation for active-task cleanup with a backup', async () => {
+ const harness = createHarness();
+ harness.confirmActiveTaskCleanup.mockResolvedValue(false);
+ const scan = await harness.handlers.scan({
+ archiveAgeMonths: '7-days',
+ includeActiveTasks: true,
+ });
+
+ await expect(
+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: true }),
+ ).resolves.toEqual({ scheduled: false });
+
+ expect(harness.confirmActiveTaskCleanup).toHaveBeenCalledExactlyOnceWith({
+ backupEnabled: true,
+ });
+ expect(harness.confirmWithoutBackup).not.toHaveBeenCalled();
+ expect(readDbSlimmingRequest(tmpDir)).toBeNull();
+ expect(harness.relaunch).not.toHaveBeenCalled();
+ });
+
+ it('includes the no-backup state in the active-task Main confirmation', async () => {
+ const harness = createHarness();
+ const scan = await harness.handlers.scan({
+ archiveAgeMonths: 1,
+ includeActiveTasks: true,
+ });
+
+ await expect(
+ harness.handlers.schedule({ scanId: scan.scanId, backupEnabled: false }),
+ ).resolves.toEqual({ scheduled: true });
+
+ expect(harness.confirmActiveTaskCleanup).toHaveBeenCalledExactlyOnceWith({
+ backupEnabled: false,
+ });
+ expect(harness.confirmWithoutBackup).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' });
@@ -185,6 +283,7 @@ describe('local database maintenance IPC', () => {
).resolves.toEqual({ scheduled: true });
expect(harness.confirmWithoutBackup).not.toHaveBeenCalled();
+ expect(harness.confirmActiveTaskCleanup).not.toHaveBeenCalled();
expect(readDbSlimmingRequest(tmpDir)).toMatchObject({
archiveAgeMonths: '7-days',
backupEnabled: true,
@@ -195,6 +294,7 @@ describe('local database maintenance IPC', () => {
it('does not restart or copy the database when the scan found nothing to clean', async () => {
const harness = createHarness();
harness.queryOne.mockResolvedValueOnce({
+ activeTaskCount: 0,
deletedTaskCount: 0,
archivedTaskCount: 0,
messageCount: 0,
@@ -207,6 +307,7 @@ describe('local database maintenance IPC', () => {
).resolves.toEqual({ scheduled: false });
expect(harness.confirmWithoutBackup).not.toHaveBeenCalled();
+ expect(harness.confirmActiveTaskCleanup).not.toHaveBeenCalled();
expect(harness.relaunch).not.toHaveBeenCalled();
expect(readDbSlimmingRequest(tmpDir)).toBeNull();
});
diff --git a/apps/desktop/src/main/localDb/ipc/maintenance.ts b/apps/desktop/src/main/localDb/ipc/maintenance.ts
index 055687be43..8e8c73b6fa 100644
--- a/apps/desktop/src/main/localDb/ipc/maintenance.ts
+++ b/apps/desktop/src/main/localDb/ipc/maintenance.ts
@@ -50,6 +50,7 @@ interface DirectoryGrant {
}
interface ScanAggregateRow {
+ activeTaskCount: number | null;
deletedTaskCount: number | null;
archivedTaskCount: number | null;
messageCount: number;
@@ -65,6 +66,7 @@ export interface LocalDbMaintenanceIpcDeps {
getUserDataDir(): string;
canSchedule(): boolean;
selectBackupDirectory(): Promise<string | null>;
+ confirmActiveTaskCleanup(input: { backupEnabled: boolean }): Promise<boolean>;
confirmWithoutBackup(): Promise<boolean>;
revealFile(filePath: string): Promise<boolean>;
relaunch(requestId: string): void;
@@ -114,6 +116,7 @@ export function createLocalDbMaintenanceIpcHandlers(deps: LocalDbMaintenanceIpcD
return {
async scan(input: DbSlimmingScanInput): Promise<DbSlimmingScanResult> {
const archiveAgeMonths = validateArchiveAge(input?.archiveAgeMonths);
+ const includeActiveTasks = validateIncludeActiveTasks(input?.includeActiveTasks);
const owner = captureReadyOwner();
const scannedAt = Date.now();
const archivedBeforeMs = archiveCutoffForAge(scannedAt, archiveAgeMonths);
@@ -122,10 +125,12 @@ export function createLocalDbMaintenanceIpcHandlers(deps: LocalDbMaintenanceIpcD
SELECT id, status
FROM sessions
WHERE ((status = 'deleted' AND updated_at <= ?)
- OR (status = 'archived' AND updated_at <= ?))
+ OR (status = 'archived' AND updated_at <= ?)
+ OR (? = 1 AND status = 'active' AND updated_at <= ?))
AND EXISTS (SELECT 1 FROM messages WHERE messages.session_id = sessions.id)
)
SELECT
+ (SELECT COUNT(*) FROM target_sessions WHERE status = 'active') AS activeTaskCount,
(SELECT COUNT(*) FROM target_sessions WHERE status = 'deleted') AS deletedTaskCount,
(SELECT COUNT(*) FROM target_sessions WHERE status = 'archived') AS archivedTaskCount,
(SELECT COUNT(*)
@@ -142,7 +147,7 @@ export function createLocalDbMaintenanceIpcHandlers(deps: LocalDbMaintenanceIpcD
), 0)
FROM messages message
JOIN target_sessions target ON target.id = message.session_id) AS estimatedMessageBytes`,
- [scannedAt, archivedBeforeMs],
+ [archivedBeforeMs, archivedBeforeMs, includeActiveTasks ? 1 : 0, archivedBeforeMs],
);
assertOwnerCurrent(owner);
const dbFilePath = deps.getCurrentDbPath();
@@ -154,8 +159,10 @@ export function createLocalDbMaintenanceIpcHandlers(deps: LocalDbMaintenanceIpcD
const result: DbSlimmingScanResult = {
scanId,
archiveAgeMonths,
+ includeActiveTasks,
scannedAt,
archivedBeforeMs,
+ activeTaskCount: row?.activeTaskCount ?? 0,
deletedTaskCount: row?.deletedTaskCount ?? 0,
archivedTaskCount: row?.archivedTaskCount ?? 0,
messageCount: row?.messageCount ?? 0,
@@ -238,7 +245,17 @@ export function createLocalDbMaintenanceIpcHandlers(deps: LocalDbMaintenanceIpcD
backupDirectory = directoryGrant.directory;
}
- if (!input.backupEnabled && !(await deps.confirmWithoutBackup())) {
+ if (
+ scan.includeActiveTasks &&
+ !(await deps.confirmActiveTaskCleanup({ backupEnabled: input.backupEnabled }))
+ ) {
+ return { scheduled: false };
+ }
+ if (
+ !scan.includeActiveTasks &&
+ !input.backupEnabled &&
+ !(await deps.confirmWithoutBackup())
+ ) {
return { scheduled: false };
}
@@ -292,6 +309,8 @@ export function createLocalDbMaintenanceIpcHandlers(deps: LocalDbMaintenanceIpcD
scannedAt: scan.scannedAt,
archivedBeforeMs: scan.archivedBeforeMs,
archiveAgeMonths: scan.archiveAgeMonths,
+ includeActiveTasks: scan.includeActiveTasks,
+ activeTaskCount: scan.activeTaskCount,
deletedTaskCount: scan.deletedTaskCount,
archivedTaskCount: scan.archivedTaskCount,
messageCount: scan.messageCount,
@@ -336,6 +355,15 @@ function validateArchiveAge(value: unknown): DbSlimmingArchiveAge {
return value as DbSlimmingArchiveAge;
}
+function validateIncludeActiveTasks(value: unknown): boolean {
+ // Missing means the legacy, safest scope for older callers.
+ if (value === undefined) return false;
+ if (typeof value !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'invalid active-task database maintenance option');
+ }
+ return value;
+}
+
/** Uses an exact seven-day duration or calendar months with month-end clamping. */
export function archiveCutoffForAge(
scannedAt: number,
diff --git a/apps/desktop/src/main/localDb/maintenanceStore.ts b/apps/desktop/src/main/localDb/maintenanceStore.ts
index 4d9f01ca0a..2e7b9a267e 100644
--- a/apps/desktop/src/main/localDb/maintenanceStore.ts
+++ b/apps/desktop/src/main/localDb/maintenanceStore.ts
@@ -8,6 +8,7 @@ import {
DbSlimmingFailureReason,
DbSlimmingResult,
} from '../../shared/localDbMaintenance';
+import { isSafeTurnChangeSetSessionId } from '../turn-change-set/storagePaths';
import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';
const REQUEST_FILE_NAME = 'db-slimming-request.json';
@@ -31,6 +32,11 @@ export interface DbSlimmingRequestRecord {
scannedAt: number;
archivedBeforeMs: number;
archiveAgeMonths: DbSlimmingArchiveAge;
+ /** Optional so an update can still finish a cleanup scheduled by an older build. */
+ includeActiveTasks?: boolean;
+ activeTaskCount?: number;
+ /** Exact committed active-task targets whose external history sidecars must also be removed. */
+ activeTaskIds?: string[];
deletedTaskCount: number;
archivedTaskCount: number;
messageCount: number;
@@ -239,6 +245,11 @@ function isDbSlimmingRequestRecord(value: unknown): value is DbSlimmingRequestRe
!isFiniteNumber(value.scannedAt) ||
!isFiniteNumber(value.archivedBeforeMs) ||
!isArchiveAge(value.archiveAgeMonths) ||
+ (value.includeActiveTasks !== undefined && typeof value.includeActiveTasks !== 'boolean') ||
+ (value.activeTaskCount !== undefined && !Number.isInteger(value.activeTaskCount)) ||
+ (value.activeTaskIds !== undefined &&
+ (!Array.isArray(value.activeTaskIds) ||
+ value.activeTaskIds.some((sessionId) => !isSafeTurnChangeSetSessionId(sessionId)))) ||
!Number.isInteger(value.deletedTaskCount) ||
!Number.isInteger(value.archivedTaskCount) ||
!Number.isInteger(value.messageCount) ||
@@ -287,6 +298,7 @@ function isDbSlimmingResultRecord(value: unknown): value is DbSlimmingResultReco
}
if (value.status !== 'completed') return false;
return (
+ (value.activeTaskCount === undefined || Number.isInteger(value.activeTaskCount)) &&
Number.isInteger(value.deletedTaskCount) &&
Number.isInteger(value.archivedTaskCount) &&
Number.isInteger(value.messageCount) &&
diff --git a/apps/desktop/src/main/turn-change-set/storagePaths.ts b/apps/desktop/src/main/turn-change-set/storagePaths.ts
new file mode 100644
index 0000000000..f6ae4351ad
--- /dev/null
+++ b/apps/desktop/src/main/turn-change-set/storagePaths.ts
@@ -0,0 +1,26 @@
+import path from 'node:path';
+
+export function isSafeTurnChangeSetSessionId(value: unknown): value is string {
+ return (
+ typeof value === 'string' &&
+ value.length > 0 &&
+ value.length <= 256 &&
+ value !== '.' &&
+ !value.includes('/') &&
+ !value.includes('\\') &&
+ !value.includes('..') &&
+ !value.includes('\0') &&
+ !value.includes(':')
+ );
+}
+
+export function turnChangeSetStorageRoot(userDataDir: string): string {
+ return path.join(userDataDir, 'turn-change-sets');
+}
+
+export function turnChangeSetSessionDirectory(userDataDir: string, sessionId: string): string {
+ if (!isSafeTurnChangeSetSessionId(sessionId)) {
+ throw new Error('Invalid session id');
+ }
+ return path.join(turnChangeSetStorageRoot(userDataDir), sessionId);
+}
diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.ts
index 2cd492d568..f4ef9ab425 100644
--- a/apps/desktop/src/main/turn-change-set/store.ts
+++ b/apps/desktop/src/main/turn-change-set/store.ts
@@ -30,6 +30,10 @@ import { detectSensitivePath } from '../security/sensitivePath.js';
import * as broadcastTap from '../device-link/broadcast-tap.js';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
import { atomicWriteFileSync } from '../utils/atomicWriteFile.js';
+import {
+ turnChangeSetSessionDirectory,
+ turnChangeSetStorageRoot,
+} from './storagePaths';
const log = createLogger('turn-change-set');
const MAX_LIST_ROWS = 100;
@@ -162,12 +166,11 @@ function assertSafeSegment(value: string, label: string): void {
}
function storageRoot(): string {
- return path.join(app.getPath('userData'), 'turn-change-sets');
+ return turnChangeSetStorageRoot(app.getPath('userData'));
}
function sessionDir(sessionId: string): string {
- assertSafeSegment(sessionId, 'session id');
- return path.join(storageRoot(), sessionId);
+ return turnChangeSetSessionDirectory(app.getPath('userData'), sessionId);
}
function detailPath(sessionId: string, id: string): string {
diff --git a/apps/desktop/src/renderer/__tests__/storageCleanupCopy.test.ts b/apps/desktop/src/renderer/__tests__/storageCleanupCopy.test.ts
index 321c013c52..57af699405 100644
--- a/apps/desktop/src/renderer/__tests__/storageCleanupCopy.test.ts
+++ b/apps/desktop/src/renderer/__tests__/storageCleanupCopy.test.ts
@@ -5,7 +5,7 @@ import ko from '../i18n/locales/ko/common.json';
import zhCN from '../i18n/locales/zh-CN/common.json';
import zhTW from '../i18n/locales/zh-TW/common.json';
-describe('fixed cache directory cleanup copy', () => {
+describe('storage cleanup copy', () => {
it.each([
['en', en, 'Clear image cache', 'Clear attachment cache'],
['ja', ja, '画像キャッシュを削除', '添付ファイルキャッシュを削除'],
@@ -23,4 +23,20 @@ describe('fixed cache directory cleanup copy', () => {
expect(storage.chatAttachmentsClearConfirmButton).toBe(attachmentAction);
},
);
+
+ it.each([
+ ['en', en, ['database backup', 'review or undo', 'cannot be restored']],
+ ['ja', ja, ['データベースのバックアップ', 'レビューや元に戻す', '復元できません']],
+ ['ko', ko, ['데이터베이스 백업', '검토하거나 실행 취소', '복구할 수 없습니다']],
+ ['zh-CN', zhCN, ['数据库备份', '审查或撤销', '无法恢复']],
+ ['zh-TW', zhTW, ['資料庫備份', '審查或撤銷', '無法復原']],
+ ] as const)(
+ '%s states that file-change review and undo records are excluded from the database backup',
+ (_locale, messages, expectedFragments) => {
+ const description =
+ messages.settings.about.storage.dbSlimmingIncludeActiveConfirmDescription;
+
+ for (const fragment of expectedFragments) expect(description).toContain(fragment);
+ },
+ );
});
diff --git a/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx b/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx
index 9e135678e3..74afb1eea5 100644
--- a/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx
+++ b/apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx
@@ -31,6 +31,7 @@ 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 { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import {
DB_SLIMMING_ARCHIVE_AGE_OPTIONS,
DB_SLIMMING_DEFAULT_ARCHIVE_AGE,
@@ -409,9 +410,11 @@ type DbSlimmingPhase =
function DatabaseSlimmingSection() {
const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
const [archiveAge, setArchiveAge] = useState<DbSlimmingArchiveAge>(
DB_SLIMMING_DEFAULT_ARCHIVE_AGE,
);
+ const [includeActiveTasks, setIncludeActiveTasks] = useState(false);
const [backupEnabled, setBackupEnabled] = useState(true);
const [backupDirectory, setBackupDirectory] =
useState<DbSlimmingBackupDirectorySelection>({ selected: false });
@@ -420,6 +423,7 @@ function DatabaseSlimmingSection() {
const [reportOpen, setReportOpen] = useState(false);
const [executionLocked, setExecutionLocked] = useState(false);
const busyRef = useRef(false);
+ const activeTasksConfirmationPendingRef = useRef(false);
const interactionLockReleaseRef = useRef<(() => void) | null>(null);
const acquireInteractionLock = () => {
@@ -466,6 +470,31 @@ function DatabaseSlimmingSection() {
invalidateScan();
};
+ const handleIncludeActiveTasksChange = async (checked: boolean) => {
+ if (!checked) {
+ setIncludeActiveTasks(false);
+ invalidateScan();
+ return;
+ }
+ if (busyRef.current || scanLoading || activeTasksConfirmationPendingRef.current) return;
+ activeTasksConfirmationPendingRef.current = true;
+ let accepted = false;
+ try {
+ accepted = await confirm({
+ title: t('settings.about.storage.dbSlimmingIncludeActiveConfirmTitle'),
+ description: t('settings.about.storage.dbSlimmingIncludeActiveConfirmDescription'),
+ confirmText: t('settings.about.storage.dbSlimmingIncludeActiveConfirmButton'),
+ cancelText: t('settings.about.storage.dbSlimmingIncludeActiveCancelButton'),
+ autoFocusConfirm: true,
+ });
+ } finally {
+ activeTasksConfirmationPendingRef.current = false;
+ }
+ if (!accepted) return;
+ setIncludeActiveTasks(true);
+ invalidateScan();
+ };
+
const handleChooseBackupDirectory = async () => {
if (busyRef.current) return;
busyRef.current = true;
@@ -489,6 +518,7 @@ function DatabaseSlimmingSection() {
try {
const scan = await window.electronAPI.localDb.maintenance.scan({
archiveAgeMonths: archiveAge,
+ includeActiveTasks,
});
setPhase({ kind: 'scanned', scan });
setReportOpen(true);
@@ -654,6 +684,25 @@ function DatabaseSlimmingSection() {
</Select.Root>
</div>
+ <label
+ htmlFor="db-slimming-include-active"
+ 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.dbSlimmingIncludeActiveLabel')}
+ </span>
+ <span className="text-11 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">
+ {t('settings.about.storage.dbSlimmingIncludeActiveDescription')}
+ </span>
+ </label>
+ <Switch
+ id="db-slimming-include-active"
+ checked={includeActiveTasks}
+ disabled={scanLoading}
+ onCheckedChange={(checked) => void handleIncludeActiveTasksChange(checked)}
+ aria-label={t('settings.about.storage.dbSlimmingIncludeActiveLabel')}
+ />
+
<label
htmlFor="db-slimming-backup-enabled"
className="flex min-w-0 cursor-pointer flex-col gap-0.5"
@@ -698,7 +747,10 @@ function DatabaseSlimmingSection() {
{t('settings.about.storage.dbSlimmingResultCompleted', {
size: formatBytes(phase.result.reclaimedBytes),
messages: phase.result.messageCount,
- tasks: phase.result.deletedTaskCount + phase.result.archivedTaskCount,
+ tasks:
+ (phase.result.activeTaskCount ?? 0) +
+ phase.result.deletedTaskCount +
+ phase.result.archivedTaskCount,
})}
</p>
{phase.result.backupCreated && (
@@ -821,10 +873,16 @@ function DatabaseCleanupDialog({
>
<ReportLine
visible
- text={t('settings.about.storage.dbSlimmingReportTasks', {
- deleted: scanned.deletedTaskCount,
- archived: scanned.archivedTaskCount,
- })}
+ text={t(
+ scanned.includeActiveTasks
+ ? 'settings.about.storage.dbSlimmingReportTasksWithActive'
+ : 'settings.about.storage.dbSlimmingReportTasks',
+ {
+ active: scanned.activeTaskCount,
+ deleted: scanned.deletedTaskCount,
+ archived: scanned.archivedTaskCount,
+ },
+ )}
/>
<ReportLine
visible
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx
index 5ae7de268d..7cd448bd05 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,14 @@
// @vitest-environment jsdom
-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactElement } from 'react';
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render as testingLibraryRender,
+ screen,
+ waitFor,
+} from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { toast } = vi.hoisted(() => ({
@@ -19,6 +27,15 @@ vi.mock('@/lib/toast', () => ({ toast }));
vi.mock('@/lib/composerDraftStore', () => ({ getAllDraftAttachmentUrls: () => [] }));
import { StorageManagementCard } from '../StorageManagementCard';
+import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
+
+function render(ui: ReactElement) {
+ return testingLibraryRender(
+ <ConfirmDialogProvider>
+ {ui}
+ </ConfirmDialogProvider>,
+ );
+}
function storageApi() {
return {
@@ -42,11 +59,16 @@ function storageApi() {
function maintenanceApi() {
return {
getLastResult: vi.fn(async () => null),
- scan: vi.fn(async (input: { archiveAgeMonths: '7-days' | 1 | 3 | 6 }) => ({
+ scan: vi.fn(async (input: {
+ archiveAgeMonths: '7-days' | 1 | 3 | 6;
+ includeActiveTasks?: boolean;
+ }) => ({
scanId: 'scan-1',
archiveAgeMonths: input.archiveAgeMonths,
+ includeActiveTasks: input.includeActiveTasks === true,
scannedAt: 1_000,
archivedBeforeMs: 500,
+ activeTaskCount: input.includeActiveTasks ? 4 : 0,
deletedTaskCount: 1,
archivedTaskCount: 2,
messageCount: 3,
@@ -247,9 +269,17 @@ describe('StorageManagementCard database cleanup', () => {
'settings.about.storage.dbSlimmingArchiveAgeOption6',
]);
fireEvent.click(options[0]!);
- expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');
+ expect(
+ screen
+ .getByRole('switch', { name: 'settings.about.storage.dbSlimmingBackupLabel' })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
fireEvent.click(screen.getByText('settings.about.storage.dbSlimmingBackupLabel'));
- expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false');
+ expect(
+ screen
+ .getByRole('switch', { name: 'settings.about.storage.dbSlimmingBackupLabel' })
+ .getAttribute('aria-checked'),
+ ).toBe('false');
fireEvent.click(screen.getByText('settings.about.storage.dbSlimmingBackupLabel'));
const scanButton = screen.getByRole('button', {
name: 'settings.about.storage.dbSlimmingScanButton',
@@ -259,6 +289,7 @@ describe('StorageManagementCard database cleanup', () => {
await waitFor(() => {
expect(window.electronAPI.localDb.maintenance.scan).toHaveBeenCalledWith({
archiveAgeMonths: '7-days',
+ includeActiveTasks: false,
});
});
await waitFor(() => expect(scanButton.getAttribute('aria-busy')).toBeNull());
@@ -269,6 +300,69 @@ describe('StorageManagementCard database cleanup', () => {
).toBeTruthy();
});
+ it('keeps active-task cleanup off until the warning is confirmed', async () => {
+ render(<StorageManagementCard />);
+
+ const activeSwitch = screen.getByRole('switch', {
+ name: 'settings.about.storage.dbSlimmingIncludeActiveLabel',
+ });
+ expect(activeSwitch.getAttribute('aria-checked')).toBe('false');
+
+ fireEvent.click(activeSwitch);
+ const warning = await screen.findByRole('alertdialog', {
+ name: 'settings.about.storage.dbSlimmingIncludeActiveConfirmTitle',
+ });
+ expect(activeSwitch.getAttribute('aria-checked')).toBe('false');
+ const confirmButton = screen.getByRole('button', {
+ name: 'settings.about.storage.dbSlimmingIncludeActiveConfirmButton',
+ });
+ await waitFor(() => expect(document.activeElement).toBe(confirmButton));
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'settings.about.storage.dbSlimmingIncludeActiveCancelButton',
+ }),
+ );
+ await waitFor(() => expect(warning.getAttribute('data-state')).toBe('closed'));
+ expect(activeSwitch.getAttribute('aria-checked')).toBe('false');
+
+ fireEvent.click(activeSwitch);
+ fireEvent.click(
+ await screen.findByRole('button', {
+ name: 'settings.about.storage.dbSlimmingIncludeActiveConfirmButton',
+ }),
+ );
+ await waitFor(() => expect(activeSwitch.getAttribute('aria-checked')).toBe('true'));
+
+ fireEvent.click(activeSwitch);
+ expect(activeSwitch.getAttribute('aria-checked')).toBe('false');
+ expect(
+ screen.queryByRole('alertdialog', {
+ name: 'settings.about.storage.dbSlimmingIncludeActiveConfirmTitle',
+ }),
+ ).toBeNull();
+
+ fireEvent.click(activeSwitch);
+ fireEvent.click(
+ await screen.findByRole('button', {
+ name: 'settings.about.storage.dbSlimmingIncludeActiveConfirmButton',
+ }),
+ );
+ await waitFor(() => expect(activeSwitch.getAttribute('aria-checked')).toBe('true'));
+ fireEvent.click(
+ screen.getByRole('button', { name: 'settings.about.storage.dbSlimmingScanButton' }),
+ );
+
+ await waitFor(() => {
+ expect(window.electronAPI.localDb.maintenance.scan).toHaveBeenCalledWith({
+ archiveAgeMonths: '7-days',
+ includeActiveTasks: true,
+ });
+ });
+ expect(
+ await screen.findByText('settings.about.storage.dbSlimmingReportTasksWithActive'),
+ ).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(
@@ -299,8 +393,10 @@ describe('StorageManagementCard database cleanup', () => {
resolveScan({
scanId: 'scan-busy',
archiveAgeMonths: '7-days',
+ includeActiveTasks: false,
scannedAt: 1_000,
archivedBeforeMs: 500,
+ activeTaskCount: 0,
deletedTaskCount: 1,
archivedTaskCount: 2,
messageCount: 3,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 2974825fa3..ab485b4815 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -853,16 +853,22 @@
"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.",
+ "dbSlimmingDescription": "Scan history in soft-deleted and archived tasks not updated for the selected period, with an option to include active 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",
+ "dbSlimmingArchiveAgeLabel": "Clean tasks not updated for more than",
"dbSlimmingArchiveAgeOption7Days": "7 days",
"dbSlimmingArchiveAgeOption1": "1 month",
"dbSlimmingArchiveAgeOption3": "3 months",
"dbSlimmingArchiveAgeOption6": "6 months",
+ "dbSlimmingIncludeActiveLabel": "Clean active task history",
+ "dbSlimmingIncludeActiveDescription": "Also clean history from active tasks older than the selected period",
+ "dbSlimmingIncludeActiveConfirmTitle": "Include active tasks in database cleanup?",
+ "dbSlimmingIncludeActiveConfirmDescription": "An active task may still be running even when it is older than the selected period. Cleanup does not wait for it to stop, and messages it adds after the scan may also be removed. When enabled, active, archived, and soft-deleted tasks not updated for the selected period will be cleaned. History will be removed from eligible active tasks and their Agent context will be reset; task entries remain. A database backup can restore task and message data; without one, that data cannot be restored either. Records used to review or undo file changes from those messages are not included in the database backup and cannot be restored.",
+ "dbSlimmingIncludeActiveConfirmButton": "Include active tasks",
+ "dbSlimmingIncludeActiveCancelButton": "Keep active tasks",
"dbSlimmingBackupLabel": "Back up database before cleanup",
"dbSlimmingBackupDefaultLocation": "Database folder (keeps only the latest cleanup backup)",
"dbSlimmingUseDefaultDirectoryButton": "Use default folder",
@@ -873,6 +879,7 @@
"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",
+ "dbSlimmingReportTasksWithActive": "Will clean {{active}} active tasks, {{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",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3295e8a9f4..ad6afeb786 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -853,16 +853,22 @@
"chatAttachmentsClearFailed": "メッセージ添付ファイルのキャッシュをクリーンアップできませんでした。もう一度お試しください。",
"dbSlimmingBackupDirectoryDialogTitle": "データベースのクリーンアップ用バックアップ先を選択",
"dbSlimmingLabel": "データベースのクリーンアップ",
- "dbSlimmingDescription": "論理削除されたタスクと長期間アーカイブされたタスクのメッセージ履歴をスキャンします。確認後に Cindy を再起動し、データベースを開く前に履歴を削除して圧縮します。ディスク上の添付ファイルや生成メディアは削除しません。",
+ "dbSlimmingDescription": "選択した期間を超えて更新されていない論理削除済みおよびアーカイブ済みタスクの履歴をスキャンし、必要に応じてアクティブなタスクも対象に含めます。確認後に Cindy を再起動し、データベースを開く前に履歴を削除して圧縮します。ディスク上の添付ファイルや生成メディアは削除しません。",
"dbSlimmingScanButton": "データベースをスキャン",
"dbSlimmingScanLoading": "データベースをスキャンしています…",
"dbSlimmingScanResultTitle": "データベースのスキャン結果",
"dbSlimmingExecutionLoading": "データベースのクリーンアップを準備しています。Cindy はまもなく再起動します…",
- "dbSlimmingArchiveAgeLabel": "次の期間を超えてアーカイブされているタスクを整理",
+ "dbSlimmingArchiveAgeLabel": "最終更新から次の期間を超えたタスクを整理",
"dbSlimmingArchiveAgeOption7Days": "7 日",
"dbSlimmingArchiveAgeOption1": "1 か月",
"dbSlimmingArchiveAgeOption3": "3 か月",
"dbSlimmingArchiveAgeOption6": "6 か月",
+ "dbSlimmingIncludeActiveLabel": "アクティブなタスクの履歴も削除",
+ "dbSlimmingIncludeActiveDescription": "選択した期間を超えたアクティブなタスクの履歴もクリーンアップします",
+ "dbSlimmingIncludeActiveConfirmTitle": "アクティブなタスクもデータベースのクリーンアップ対象にしますか?",
+ "dbSlimmingIncludeActiveConfirmDescription": "選択した期間を超えたアクティブなタスクでも、まだ実行中の可能性があります。クリーンアップはタスクの停止を待たず、スキャン後に追加されたメッセージも削除される場合があります。有効にすると、選択した期間を超えて更新されていないアクティブ、アーカイブ済み、論理削除済みのタスクがクリーンアップされます。対象のアクティブなタスクの履歴と Agent コンテキストは削除されますが、タスク自体は残ります。データベースのバックアップではタスクとメッセージのデータを復元できます。バックアップを作成しない場合、それらのデータも復元できません。それらのメッセージによるファイル変更のレビューや元に戻す操作に使う記録はデータベースのバックアップに含まれず、復元できません。",
+ "dbSlimmingIncludeActiveConfirmButton": "アクティブなタスクを含める",
+ "dbSlimmingIncludeActiveCancelButton": "アクティブなタスクを残す",
"dbSlimmingBackupLabel": "クリーンアップ前にデータベースをバックアップ",
"dbSlimmingBackupDefaultLocation": "データベースのフォルダ(最新のクリーンアップ用バックアップのみ保持)",
"dbSlimmingUseDefaultDirectoryButton": "既定のフォルダを使用",
@@ -873,6 +879,7 @@
"dbSlimmingBackupMissing": "最新のクリーンアップ用バックアップが見つかりません。",
"dbSlimmingBackupOpenFailed": "クリーンアップ用バックアップの場所を開けませんでした。もう一度お試しください。",
"dbSlimmingReportTasks": "論理削除タスク {{deleted}} 件、アーカイブ済みタスク {{archived}} 件を削除します",
+ "dbSlimmingReportTasksWithActive": "アクティブなタスク {{active}} 件、論理削除済みタスク {{deleted}} 件、アーカイブ済みタスク {{archived}} 件をクリーンアップします",
"dbSlimmingReportMessages": "削除予定のメッセージ内容:{{count}} 件(約 {{size}})",
"dbSlimmingReportSpace": "データベース {{database}}、必要な一時領域は最低 {{temporary}}、空き容量 {{free}}",
"dbSlimmingSpaceUnknown": "不明",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index dc5bc44dbf..f2633c0586 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -853,16 +853,22 @@
"chatAttachmentsClearFailed": "메시지 첨부 파일 캐시를 정리할 수 없습니다. 다시 시도해 주세요.",
"dbSlimmingBackupDirectoryDialogTitle": "데이터베이스 정리 백업 폴더 선택",
"dbSlimmingLabel": "데이터베이스 정리",
- "dbSlimmingDescription": "소프트 삭제된 작업과 오래 보관된 작업의 메시지 기록을 검사합니다. 확인 후 Cindy를 다시 시작하고 데이터베이스를 열기 전에 기록을 정리하고 압축합니다. 디스크의 첨부 파일과 생성 미디어는 삭제하지 않습니다.",
+ "dbSlimmingDescription": "선택한 기간보다 오래 업데이트되지 않은 소프트 삭제 및 보관 작업의 기록을 검사하며, 활성 작업도 선택적으로 포함할 수 있습니다. 확인 후 Cindy를 다시 시작하고 데이터베이스를 열기 전에 기록을 정리하고 압축합니다. 디스크의 첨부 파일과 생성 미디어는 삭제하지 않습니다.",
"dbSlimmingScanButton": "데이터베이스 검사",
"dbSlimmingScanLoading": "데이터베이스를 검사하는 중…",
"dbSlimmingScanResultTitle": "데이터베이스 검사 결과",
"dbSlimmingExecutionLoading": "데이터베이스 정리를 준비하고 있습니다. Cindy가 곧 다시 시작됩니다…",
- "dbSlimmingArchiveAgeLabel": "보관 후 다음 기간이 지난 작업 정리",
+ "dbSlimmingArchiveAgeLabel": "다음 기간 동안 업데이트되지 않은 작업 정리",
"dbSlimmingArchiveAgeOption7Days": "7일",
"dbSlimmingArchiveAgeOption1": "1개월",
"dbSlimmingArchiveAgeOption3": "3개월",
"dbSlimmingArchiveAgeOption6": "6개월",
+ "dbSlimmingIncludeActiveLabel": "활성 작업 기록도 정리",
+ "dbSlimmingIncludeActiveDescription": "선택한 기간보다 오래된 활성 작업의 기록도 정리합니다",
+ "dbSlimmingIncludeActiveConfirmTitle": "활성 작업도 데이터베이스 정리 대상에 포함할까요?",
+ "dbSlimmingIncludeActiveConfirmDescription": "선택한 기간보다 오래된 활성 작업도 아직 실행 중일 수 있습니다. 정리는 작업이 중지될 때까지 기다리지 않으며 스캔 후 추가된 메시지도 삭제될 수 있습니다. 사용하면 선택한 기간보다 오래 업데이트되지 않은 활성, 보관 및 소프트 삭제 작업이 정리됩니다. 대상 활성 작업의 기록과 Agent 컨텍스트는 삭제되지만 작업 항목은 유지됩니다. 데이터베이스 백업으로 작업과 메시지 데이터는 복구할 수 있습니다. 백업을 만들지 않으면 해당 데이터도 복구할 수 없습니다. 해당 메시지의 파일 변경 사항을 검토하거나 실행 취소하는 데 사용되는 기록은 데이터베이스 백업에 포함되지 않으며 복구할 수 없습니다.",
+ "dbSlimmingIncludeActiveConfirmButton": "활성 작업 포함",
+ "dbSlimmingIncludeActiveCancelButton": "활성 작업 유지",
"dbSlimmingBackupLabel": "정리 전 데이터베이스 백업",
"dbSlimmingBackupDefaultLocation": "데이터베이스 폴더(최근 정리 백업만 유지)",
"dbSlimmingUseDefaultDirectoryButton": "기본 폴더 사용",
@@ -873,6 +879,7 @@
"dbSlimmingBackupMissing": "최근 정리 백업을 찾을 수 없습니다.",
"dbSlimmingBackupOpenFailed": "정리 백업 위치를 열 수 없습니다. 다시 시도해 주세요.",
"dbSlimmingReportTasks": "소프트 삭제 작업 {{deleted}}개와 보관된 작업 {{archived}}개를 정리합니다",
+ "dbSlimmingReportTasksWithActive": "활성 작업 {{active}}개, 소프트 삭제된 작업 {{deleted}}개, 보관된 작업 {{archived}}개를 정리합니다",
"dbSlimmingReportMessages": "정리할 메시지 내용: {{count}}개(약 {{size}})",
"dbSlimmingReportSpace": "데이터베이스 {{database}}, 필요한 임시 공간 최소 {{temporary}}, 사용 가능 {{free}}",
"dbSlimmingSpaceUnknown": "알 수 없음",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 6cd44d5355..1f736dab6e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -853,16 +853,22 @@
"chatAttachmentsClearFailed": "无法清理消息附件缓存,请重试",
"dbSlimmingBackupDirectoryDialogTitle": "选择数据库清理备份目录",
"dbSlimmingLabel": "数据库清理",
- "dbSlimmingDescription": "扫描软删除任务和长时间归档任务中的历史消息,确认后重启 Cindy,在数据库打开前清理并压缩。不会删除磁盘附件或生成媒体。",
+ "dbSlimmingDescription": "扫描超过所选时间未更新的软删除和已归档任务历史,可选择同时纳入活跃任务。确认后重启 Cindy,在数据库打开前清理并压缩。不会删除磁盘附件或生成媒体。",
"dbSlimmingScanButton": "扫描数据库",
"dbSlimmingScanLoading": "正在扫描数据库,请稍候…",
"dbSlimmingScanResultTitle": "数据库扫描结果",
"dbSlimmingExecutionLoading": "正在准备数据库清理,Cindy 即将重启…",
- "dbSlimmingArchiveAgeLabel": "清理归档时间超过",
+ "dbSlimmingArchiveAgeLabel": "清理未更新时间超过",
"dbSlimmingArchiveAgeOption7Days": "7 天",
"dbSlimmingArchiveAgeOption1": "1 个月",
"dbSlimmingArchiveAgeOption3": "3 个月",
"dbSlimmingArchiveAgeOption6": "6 个月",
+ "dbSlimmingIncludeActiveLabel": "清理活跃任务历史",
+ "dbSlimmingIncludeActiveDescription": "同时清理超过所选时间的活跃任务历史",
+ "dbSlimmingIncludeActiveConfirmTitle": "将活跃任务纳入数据库清理?",
+ "dbSlimmingIncludeActiveConfirmDescription": "活跃任务即使超过所选时间,也可能仍在运行。清理不会等待任务停止,任务在扫描后继续产生的消息也可能被清除。启用后,超过所选时间的活跃、已归档和软删除任务都会被清理。符合范围的活跃任务历史消息和 Agent 上下文将被清除;任务条目仍会保留。数据库备份可以恢复任务和消息数据;不创建备份时,这些数据也无法恢复。用于审查或撤销这些消息所产生文件改动的记录不包含在数据库备份中,无法恢复。",
+ "dbSlimmingIncludeActiveConfirmButton": "纳入活跃任务",
+ "dbSlimmingIncludeActiveCancelButton": "保留活跃任务",
"dbSlimmingBackupLabel": "清理前备份数据库",
"dbSlimmingBackupDefaultLocation": "数据库所在目录(只保留最近一次清理备份)",
"dbSlimmingUseDefaultDirectoryButton": "使用默认目录",
@@ -873,6 +879,7 @@
"dbSlimmingBackupMissing": "没有找到最近一次清理备份",
"dbSlimmingBackupOpenFailed": "无法打开清理备份位置,请重试",
"dbSlimmingReportTasks": "将清理软删除任务 {{deleted}} 个、归档任务 {{archived}} 个",
+ "dbSlimmingReportTasksWithActive": "将清理活跃任务 {{active}} 个、软删除任务 {{deleted}} 个、归档任务 {{archived}} 个",
"dbSlimmingReportMessages": "预计清理 {{count}} 条消息内容(约 {{size}})",
"dbSlimmingReportSpace": "数据库 {{database}};临时空间至少需要 {{temporary}};当前可用 {{free}}",
"dbSlimmingSpaceUnknown": "未知",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 1df1b13260..afa5eba163 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -853,16 +853,22 @@
"chatAttachmentsClearFailed": "無法清理訊息附件快取,請重試",
"dbSlimmingBackupDirectoryDialogTitle": "選擇資料庫清理備份目錄",
"dbSlimmingLabel": "資料庫清理",
- "dbSlimmingDescription": "掃描軟刪除任務和長時間封存任務中的歷史訊息,確認後重新啟動 Cindy,在資料庫開啟前清理並壓縮。不會刪除磁碟附件或生成媒體。",
+ "dbSlimmingDescription": "掃描超過所選時間未更新的軟刪除和已封存任務歷史,可選擇同時納入活躍任務。確認後重新啟動 Cindy,在資料庫開啟前清理並壓縮。不會刪除磁碟附件或生成媒體。",
"dbSlimmingScanButton": "掃描資料庫",
"dbSlimmingScanLoading": "正在掃描資料庫,請稍候…",
"dbSlimmingScanResultTitle": "資料庫掃描結果",
"dbSlimmingExecutionLoading": "正在準備資料庫清理,Cindy 即將重新啟動…",
- "dbSlimmingArchiveAgeLabel": "清理封存時間超過",
+ "dbSlimmingArchiveAgeLabel": "清理未更新時間超過",
"dbSlimmingArchiveAgeOption7Days": "7 天",
"dbSlimmingArchiveAgeOption1": "1 個月",
"dbSlimmingArchiveAgeOption3": "3 個月",
"dbSlimmingArchiveAgeOption6": "6 個月",
+ "dbSlimmingIncludeActiveLabel": "清理活躍任務歷史",
+ "dbSlimmingIncludeActiveDescription": "同時清理超過所選時間的活躍任務歷史",
+ "dbSlimmingIncludeActiveConfirmTitle": "將活躍任務納入資料庫清理?",
+ "dbSlimmingIncludeActiveConfirmDescription": "活躍任務即使超過所選時間,也可能仍在執行。清理不會等待任務停止,任務在掃描後繼續產生的訊息也可能被清除。啟用後,超過所選時間的活躍、已封存和軟刪除任務都會被清理。符合範圍的活躍任務歷史訊息和 Agent 上下文將被清除;任務項目仍會保留。資料庫備份可以復原任務和訊息資料;不建立備份時,這些資料也無法復原。用於審查或撤銷這些訊息所產生檔案變更的記錄不包含在資料庫備份中,無法復原。",
+ "dbSlimmingIncludeActiveConfirmButton": "納入活躍任務",
+ "dbSlimmingIncludeActiveCancelButton": "保留活躍任務",
"dbSlimmingBackupLabel": "清理前備份資料庫",
"dbSlimmingBackupDefaultLocation": "資料庫所在目錄(只保留最近一次清理備份)",
"dbSlimmingUseDefaultDirectoryButton": "使用預設目錄",
@@ -873,6 +879,7 @@
"dbSlimmingBackupMissing": "找不到最近一次清理備份",
"dbSlimmingBackupOpenFailed": "無法開啟清理備份位置,請重試",
"dbSlimmingReportTasks": "將清理軟刪除任務 {{deleted}} 個、封存任務 {{archived}} 個",
+ "dbSlimmingReportTasksWithActive": "將清理活躍任務 {{active}} 個、軟刪除任務 {{deleted}} 個、封存任務 {{archived}} 個",
"dbSlimmingReportMessages": "預計清理 {{count}} 則訊息內容(約 {{size}})",
"dbSlimmingReportSpace": "資料庫 {{database}};暫存空間至少需要 {{temporary}};目前可用 {{free}}",
"dbSlimmingSpaceUnknown": "未知",
diff --git a/apps/desktop/src/shared/localDbMaintenance.ts b/apps/desktop/src/shared/localDbMaintenance.ts
index d6651fbb1a..4fc221bb98 100644
--- a/apps/desktop/src/shared/localDbMaintenance.ts
+++ b/apps/desktop/src/shared/localDbMaintenance.ts
@@ -9,13 +9,17 @@ export type DbSlimmingBackupLocation = 'database-directory' | 'custom-directory'
export interface DbSlimmingScanInput {
/** Legacy wire key retained so existing numeric month requests stay readable. */
archiveAgeMonths: DbSlimmingArchiveAge;
+ /** Explicit opt-in: active tasks are excluded from cleanup by default. */
+ includeActiveTasks?: boolean;
}
export interface DbSlimmingScanResult {
scanId: string;
archiveAgeMonths: DbSlimmingArchiveAge;
+ includeActiveTasks: boolean;
scannedAt: number;
archivedBeforeMs: number;
+ activeTaskCount: number;
deletedTaskCount: number;
archivedTaskCount: number;
messageCount: number;
@@ -84,6 +88,8 @@ export type DbSlimmingResult =
status: 'completed';
finishedAt: number;
archiveAgeMonths: DbSlimmingArchiveAge;
+ /** Missing on results written before active-task cleanup was introduced. */
+ activeTaskCount?: number;
deletedTaskCount: number;
archivedTaskCount: number;
messageCount: number;
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 7dd2a2544f..a5ef946c37 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -209,7 +209,7 @@ Cindy AI 个人账号的免费会员身份标签。只在服务端明确下发 a
### Database cleanup
-设置 → 存储空间内主动备份、清理非活跃任务消息并压缩本地数据库的功能名称。先登记为 proposed,待实际使用后再固化。
+设置 → 存储空间内主动备份、清理任务消息并压缩本地数据库的功能名称。默认只清理非活跃任务;用户确认开启可选项后,也会清理活跃任务的历史。先登记为 proposed,待实际使用后再固化。
### Release
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 967421ed49..12758275b2 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -1817,7 +1817,7 @@
"ja": "データベースのクリーンアップ",
"ko": "데이터베이스 정리"
},
- "note": "设置 → 存储空间内主动备份、清理非活跃任务消息并压缩本地数据库的功能名称。先登记为 proposed,待实际使用后再固化。"
+ "note": "设置 → 存储空间内主动备份、清理任务消息并压缩本地数据库的功能名称。默认只清理非活跃任务;用户确认开启可选项后,也会清理活跃任务的历史。先登记为 proposed,待实际使用后再固化。"
}
]
}