Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 数据库清理后移除活跃任务列表条目 (#5098)

DavidShenXD9c7ae816c8ca
diff --git a/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts b/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts
index a0bff6a676..f2c45fed48 100644
--- a/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/dbSlimmingMaintenance.test.ts
@@ -392,7 +392,7 @@ describe('runDbSlimmingMaintenance', () => {
}
});
- it('cleans only tasks older than the selected cutoff and keeps every recent status intact', async () => {
+ it('removes cleaned active tasks from lists and keeps every recent status intact', async () => {
createCleanupFixture();
const cleanedTurnChangeSetDir = path.join(tmpDir, 'turn-change-sets', 'active-old');
const retainedTurnChangeSetDir = path.join(
@@ -481,7 +481,7 @@ describe('runDbSlimmingMaintenance', () => {
FROM sessions WHERE id = 'active-old'
`).get(),
).toEqual({
- status: 'active',
+ status: 'deleted',
updated_at: 2_000,
sdk_session_id: null,
list_preview: null,
@@ -491,6 +491,12 @@ describe('runDbSlimmingMaintenance', () => {
codex_plan_json: null,
summary: null,
});
+ expect(
+ db.prepare("SELECT id FROM sessions WHERE status = 'active' ORDER BY id").all(),
+ ).toEqual([{ id: 'active-recent' }, { id: 'active-updated-after-scan' }]);
+ expect(
+ db.prepare("SELECT id FROM sessions WHERE status != 'deleted' AND id = 'active-old'").all(),
+ ).toEqual([]);
expect(
db.prepare(`
SELECT updated_at, sdk_session_id, list_preview, list_preview_role,
@@ -565,6 +571,116 @@ describe('runDbSlimmingMaintenance', () => {
}
});
+ it.each(
+ [null, 0, 1].flatMap((existingCloseTerminal) =>
+ [false, true].map((rollback) => ({ existingCloseTerminal, rollback })),
+ ),
+ )(
+ 'closes sharing and queued input atomically while preserving Bot timelines (existingCloseTerminal=$existingCloseTerminal, rollback=$rollback)',
+ async ({ existingCloseTerminal, rollback }) => {
+ createCleanupFixture();
+ const setup = createBetterSqliteDatabase(dbFilePath, { fileMustExist: true });
+ try {
+ setup.exec(`
+ ALTER TABLE sessions ADD COLUMN source TEXT;
+ UPDATE sessions SET source = 'bot' WHERE id = 'active-old';
+ CREATE TABLE shared_task_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ shared_task_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ revision INTEGER NOT NULL,
+ kind TEXT NOT NULL,
+ terminal INTEGER NOT NULL,
+ snapshot TEXT,
+ recorded_at INTEGER NOT NULL,
+ UNIQUE (shared_task_id, kind, revision)
+ );
+ `);
+ for (const id of ['active-old', 'active-recent', 'active-updated-after-scan']) {
+ setup
+ .prepare(
+ `
+ INSERT INTO shared_task_events
+ (shared_task_id, session_id, revision, kind, terminal, recorded_at)
+ VALUES (?, ?, 1, 'authority', 0, 100)
+ `,
+ )
+ .run(`shared-${id}`, id);
+ if (existingCloseTerminal !== null) {
+ setup
+ .prepare(
+ `INSERT INTO shared_task_events
+ (shared_task_id, session_id, revision, kind, terminal, recorded_at)
+ VALUES (?, ?, 0, 'local-close', ?, 100)`,
+ )
+ .run(`shared-${id}`, id, existingCloseTerminal);
+ }
+ setup.prepare('INSERT INTO agent_input_queue_snapshots VALUES (?, ?)').run(id, '[]');
+ }
+ } finally {
+ setup.close();
+ }
+
+ const outcome = await runDbSlimmingMaintenance({
+ userDataDir: tmpDir,
+ dbFilePath,
+ request: request({ includeActiveTasks: true }),
+ now: () => 3_000,
+ log,
+ beforeReplacement: rollback
+ ? async () => {
+ throw new Error('replacement cancelled');
+ }
+ : undefined,
+ });
+ expect(outcome.result.status).toBe(rollback ? 'failed' : 'completed');
+ const db = createBetterSqliteDatabase(dbFilePath, { fileMustExist: true });
+ try {
+ expect(
+ db.prepare("SELECT id, status FROM sessions WHERE id LIKE 'active-%' ORDER BY id").all(),
+ ).toEqual([
+ { id: 'active-old', status: 'active' },
+ { id: 'active-recent', status: 'active' },
+ { id: 'active-updated-after-scan', status: rollback ? 'active' : 'deleted' },
+ ]);
+ expect(
+ db
+ .prepare(
+ "SELECT session_id, terminal, recorded_at FROM shared_task_events WHERE kind = 'local-close' ORDER BY session_id",
+ )
+ .all(),
+ ).toEqual(
+ existingCloseTerminal === null
+ ? rollback
+ ? []
+ : [{ session_id: 'active-updated-after-scan', terminal: 1, recorded_at: 2_000 }]
+ : [
+ { session_id: 'active-old', terminal: existingCloseTerminal, recorded_at: 100 },
+ { session_id: 'active-recent', terminal: existingCloseTerminal, recorded_at: 100 },
+ {
+ session_id: 'active-updated-after-scan',
+ terminal: rollback ? existingCloseTerminal : 1,
+ recorded_at: 100,
+ },
+ ],
+ );
+ expect(
+ db
+ .prepare(
+ "SELECT session_id FROM agent_input_queue_snapshots WHERE session_id LIKE 'active-%' ORDER BY session_id",
+ )
+ .all(),
+ ).toEqual([
+ { session_id: 'active-old' },
+ { session_id: 'active-recent' },
+ ...(rollback ? [{ session_id: 'active-updated-after-scan' }] : []),
+ ]);
+ } finally {
+ db.close();
+ }
+ },
+ );
+
it('keeps the untouched original as the latest default-directory slimming backup', async () => {
createCleanupFixture();
const beforeBytes = estimateDbFilesBytes(dbFilePath);
@@ -572,7 +688,7 @@ describe('runDbSlimmingMaintenance', () => {
const outcome = await runDbSlimmingMaintenance({
userDataDir: tmpDir,
dbFilePath,
- request: request({ beforeBytes, backupEnabled: true }),
+ request: request({ beforeBytes, backupEnabled: true, includeActiveTasks: true }),
now: () => 3_000,
log,
});
@@ -589,6 +705,9 @@ describe('runDbSlimmingMaintenance', () => {
});
try {
expect(backup.prepare('SELECT count(*) AS count FROM messages').get()).toEqual({ count: 8 });
+ expect(backup.prepare("SELECT status FROM sessions WHERE id = 'active-old'").get()).toEqual({
+ status: 'active',
+ });
} finally {
backup.close();
}
diff --git a/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts b/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts
index 14d8962777..acd78abbe4 100644
--- a/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts
+++ b/apps/desktop/src/main/localDb/dbSlimmingMaintenance.ts
@@ -20,6 +20,7 @@ import {
writeDbSlimmingRequest,
writeDbSlimmingResult,
} from './maintenanceStore';
+import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from './sharedTaskClosureSql';
const TEMP_SPACE_MARGIN_BYTES = 64 * 1024 * 1024;
const SQLITE_SIDECAR_SUFFIXES = ['-wal', '-shm', '-journal'] as const;
@@ -751,6 +752,48 @@ function compactWorkingCopy(
)
.run(...activeResetBoundaryParameters);
}
+ // Cleared ordinary tasks must not remain as empty entries in local or
+ // remote lists. Bot-owned timelines keep their separate lifecycle.
+ activeDb.exec(
+ `UPDATE sessions SET status = 'deleted'
+ WHERE id IN (
+ SELECT id FROM temp.db_slimming_targets WHERE status = 'active'
+ )${sessionColumns.has('source') ? " AND COALESCE(source, '') != 'bot'" : ''}`,
+ );
+ if (tableExists(activeDb, 'agent_input_queue_snapshots')) {
+ activeDb.exec(
+ `DELETE FROM agent_input_queue_snapshots
+ WHERE session_id IN (
+ SELECT s.id FROM sessions s
+ JOIN temp.db_slimming_targets t ON t.id = s.id
+ WHERE t.status = 'active' AND s.status = 'deleted'
+ )`,
+ );
+ }
+ if (tableExists(activeDb, 'shared_task_events')) {
+ // Persist closure in the same transaction; relay recovery consumes
+ // this existing journal after the compacted database is installed.
+ const sharedTasks = activeDb
+ .prepare(
+ `SELECT DISTINCT e.session_id AS sessionId
+ FROM shared_task_events e
+ JOIN temp.db_slimming_targets t ON t.id = e.session_id
+ JOIN sessions s ON s.id = t.id
+ WHERE t.status = 'active' AND s.status = 'deleted'`,
+ )
+ .all() as Array<{ sessionId: string }>;
+ const closeSharedTask = activeDb.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL);
+ const commitPreparedClose = activeDb.prepare(
+ `UPDATE shared_task_events SET terminal = 1
+ WHERE session_id = ? AND kind = 'local-close' AND revision = 0 AND terminal = 0`,
+ );
+ for (const { sessionId } of sharedTasks) {
+ closeSharedTask.run(Math.floor(request.scannedAt), sessionId);
+ // An interrupted preparation may already occupy the unique fence.
+ // Commit it together with deletion so relay recovery can retry it.
+ commitPreparedClose.run(sessionId);
+ }
+ }
}
if (messagesFtsDeleteTriggerSql) activeDb.exec(messagesFtsDeleteTriggerSql);
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e13b8c4cb3..417f3c44a0 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1221,10 +1221,10 @@
"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",
+ "dbSlimmingIncludeActiveLabel": "Clean Active Tasks",
+ "dbSlimmingIncludeActiveDescription": "Also clean active tasks older than the selected period and remove them from the task list",
"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.",
+ "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; ordinary task entries will also be removed from the list, while teammates’ main tasks 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",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 25b30cc3d6..df6c8e9ddb 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1221,10 +1221,10 @@
"dbSlimmingArchiveAgeOption1": "1 か月",
"dbSlimmingArchiveAgeOption3": "3 か月",
"dbSlimmingArchiveAgeOption6": "6 か月",
- "dbSlimmingIncludeActiveLabel": "アクティブなタスクの履歴も削除",
- "dbSlimmingIncludeActiveDescription": "選択した期間を超えたアクティブなタスクの履歴もクリーンアップします",
+ "dbSlimmingIncludeActiveLabel": "アクティブなセッションをクリーンアップ",
+ "dbSlimmingIncludeActiveDescription": "選択した期間を超えたアクティブなセッションもクリーンアップし、一覧から削除します",
"dbSlimmingIncludeActiveConfirmTitle": "アクティブなタスクもデータベースのクリーンアップ対象にしますか?",
- "dbSlimmingIncludeActiveConfirmDescription": "選択した期間を超えたアクティブなタスクでも、まだ実行中の可能性があります。クリーンアップはタスクの停止を待たず、スキャン後に追加されたメッセージも削除される場合があります。有効にすると、選択した期間を超えて更新されていないアクティブ、アーカイブ済み、論理削除済みのタスクがクリーンアップされます。対象のアクティブなタスクの履歴と Agent コンテキストは削除されますが、タスク自体は残ります。データベースのバックアップではタスクとメッセージのデータを復元できます。バックアップを作成しない場合、それらのデータも復元できません。それらのメッセージによるファイル変更のレビューや元に戻す操作に使う記録はデータベースのバックアップに含まれず、復元できません。",
+ "dbSlimmingIncludeActiveConfirmDescription": "選択した期間を超えたアクティブなタスクでも、まだ実行中の可能性があります。クリーンアップはタスクの停止を待たず、スキャン後に追加されたメッセージも削除される場合があります。有効にすると、選択した期間を超えて更新されていないアクティブ、アーカイブ済み、論理削除済みのタスクがクリーンアップされます。対象のアクティブなセッションの履歴と Agent コンテキストは削除され、通常のセッションは一覧からも削除されます。仲間のメインセッションは残ります。データベースのバックアップではタスクとメッセージのデータを復元できます。バックアップを作成しない場合、それらのデータも復元できません。それらのメッセージによるファイル変更のレビューや元に戻す操作に使う記録はデータベースのバックアップに含まれず、復元できません。",
"dbSlimmingIncludeActiveConfirmButton": "アクティブなタスクを含める",
"dbSlimmingIncludeActiveCancelButton": "アクティブなタスクを残す",
"dbSlimmingBackupLabel": "クリーンアップ前にデータベースをバックアップ",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 36d3306962..2a2d21f825 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1221,10 +1221,10 @@
"dbSlimmingArchiveAgeOption1": "1개월",
"dbSlimmingArchiveAgeOption3": "3개월",
"dbSlimmingArchiveAgeOption6": "6개월",
- "dbSlimmingIncludeActiveLabel": "활성 작업 기록도 정리",
- "dbSlimmingIncludeActiveDescription": "선택한 기간보다 오래된 활성 작업의 기록도 정리합니다",
+ "dbSlimmingIncludeActiveLabel": "활성 세션 정리",
+ "dbSlimmingIncludeActiveDescription": "선택한 기간보다 오래된 활성 세션도 정리하고 세션 목록에서 제거합니다",
"dbSlimmingIncludeActiveConfirmTitle": "활성 작업도 데이터베이스 정리 대상에 포함할까요?",
- "dbSlimmingIncludeActiveConfirmDescription": "선택한 기간보다 오래된 활성 작업도 아직 실행 중일 수 있습니다. 정리는 작업이 중지될 때까지 기다리지 않으며 스캔 후 추가된 메시지도 삭제될 수 있습니다. 사용하면 선택한 기간보다 오래 업데이트되지 않은 활성, 보관 및 소프트 삭제 작업이 정리됩니다. 대상 활성 작업의 기록과 Agent 컨텍스트는 삭제되지만 작업 항목은 유지됩니다. 데이터베이스 백업으로 작업과 메시지 데이터는 복구할 수 있습니다. 백업을 만들지 않으면 해당 데이터도 복구할 수 없습니다. 해당 메시지의 파일 변경 사항을 검토하거나 실행 취소하는 데 사용되는 기록은 데이터베이스 백업에 포함되지 않으며 복구할 수 없습니다.",
+ "dbSlimmingIncludeActiveConfirmDescription": "선택한 기간보다 오래된 활성 작업도 아직 실행 중일 수 있습니다. 정리는 작업이 중지될 때까지 기다리지 않으며 스캔 후 추가된 메시지도 삭제될 수 있습니다. 사용하면 선택한 기간보다 오래 업데이트되지 않은 활성, 보관 및 소프트 삭제 작업이 정리됩니다. 대상 활성 세션의 기록과 Agent 컨텍스트가 삭제되며 일반 세션 항목도 목록에서 제거됩니다. 동료의 기본 세션은 유지됩니다. 데이터베이스 백업으로 작업과 메시지 데이터는 복구할 수 있습니다. 백업을 만들지 않으면 해당 데이터도 복구할 수 없습니다. 해당 메시지의 파일 변경 사항을 검토하거나 실행 취소하는 데 사용되는 기록은 데이터베이스 백업에 포함되지 않으며 복구할 수 없습니다.",
"dbSlimmingIncludeActiveConfirmButton": "활성 작업 포함",
"dbSlimmingIncludeActiveCancelButton": "활성 작업 유지",
"dbSlimmingBackupLabel": "정리 전 데이터베이스 백업",
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 c2e2e8fb87..ef389bb670 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1221,10 +1221,10 @@
"dbSlimmingArchiveAgeOption1": "1 个月",
"dbSlimmingArchiveAgeOption3": "3 个月",
"dbSlimmingArchiveAgeOption6": "6 个月",
- "dbSlimmingIncludeActiveLabel": "清理活跃任务历史",
- "dbSlimmingIncludeActiveDescription": "同时清理超过所选时间的活跃任务历史",
+ "dbSlimmingIncludeActiveLabel": "清理活跃任务",
+ "dbSlimmingIncludeActiveDescription": "同时清理超过所选时间的活跃任务,并从任务列表移除",
"dbSlimmingIncludeActiveConfirmTitle": "将活跃任务纳入数据库清理?",
- "dbSlimmingIncludeActiveConfirmDescription": "活跃任务即使超过所选时间,也可能仍在运行。清理不会等待任务停止,任务在扫描后继续产生的消息也可能被清除。启用后,超过所选时间的活跃、已归档和软删除任务都会被清理。符合范围的活跃任务历史消息和 Agent 上下文将被清除;任务条目仍会保留。数据库备份可以恢复任务和消息数据;不创建备份时,这些数据也无法恢复。用于审查或撤销这些消息所产生文件改动的记录不包含在数据库备份中,无法恢复。",
+ "dbSlimmingIncludeActiveConfirmDescription": "活跃任务即使超过所选时间,也可能仍在运行。清理不会等待任务停止,任务在扫描后继续产生的消息也可能被清除。启用后,超过所选时间的活跃、已归档和软删除任务都会被清理。符合范围的活跃任务历史消息和 Agent 上下文将被清除;普通任务条目也将从列表移除,伙伴主任务仍会保留。数据库备份可以恢复任务和消息数据;不创建备份时,这些数据也无法恢复。用于审查或撤销这些消息所产生文件改动的记录不包含在数据库备份中,无法恢复。",
"dbSlimmingIncludeActiveConfirmButton": "纳入活跃任务",
"dbSlimmingIncludeActiveCancelButton": "保留活跃任务",
"dbSlimmingBackupLabel": "清理前备份数据库",
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 45ce25b079..753e0e17a2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1221,10 +1221,10 @@
"dbSlimmingArchiveAgeOption1": "1 個月",
"dbSlimmingArchiveAgeOption3": "3 個月",
"dbSlimmingArchiveAgeOption6": "6 個月",
- "dbSlimmingIncludeActiveLabel": "清理活躍任務歷史",
- "dbSlimmingIncludeActiveDescription": "同時清理超過所選時間的活躍任務歷史",
+ "dbSlimmingIncludeActiveLabel": "清理活躍任務",
+ "dbSlimmingIncludeActiveDescription": "同時清理超過所選時間的活躍任務,並從任務列表移除",
"dbSlimmingIncludeActiveConfirmTitle": "將活躍任務納入資料庫清理?",
- "dbSlimmingIncludeActiveConfirmDescription": "活躍任務即使超過所選時間,也可能仍在執行。清理不會等待任務停止,任務在掃描後繼續產生的訊息也可能被清除。啟用後,超過所選時間的活躍、已封存和軟刪除任務都會被清理。符合範圍的活躍任務歷史訊息和 Agent 上下文將被清除;任務項目仍會保留。資料庫備份可以復原任務和訊息資料;不建立備份時,這些資料也無法復原。用於審查或撤銷這些訊息所產生檔案變更的記錄不包含在資料庫備份中,無法復原。",
+ "dbSlimmingIncludeActiveConfirmDescription": "活躍任務即使超過所選時間,也可能仍在執行。清理不會等待任務停止,任務在掃描後繼續產生的訊息也可能被清除。啟用後,超過所選時間的活躍、已封存和軟刪除任務都會被清理。符合範圍的活躍任務歷史訊息和 Agent 上下文將被清除;一般任務項目也將從列表移除,夥伴主任務仍會保留。資料庫備份可以復原任務和訊息資料;不建立備份時,這些資料也無法復原。用於審查或撤銷這些訊息所產生檔案變更的記錄不包含在資料庫備份中,無法復原。",
"dbSlimmingIncludeActiveConfirmButton": "納入活躍任務",
"dbSlimmingIncludeActiveCancelButton": "保留活躍任務",
"dbSlimmingBackupLabel": "清理前備份資料庫",