command-center-history-search.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { once } from "node:events";
  5. import { createServer } from "node:http";
  6. import { chromium } from "playwright-core";
  7. import { DEFAULT_WORKSPACE, waitForWorkspaceApp } from "#e2e/helpers/desktop-app";
  8. import { isIsolatedE2EHomeDir } from "#e2e/helpers/e2e-runtime-paths";
  9. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  10. import { seedProviderReadinessHistoryFixture } from "#e2e/helpers/provider-readiness-history-fixture";
  11. import { openMobilePairingPage } from "#e2e/helpers/mobile-pairing";
  12. import { WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS } from "#e2e/helpers/web-remote-control-session-events-fixture";
  13. const marker = "E2E_HISTORY_TITLE";
  14. const bodyMarker = "E2E_HISTORY_BODY";
  15. const inputSelector = '[role="dialog"] [cmdk-input]';
  16. const rowSelector = '[role="dialog"] [cmdk-item][data-value^="task-result:"]';
  17. const cases = ["active", "pinned", "archived", "unclassified", "deleted", "cli-deleted", "foreign"];
  18. const visibleCases = cases.slice(0, 4);
  19. let closedWorkspace: string;
  20. let home: string;
  21. describe("Command Center Host 历史搜索", () => {
  22. afterEach(async () => {
  23. const snapshot = await browser.execute(() => ({
  24. text: document.body.innerText.slice(0, 12000),
  25. rows: Array.from(document.querySelectorAll('[role="dialog"] [cmdk-item]')).map((row) => ({
  26. text: row.textContent,
  27. value: row.getAttribute("data-value"),
  28. })),
  29. }));
  30. await writeFile(
  31. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "history-search-state.json"),
  32. JSON.stringify(snapshot, null, 2),
  33. );
  34. });
  35. before(async () => {
  36. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
  37. home = process.env.ZCODE_E2E_HOME_DIR ?? "";
  38. // 旧 basename 守卫误拒 runner 默认的 .e2e-home;复用统一守卫,仍禁止写普通 HOME。
  39. if (!isIsolatedE2EHomeDir(home)) throw new Error("需要隔离 E2E HOME");
  40. closedWorkspace = join(home, "ClosedHistoryWorkspace");
  41. await mkdir(closedWorkspace, { recursive: true });
  42. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  43. afterElectronProcessExit: async () => {
  44. for (const name of cases) {
  45. await seedProviderReadinessHistoryFixture({
  46. cliEntryPoint: resolve("../../apps/zcode-cli/packages/cli/dist/zcode.cjs"),
  47. e2eHomeDir: home,
  48. workspacePath: closedWorkspace,
  49. history: {
  50. sessionId: `session_e2e_history_${name}`,
  51. title: `${marker}_${name}`,
  52. userText: `${bodyMarker}_${name}`,
  53. assistantText: `Persisted history ${name}`,
  54. modelId: "missing-model",
  55. runtimeProviderId: "missing-provider",
  56. taskProviderId: "glm",
  57. assistantInputTokens: 0,
  58. assistantOutputTokens: 0,
  59. },
  60. });
  61. }
  62. // node:sqlite 只提供同步接口;夹具在 Host 退出后写入,避免与迁移/索引写入竞争。
  63. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"));
  64. try {
  65. const stamp = Date.now() - 36 * 24 * 60 * 60 * 1000;
  66. db.prepare(`UPDATE tasks SET host_id='local', root_path=workspace_path,
  67. project_id=NULL, cli_title=title, cli_title_source='custom', cli_created_at=?,
  68. cli_updated_at=?, created_at=?, updated_at=?, cli_deleted=0, handoff_pending=8
  69. WHERE task_id LIKE 'session_e2e_history_%'`).run(stamp, stamp, stamp, stamp);
  70. db.exec(`UPDATE tasks SET pinned=1 WHERE task_id='session_e2e_history_pinned';
  71. UPDATE tasks SET archived=1 WHERE task_id='session_e2e_history_archived';
  72. UPDATE tasks SET deleted=1 WHERE task_id='session_e2e_history_deleted';
  73. UPDATE tasks SET cli_deleted=1 WHERE task_id='session_e2e_history_cli-deleted';
  74. UPDATE tasks SET host_id='server:other-device' WHERE task_id='session_e2e_history_foreign'`);
  75. db.prepare(`INSERT INTO projects(project_id,host_id,name,position,created_at,updated_at)
  76. VALUES('e2e-history-project','local','E2E_HISTORY_PROJECT',100,?,?)`).run(stamp, stamp);
  77. db.prepare(
  78. `INSERT INTO project_roots(project_id,root_path,position) VALUES('e2e-history-project',?,0)`,
  79. ).run(closedWorkspace);
  80. db.exec(`UPDATE tasks SET project_id='e2e-history-project' WHERE task_id IN
  81. ('session_e2e_history_active','session_e2e_history_pinned','session_e2e_history_archived')`);
  82. } finally {
  83. db.close();
  84. }
  85. const settingsPath = join(home, ".zcode/v2/setting.json");
  86. const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  87. await writeFile(
  88. settingsPath,
  89. JSON.stringify({ ...settings, taskAutoArchiveEnabled: false }),
  90. );
  91. },
  92. });
  93. });
  94. it("CC-HISTORY-01:未打开目录的一个月前标题/正文、置顶、归档及 Host 隔离", async () => {
  95. const tabs = await browser.execute(() => {
  96. const store = (
  97. window as typeof window & {
  98. __zcodeTabStoreE2E?: { getState(): { tabs: Array<{ workspacePath?: string }> } };
  99. }
  100. ).__zcodeTabStoreE2E;
  101. if (!store) throw new Error("缺少 tab store 测试入口");
  102. return store.getState().tabs.map((tab) => tab.workspacePath);
  103. });
  104. expect(tabs).not.toContain(closedWorkspace);
  105. await openSearch();
  106. await searchAndExpect(marker, visibleCases);
  107. for (const name of visibleCases) await searchAndExpect(`${bodyMarker}_${name}`, [name]);
  108. await browser.saveScreenshot(
  109. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "history-cold-search.png"),
  110. );
  111. await browser.keys("Escape");
  112. });
  113. it("CC-HISTORY-02:点击未打开目录的归档结果并再次搜索", async () => {
  114. await openSearch();
  115. await searchAndExpect(`${marker}_archived`, ["archived"]);
  116. await $(rowSelector).click();
  117. await browser.waitUntil(
  118. () =>
  119. browser.execute((text) => document.body.innerText.includes(text), `${bodyMarker}_archived`),
  120. { timeout: 45_000, timeoutMsg: "应打开归档任务的真实持久化正文" },
  121. );
  122. await openSearch();
  123. await searchAndExpect(marker, visibleCases);
  124. await browser.keys("Escape");
  125. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"), { readOnly: true });
  126. try {
  127. expect(
  128. db.prepare("SELECT archived FROM tasks WHERE task_id='session_e2e_history_archived'").get(),
  129. ).toEqual({ archived: 1 });
  130. } finally {
  131. db.close();
  132. }
  133. });
  134. it("CC-HISTORY-03:手机真实 shared-host 搜索旧任务标题和正文", async function () {
  135. this.timeout(120_000);
  136. let receivePair!: (url: string) => void;
  137. const pairing = new Promise<string>((resolvePair) => {
  138. receivePair = resolvePair;
  139. });
  140. // 配对链接只经过内存,不让 WDIO 命令日志保存配对密码。
  141. const receiver = createServer(async (request, response) => {
  142. response.setHeader("Access-Control-Allow-Origin", "*");
  143. if (request.method !== "OPTIONS") {
  144. let value = "";
  145. for await (const chunk of request) value += String(chunk);
  146. receivePair(value);
  147. }
  148. response.end();
  149. });
  150. receiver.listen(0, "127.0.0.1");
  151. await once(receiver, "listening");
  152. const address = receiver.address();
  153. if (!address || typeof address === "string") throw new Error("pair receiver failed");
  154. const mobile = await chromium.launch({
  155. ...(process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE
  156. ? { executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE }
  157. : { channel: "chrome" }),
  158. headless: true,
  159. });
  160. try {
  161. await browser.execute((port) => {
  162. const target = window as typeof window & { __historyRestoreClipboard?: () => void };
  163. const original = navigator.clipboard.writeText.bind(navigator.clipboard);
  164. target.__historyRestoreClipboard = () => {
  165. navigator.clipboard.writeText = original;
  166. };
  167. navigator.clipboard.writeText = async (text) => {
  168. await fetch(`http://127.0.0.1:${port}`, { method: "POST", body: text });
  169. };
  170. }, address.port);
  171. await $(
  172. 'button[aria-label="移动端远程控制"], button[aria-label="Mobile remote control"]',
  173. ).click();
  174. await browser.waitUntil(
  175. () =>
  176. browser.execute(() => {
  177. const button = Array.from(
  178. document.querySelectorAll<HTMLButtonElement>(
  179. '[data-testid="web-remote-control-dialog-scroll"] button',
  180. ),
  181. ).find(
  182. (node) => /^(复制链接|Copy link)$/.test(node.innerText.trim()) && !node.disabled,
  183. );
  184. button?.click();
  185. return Boolean(button);
  186. }),
  187. { timeout: 45_000 },
  188. );
  189. const context = await mobile.newContext({
  190. viewport: { width: 390, height: 844 },
  191. isMobile: true,
  192. hasTouch: true,
  193. locale: "zh-CN",
  194. });
  195. await context.addInitScript((credentials) => {
  196. for (const [key, value] of Object.entries(credentials)) localStorage.setItem(key, value);
  197. }, WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS);
  198. const page = await context.newPage();
  199. await openMobilePairingPage(page, await pairing, {
  200. artifactDir: process.env.ZCODE_E2E_ARTIFACT_DIR!,
  201. caseMarker: "CC-HISTORY-03",
  202. phase: "history-search",
  203. readySelector: '[data-testid="sidebar-search-open"]',
  204. });
  205. await page.getByTestId("sidebar-search-open").tap();
  206. await page.getByRole("tab", { name: /^(任务|Tasks)$/ }).click();
  207. for (const query of [marker, bodyMarker]) {
  208. await page.locator(inputSelector).fill(query);
  209. await page.waitForFunction(
  210. ({ rowSelector, marker, visibleCases }) => {
  211. const rows = Array.from(document.querySelectorAll(rowSelector)).map(
  212. (row) => row.textContent ?? "",
  213. );
  214. return (
  215. rows.length === visibleCases.length &&
  216. visibleCases.every((name) => rows.some((text) => text.includes(`${marker}_${name}`)))
  217. );
  218. },
  219. { rowSelector, marker, visibleCases },
  220. );
  221. }
  222. await page.screenshot({
  223. path: join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "history-mobile-search.png"),
  224. });
  225. } finally {
  226. await mobile.close();
  227. receiver.close();
  228. await browser.execute(() => {
  229. const target = window as typeof window & { __historyRestoreClipboard?: () => void };
  230. target.__historyRestoreClipboard?.();
  231. delete target.__historyRestoreClipboard;
  232. });
  233. await browser.keys("Escape");
  234. }
  235. });
  236. });
  237. async function openSearch() {
  238. await $('[data-testid="sidebar-search-open"]').click();
  239. await $(inputSelector).waitForDisplayed();
  240. await $('[role="dialog"]')
  241. .$('.//button[@role="tab" and (normalize-space(.)="任务" or normalize-space(.)="Tasks")]')
  242. .click();
  243. }
  244. async function searchAndExpect(query: string, names: string[]) {
  245. await $(inputSelector).setValue(query);
  246. await browser.waitUntil(
  247. async () => {
  248. const texts = await $$(rowSelector).map((row) => row.getText());
  249. return (
  250. texts.length === names.length &&
  251. names.every((name) => texts.some((text) => text.includes(`${marker}_${name}`)))
  252. );
  253. },
  254. { timeout: 10_000, timeoutMsg: `历史搜索 ${query} 应返回 ${names.join(",")}` },
  255. );
  256. }