conversation-session-delete-all-archived-tasks.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import { access, mkdir, writeFile } from "node:fs/promises";
  2. import { basename, join } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { DEFAULT_WORKSPACE, clearAppData, waitForWorkspaceApp } from "#e2e/helpers/desktop-app";
  5. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  6. const home = process.env.ZCODE_E2E_HOME_DIR!;
  7. const prefix = "e2e-bulk-archive-";
  8. const control = `${prefix}active`;
  9. // prefix0 的附件被保留的普通任务引用;prefix24 有待处理输入,本次无法删除。
  10. const sharedOwner = `${prefix}0`;
  11. const pendingTask = `${prefix}24`;
  12. const artifactDir = join(home, ".zcode/cli/artifacts", sharedOwner);
  13. describe("TSL39:一键删除全部归档任务", () => {
  14. after(async () => {
  15. await clearAppData();
  16. });
  17. it("按批预检 25 条折叠归档:取消不写入,确认后删除可删项并保留被引用附件与普通任务", async function () {
  18. this.timeout(240000);
  19. // 修复原因:直接运行 wdio 时默认 HOME 是 `.e2e-home`(无 runId 后缀),旧守卫只认
  20. // `.e2e-home-*`,在 CI/本地单跑时误报;两种隔离目录名都只存在于 E2E runner。
  21. if (!home || !/^\.e2e-home(?:-|$)/u.test(basename(home)))
  22. throw new Error("isolated E2E HOME required");
  23. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45000);
  24. // 旧夹具依赖已移除的 runner 开关,且只有 Host 摘要,无法验证当前 CLI 删除命令。
  25. // 在进程退出后准备两库完整历史,冷启读取;执行阶段只经真实 UI 发送删除。
  26. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  27. afterElectronProcessExit: async () => {
  28. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"));
  29. const cli = new DatabaseSync(join(home, ".zcode/cli/db/db.sqlite"));
  30. try {
  31. const project = db
  32. .prepare("SELECT project_id FROM project_roots WHERE root_path=? LIMIT 1")
  33. .get(DEFAULT_WORKSPACE) as { project_id: string };
  34. const now = Date.now();
  35. for (let i = 0; i < 26; i++) {
  36. const id = i === 25 ? control : `${prefix}${i}`;
  37. const title = `E2E_BULK_ARCHIVE_${i}`,
  38. archived = i === 25 ? 0 : 1;
  39. cli
  40. .prepare(
  41. "INSERT INTO session(id,project_id,slug,directory,title,version,time_created,time_updated,title_source,last_outcome) VALUES(?,?,?,?,?,'1',?,?,'custom','completed')",
  42. )
  43. .run(id, "e2e-bulk-cli-scope", id, DEFAULT_WORKSPACE, title, now, now);
  44. db.prepare(
  45. "INSERT INTO tasks(workspace_key,workspace_path,task_id,title,provider,created_at,updated_at,host_id,root_path,project_id,archived,cli_title,cli_title_source,cli_created_at,cli_updated_at,cli_last_outcome,cli_deleted,meta_json) VALUES(?,?,?,?,'glm',?,?,'local',?,?,?,?, 'custom',?,?,'completed',0,?)",
  46. ).run(
  47. DEFAULT_WORKSPACE,
  48. DEFAULT_WORKSPACE,
  49. id,
  50. title,
  51. now,
  52. now,
  53. DEFAULT_WORKSPACE,
  54. project.project_id,
  55. archived,
  56. title,
  57. now,
  58. now,
  59. JSON.stringify({
  60. taskId: id,
  61. traceId: id,
  62. title,
  63. workspacePath: DEFAULT_WORKSPACE,
  64. createdAt: now,
  65. updatedAt: now,
  66. mode: "build",
  67. archived: Boolean(archived),
  68. }),
  69. );
  70. }
  71. // 普通任务引用 prefix0 的附件:预检须列出保留附件,删除后文件仍在。
  72. cli
  73. .prepare(
  74. "INSERT INTO message(id,session_id,time_created,time_updated,data) VALUES('e2e-bulk-ref-msg',?,1,1,?)",
  75. )
  76. .run(control, JSON.stringify({ role: "user" }));
  77. cli
  78. .prepare(
  79. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES('e2e-bulk-ref-part','e2e-bulk-ref-msg',?,1,1,?)",
  80. )
  81. .run(
  82. control,
  83. JSON.stringify({ type: "file", url: `zcode-artifact://${sharedOwner}/shared` }),
  84. );
  85. await mkdir(artifactDir, { recursive: true });
  86. await writeFile(join(artifactDir, "shared.png"), "E2E_BULK_SHARED_ATTACHMENT");
  87. await writeFile(join(artifactDir, "private.txt"), "E2E_BULK_PRIVATE_ATTACHMENT");
  88. } finally {
  89. db.close();
  90. cli.close();
  91. }
  92. },
  93. });
  94. await browser.execute(() => {
  95. (
  96. window as typeof window & { __testActions: { setLocale(value: string): void } }
  97. ).__testActions.setLocale("zh-CN");
  98. });
  99. expect(readCounts()).toEqual({
  100. archived: 25,
  101. deleted: 0,
  102. active: 1,
  103. cliRows: 26,
  104. cliDeleted: 0,
  105. });
  106. const removedVisitKey = `zcode-browser-recent-visits:${JSON.stringify([DEFAULT_WORKSPACE, "", `${prefix}0`])}`;
  107. const retainedVisitKey = `zcode-browser-recent-visits:${JSON.stringify([DEFAULT_WORKSPACE, "", control])}`;
  108. await browser.execute(
  109. (keys) => {
  110. const visit = JSON.stringify([
  111. {
  112. url: "https://example.test/browser-history",
  113. title: "Browser history",
  114. faviconUrl: null,
  115. lastVisitedAt: Date.now(),
  116. },
  117. ]);
  118. localStorage.setItem(keys.removed, visit);
  119. localStorage.setItem(keys.retained, visit);
  120. },
  121. { removed: removedVisitKey, retained: retainedVisitKey },
  122. );
  123. // 第二批(第 20 项之后)里的一项有待处理输入,预检必须逐项列为无法删除。
  124. const pendingDb = new DatabaseSync(join(home, ".zcode/cli/db/db.sqlite"));
  125. try {
  126. pendingDb
  127. .prepare(
  128. "INSERT INTO session_input(id,session_id,kind,delivery,payload,admitted_sequence,status,time_created,time_updated) VALUES('e2e-bulk-queued',?,'prompt','queue','{}',1,'admitted',1,1)",
  129. )
  130. .run(pendingTask);
  131. } finally {
  132. pendingDb.close();
  133. }
  134. // 只观察不拦截:记录批量预检 RPC 次数与弹窗出现过的进度,证明按批(20+5)推进而非逐项。
  135. await browser.execute(() => {
  136. const original = MessagePort.prototype.postMessage;
  137. const probe = { calls: 0, progress: [] as string[] };
  138. (window as typeof window & { __tsl39Preflight?: typeof probe }).__tsl39Preflight = probe;
  139. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  140. if (
  141. message instanceof Uint8Array &&
  142. new TextDecoder().decode(message).includes("previewArchivedTaskDeletions")
  143. )
  144. probe.calls++;
  145. return Reflect.apply(
  146. original,
  147. this,
  148. options === undefined ? [message] : [message, options],
  149. );
  150. };
  151. new MutationObserver(() => {
  152. const text = document.querySelector(
  153. '[data-confirm-intent="archive-management-delete"]',
  154. )?.textContent;
  155. const value = text?.match(/正在检查 (\d+\/\d+) 个会话/u)?.[1];
  156. if (value && probe.progress.at(-1) !== value) probe.progress.push(value);
  157. }).observe(document.body, { childList: true, subtree: true, characterData: true });
  158. });
  159. const preflight = () =>
  160. browser.execute(
  161. () =>
  162. (
  163. window as typeof window & {
  164. __tsl39Preflight: { calls: number; progress: string[] };
  165. }
  166. ).__tsl39Preflight,
  167. );
  168. await $('[data-testid="task-settings-button"]').click();
  169. await $('[data-testid="settings-section-nav-archives"]').click();
  170. await $('[data-testid="archive-management"]').waitForDisplayed();
  171. // 分组收起没有行 DOM;批量目标必须来自完整权威集合,不能只删除已渲染行。
  172. expect(await $$('[data-testid="archive-task"]').length).toBe(0);
  173. const removeAll = $('[data-testid="archive-delete-all"]');
  174. await removeAll.click();
  175. const confirmation = $('[data-confirm-intent="archive-management-delete"]');
  176. await expect(confirmation).toHaveText(expect.stringContaining("25"));
  177. await browser.keys("Escape");
  178. await confirmation.waitForExist({ reverse: true });
  179. const historyAfterCancel = await browser.execute(
  180. (key) => localStorage.getItem(key),
  181. removedVisitKey,
  182. );
  183. expect(historyAfterCancel).not.toBeNull();
  184. expect(readCounts()).toEqual({
  185. archived: 25,
  186. deleted: 0,
  187. active: 1,
  188. cliRows: 26,
  189. cliDeleted: 0,
  190. });
  191. const callsBeforeConfirm = (await preflight()).calls;
  192. await browser.execute(() => {
  193. (
  194. window as typeof window & { __tsl39Preflight: { progress: string[] } }
  195. ).__tsl39Preflight.progress = [];
  196. });
  197. await removeAll.click();
  198. await expect(confirmation).toHaveText(expect.stringContaining("25"));
  199. const confirmButton = $('[data-testid="confirm-dialog-confirm"]');
  200. await expect(confirmButton).toHaveText("永久删除 24 个会话", { wait: 60000 });
  201. await expect(confirmButton).toBeEnabled();
  202. // 25 项分两批:只发 2 次批量预检,进度从 0 跳到 20 再完成,不逐项前进。
  203. const checked = await preflight();
  204. expect(checked.calls - callsBeforeConfirm).toBe(2);
  205. // 最后一批的 25/25 与结果清单在同一轮提交,可能不单独渲染,故不计入比较。
  206. expect(checked.progress.filter((value) => value !== "25/25")).toEqual(["0/25", "20/25"]);
  207. await expect(confirmation).toHaveText(
  208. expect.stringContaining("附件 shared.png:被 E2E_BULK_ARCHIVE_25 引用,保留文件"),
  209. );
  210. await expect(confirmation).toHaveText(
  211. expect.stringMatching(/本次无法删除\s*• E2E_BULK_ARCHIVE_24 · .*任务仍在运行或有待处理输入/u),
  212. );
  213. await browser.saveScreenshot(
  214. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "delete-all-archived-tasks-preflight.png"),
  215. );
  216. await confirmButton.click();
  217. // 永久删除走存储控制面,无需冷恢复 24 个 Agent runtime。
  218. await browser.waitUntil(() => readCounts().cliRows === 2, { timeout: 120000 });
  219. expect(readCounts()).toEqual({
  220. archived: 1,
  221. deleted: 0,
  222. active: 1,
  223. cliRows: 2,
  224. cliDeleted: 0,
  225. });
  226. // 被保留会话引用的附件留下,同一会话的独占附件删除。
  227. await access(join(artifactDir, "shared.png"));
  228. await expect(access(join(artifactDir, "private.txt"))).rejects.toThrow();
  229. await expect(removeAll).toBeEnabled();
  230. const visitsAfterDelete = await browser.execute(
  231. (keys) => ({
  232. removed: localStorage.getItem(keys.removed),
  233. retained: localStorage.getItem(keys.retained),
  234. }),
  235. { removed: removedVisitKey, retained: retainedVisitKey },
  236. );
  237. expect(visitsAfterDelete.removed).toBeNull();
  238. expect(visitsAfterDelete.retained).not.toBeNull();
  239. expect(await $$('[data-testid="archive-group"]').length).toBe(1);
  240. await browser.saveScreenshot(
  241. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "delete-all-archived-tasks.png"),
  242. );
  243. });
  244. });
  245. function readCounts() {
  246. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"), { readOnly: true });
  247. const cli = new DatabaseSync(join(home, ".zcode/cli/db/db.sqlite"), { readOnly: true });
  248. try {
  249. return {
  250. ...(db
  251. .prepare(
  252. "SELECT sum(archived=1 AND cli_deleted=0) AS archived, sum(cli_deleted=1) AS deleted, sum(task_id=? AND archived=0 AND cli_deleted=0) AS active FROM tasks WHERE task_id LIKE ?",
  253. )
  254. .get(control, `${prefix}%`) as { archived: number; deleted: number; active: number }),
  255. ...(cli
  256. .prepare(
  257. "SELECT count(*) AS cliRows, sum(time_deleted IS NOT NULL) AS cliDeleted FROM session WHERE id LIKE ?",
  258. )
  259. .get(`${prefix}%`) as { cliRows: number; cliDeleted: number }),
  260. };
  261. } finally {
  262. db.close();
  263. cli.close();
  264. }
  265. }