conversation-session-auto-archived-task-closes-side-pane-tabs.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import { createServer, type Server } from "node:http";
  2. import { DatabaseSync } from "node:sqlite";
  3. import { join } from "node:path";
  4. import type { AddressInfo } from "node:net";
  5. import { TID_BROWSER_ADDRESS_INPUT, TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  6. import { DEFAULT_WORKSPACE, clearAppData } from "#e2e/helpers/desktop-app";
  7. import { seedArchiveAutomations } from "#e2e/helpers/archive-automations";
  8. import { ensureProjectExpanded } from "#e2e/helpers/project-sidebar";
  9. import { openFirstBrowserTab } from "#e2e/helpers/browser-side-pane";
  10. import {
  11. prepareV4ConversationE2E,
  12. sendV4Prompt,
  13. waitForV4AssistantMessageContaining,
  14. waitForV4Pane,
  15. } from "#e2e/helpers/v4-conversation";
  16. const CASE_TIMEOUT_MS = 180_000;
  17. const PROMPT_MARKER = "E2E_AUTO_ARCHIVED_TASK_BROWSER_TABS";
  18. const REPLY_MARKER = "AUTO_ARCHIVED_TASK_BROWSER_TABS_OK";
  19. const DAY = 86_400_000;
  20. const home = process.env.ZCODE_E2E_HOME_DIR!;
  21. let fixtureServer: Server | null = null;
  22. let fixtureUrl = "";
  23. describe("自动归档任务关闭其全部 tab", () => {
  24. before(async () => {
  25. fixtureServer = createFixtureServer();
  26. fixtureUrl = `${await listen(fixtureServer)}/archived-task-tab`;
  27. });
  28. after(async () => {
  29. await closeServer(fixtureServer);
  30. fixtureServer = null;
  31. await browser.electron.restoreAllMocks();
  32. await clearAppData();
  33. });
  34. it("自动归档关闭该任务的全部 tab,取消归档后不恢复", async function () {
  35. this.timeout(CASE_TIMEOUT_MS);
  36. await prepareV4ConversationE2E();
  37. await sendV4Prompt(`${PROMPT_MARKER}: Reply with exactly "${REPLY_MARKER}" and no other text.`);
  38. await waitForV4AssistantMessageContaining(REPLY_MARKER, 60_000);
  39. const completed = await waitForV4Pane(
  40. (snapshot) =>
  41. !snapshot.canStop && Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  42. "前置任务没有完成",
  43. 60_000,
  44. );
  45. const taskId = requireTaskId(completed.sessionId);
  46. const automations = await seedArchiveAutomations({ workspacePath: DEFAULT_WORKSPACE, taskId });
  47. await openFirstBrowserTab();
  48. const addressInput = await $(`[data-testid="${TID_BROWSER_ADDRESS_INPUT}"]`);
  49. await addressInput.waitForDisplayed({ timeout: 15_000 });
  50. await addressInput.setValue(fixtureUrl);
  51. await addressInput.click();
  52. await browser.keys("Enter");
  53. await waitForFixtureGuest(true, "任务内 Browser tab 没有创建 guest");
  54. await openLauncherItem("terminal");
  55. const taskTabIds = await readSidePaneTabIds();
  56. expect(taskTabIds.some((id) => id.startsWith("browser:"))).toBe(true);
  57. expect(taskTabIds.length).toBeGreaterThanOrEqual(2);
  58. // 自动归档只看 CLI 最后活动时间;把它拨到保留期之外,再开启设置触发 Host 补扫。
  59. ageTask(taskId, 60 * DAY);
  60. await openArchivedView();
  61. const toggle = $('[data-testid="archive-auto-archive-switch"]');
  62. await toggle.waitForDisplayed();
  63. expect(await toggle.getAttribute("aria-checked")).toBe("false");
  64. await toggle.click();
  65. await browser.waitUntil(() => readArchived(taskId) === 1, {
  66. timeout: 30_000,
  67. timeoutMsg: "开启自动归档后任务没有被归档",
  68. });
  69. await waitForFixtureGuest(false, "自动归档任务后它的 Browser guest 仍然存活");
  70. await automations.assertPaused();
  71. await toggle.click();
  72. await expandArchivedGroups();
  73. await $(
  74. `[data-testid="archive-task"][data-task-id="${taskId}"] [data-testid="archive-unarchive"]`,
  75. ).click();
  76. await waitForArchivedRow(taskId, false, "取消归档后 Archived 仍显示任务");
  77. await automations.assertPaused();
  78. await $('[data-testid="settings-back-button"]').click();
  79. await ensureProjectExpanded(DEFAULT_WORKSPACE);
  80. await waitForProjectRow(taskId, true, "取消归档后任务没有回到 Project");
  81. await $(`[data-testid="${testId(TID_TASK_ITEM, taskId)}"]`).click();
  82. await waitForV4Pane((snapshot) => snapshot.sessionId === taskId, "没有重新打开取消归档的任务");
  83. await browser.pause(1_000);
  84. const restoredTabIds = await readSidePaneTabIds();
  85. expect(restoredTabIds.filter((id) => taskTabIds.includes(id))).toEqual([]);
  86. expect(await readFixtureGuestCount()).toBe(0);
  87. });
  88. });
  89. function requireTaskId(value: string | null): string {
  90. if (!value || value === "draft") throw new Error(`缺少 taskId: ${String(value)}`);
  91. return value;
  92. }
  93. async function readFixtureGuestCount(): Promise<number> {
  94. const urls = (await browser.electron.execute((electron) =>
  95. electron.webContents
  96. .getAllWebContents()
  97. .filter((contents) => !contents.isDestroyed() && contents.getType() === "webview")
  98. .map((contents) => contents.getURL()),
  99. )) as unknown as string[];
  100. return urls.filter((url) => url === fixtureUrl).length;
  101. }
  102. async function waitForFixtureGuest(expected: boolean, timeoutMsg: string): Promise<void> {
  103. await browser.waitUntil(async () => (await readFixtureGuestCount()) > 0 === expected, {
  104. timeout: 30_000,
  105. timeoutMsg,
  106. });
  107. }
  108. function ageTask(taskId: string, ageMs: number): void {
  109. const updatedAt = Date.now() - ageMs;
  110. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"));
  111. const cli = new DatabaseSync(join(home, ".zcode/cli/db/db.sqlite"));
  112. try {
  113. db.prepare("UPDATE tasks SET cli_updated_at=? WHERE task_id=?").run(updatedAt, taskId);
  114. cli.prepare("UPDATE session SET time_updated=? WHERE id=?").run(updatedAt, taskId);
  115. } finally {
  116. db.close();
  117. cli.close();
  118. }
  119. }
  120. function readArchived(taskId: string): number | undefined {
  121. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"), { readOnly: true });
  122. try {
  123. return (
  124. db.prepare("SELECT archived FROM tasks WHERE task_id=?").get(taskId) as
  125. | { archived: number }
  126. | undefined
  127. )?.archived;
  128. } finally {
  129. db.close();
  130. }
  131. }
  132. async function openArchivedView(): Promise<void> {
  133. await $('[data-testid="task-settings-button"]').click();
  134. await $('[data-testid="settings-section-nav-archives"]').click();
  135. await $('[data-testid="archive-management"]').waitForDisplayed();
  136. }
  137. async function expandArchivedGroups(): Promise<void> {
  138. await browser.waitUntil(
  139. async () => (await $$('[data-testid="archive-group-toggle"]').length) > 0,
  140. {
  141. timeout: 15_000,
  142. timeoutMsg: "Archived 没有出现分组",
  143. },
  144. );
  145. for (const toggle of await $$('[data-testid="archive-group-toggle"]')) {
  146. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  147. }
  148. }
  149. async function readSidePaneTabIds(): Promise<string[]> {
  150. return browser.execute(() =>
  151. Array.from(document.querySelectorAll<HTMLElement>("[data-side-pane-tab-id]")).map(
  152. (element) => element.dataset.sidePaneTabId ?? "",
  153. ),
  154. );
  155. }
  156. async function openLauncherItem(itemId: string): Promise<void> {
  157. const before = (await readSidePaneTabIds()).length;
  158. await browser.waitUntil(
  159. () =>
  160. browser.execute(() => {
  161. const trigger = document.querySelector<HTMLElement>("[data-side-pane-add-trigger]");
  162. if (!trigger) return false;
  163. trigger.dispatchEvent(
  164. new PointerEvent("pointerdown", {
  165. bubbles: true,
  166. cancelable: true,
  167. button: 0,
  168. pointerId: 1,
  169. pointerType: "mouse",
  170. }),
  171. );
  172. trigger.click();
  173. return true;
  174. }),
  175. { timeout: 10_000, timeoutMsg: "没有找到新建 tab 入口" },
  176. );
  177. await browser.waitUntil(
  178. () =>
  179. browser.execute((id) => {
  180. const item = document.querySelector<HTMLElement>(
  181. `[data-state="active"] [data-side-pane-open-tab-item="${id}"]`,
  182. );
  183. if (!item) return false;
  184. item.click();
  185. return true;
  186. }, itemId),
  187. { timeout: 10_000, timeoutMsg: `新建 tab 菜单里没有 ${itemId}` },
  188. );
  189. await browser.waitUntil(async () => (await readSidePaneTabIds()).length > before, {
  190. timeout: 15_000,
  191. timeoutMsg: `${itemId} tab 没有打开`,
  192. });
  193. }
  194. async function waitForProjectRow(taskId: string, expected: boolean, timeoutMsg: string) {
  195. await browser.waitUntil(
  196. () =>
  197. browser.execute(
  198. (taskItemTestId, shouldExist) =>
  199. Boolean(document.querySelector(`[data-testid="${taskItemTestId}"]`)) === shouldExist,
  200. testId(TID_TASK_ITEM, taskId),
  201. expected,
  202. ),
  203. { timeout: 30_000, timeoutMsg },
  204. );
  205. }
  206. async function waitForArchivedRow(taskId: string, expected: boolean, timeoutMsg: string) {
  207. await browser.waitUntil(
  208. async () =>
  209. (await $(`[data-testid="archive-task"][data-task-id="${taskId}"]`).isExisting()) === expected,
  210. { timeout: 30_000, timeoutMsg },
  211. );
  212. }
  213. function createFixtureServer(): Server {
  214. return createServer((_request, response) => {
  215. response.setHeader("content-type", "text/html; charset=utf-8");
  216. response.end(
  217. "<!doctype html><html><head><title>Auto archived task tab</title></head><body>ready</body></html>",
  218. );
  219. });
  220. }
  221. async function listen(server: Server): Promise<string> {
  222. await new Promise<void>((resolve, reject) => {
  223. server.once("error", reject);
  224. server.listen(0, "127.0.0.1", () => {
  225. server.off("error", reject);
  226. resolve();
  227. });
  228. });
  229. const address = server.address() as AddressInfo | null;
  230. if (!address) throw new Error("fixture server 没有绑定端口");
  231. return `http://127.0.0.1:${address.port}`;
  232. }
  233. async function closeServer(server: Server | null): Promise<void> {
  234. if (!server?.listening) return;
  235. await new Promise<void>((resolve, reject) => {
  236. server.close((error) => (error ? reject(error) : resolve()));
  237. });
  238. }