conversation-session-project-missing-primary-root.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  2. import { selectNativeProjectDirectories } from "#e2e/helpers/project-sidebar";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { mkdir, rename, rm, stat } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { DEFAULT_WORKSPACE, waitForWorkspaceApp } from "#e2e/helpers/desktop-app";
  7. const PROJECT = '[data-project-name="E2E_MISSING_PRIMARY"]';
  8. const SINGLE_PROJECT = '[data-project-name="E2E_SINGLE_PRIMARY"]';
  9. const HISTORY_ID = "sess_e2e_missing_primary_history";
  10. const HISTORY_BODY = "E2E_MISSING_PRIMARY_HISTORY_BODY";
  11. const REASON = "该项目主文件夹已被删除或移动";
  12. type TestWindow = Window & {
  13. __testActions?: { setLocale(locale: "zh-CN" | "en-US"): void; setTheme(theme: string): void };
  14. __zcodeTabStoreE2E?: { getState(): { activeWorkspacePath: string | null } };
  15. __zcodeSessionStoreE2E?: {
  16. getState(): {
  17. getWorkspaceState(path: string): {
  18. activeTaskId: string | null;
  19. draftProjectId?: string | null;
  20. draftFocusVersion: number;
  21. };
  22. };
  23. };
  24. };
  25. describe("项目主目录失效", () => {
  26. it("VP-ROOT-01:移走主目录仍可展开历史但禁用新建与查看文件,恢复后重新可用", async function () {
  27. if (process.platform === "win32") {
  28. // 暂时跳过原因:Agent 进程以主目录为 cwd 常驻,Windows 不允许重命名任一进程的 cwd
  29. // 目录(rename 报 EBUSY),本例“运行中移走主目录”的前置条件在 Windows 上无法构造。
  30. // 是否调整 Agent cwd 策略待产品决策,见 docs/conversation-session-case-catalog.md VP-ROOT-01。
  31. this.skip();
  32. }
  33. this.timeout(150_000);
  34. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
  35. await browser.execute(() => (window as TestWindow).__testActions!.setLocale("zh-CN"));
  36. const root = join(DEFAULT_WORKSPACE, ".zcode-e2e", "missing-primary");
  37. const primary = join(root, "primary");
  38. const extra = join(root, "extra");
  39. const moved = join(root, "moved");
  40. const singlePrimary = join(root, "single-primary");
  41. const singleMoved = join(root, "single-moved");
  42. await Promise.all([mkdir(primary, { recursive: true }), mkdir(extra, { recursive: true })]);
  43. await mkdir(singlePrimary, { recursive: true });
  44. await openEditor("E2E_MISSING_PRIMARY");
  45. await chooseRoot(primary);
  46. await chooseRoot(extra);
  47. await $('[data-testid="virtual-project-save"]').click();
  48. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  49. await $('[data-testid="project-folder-trust-confirm"]').click();
  50. let project = $(PROJECT);
  51. await project.waitForDisplayed();
  52. let toggle = project.$('[data-testid="virtual-project-toggle"]');
  53. expect(await toggle.isEnabled()).toBe(true);
  54. expect(await project.$('[data-testid="virtual-project-files"]').isEnabled()).toBe(true);
  55. await openEditor("E2E_SINGLE_PRIMARY");
  56. await chooseRoot(singlePrimary);
  57. await $('[data-testid="virtual-project-save"]').click();
  58. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  59. await $('[data-testid="project-folder-trust-confirm"]').click();
  60. let single = $(SINGLE_PROJECT);
  61. await single.waitForDisplayed();
  62. expect(await single.$('[data-testid="virtual-project-files"]').isEnabled()).toBe(true);
  63. // 先回到本例要验证的主项目再冷启动准备历史;不让第二个对照项目的空草稿决定恢复目标。
  64. await project.$('[data-testid="virtual-project-create-task"]').click();
  65. await waitForWorkspaceApp(primary, 30_000);
  66. // PCD01 创建后会自动选择项目并准备目录;零 root 对照必须是从未进入的持久项目。
  67. // 同时在 Host 退出后写历史,两库准备完成再冷启,不能写运行中的索引假装快照已刷新。
  68. await restartIntoWorkspacePreservingProfile(primary, {
  69. afterElectronProcessExit: async () => {
  70. seedHistory(primary);
  71. const db = new DatabaseSync(
  72. join(process.env.ZCODE_E2E_HOME_DIR!, ".zcode/v2/tasks-index.sqlite"),
  73. );
  74. try {
  75. db.prepare(
  76. "INSERT INTO projects(project_id,host_id,name,position,created_at,updated_at) VALUES('e2e-empty-primary','local','E2E_EMPTY_PRIMARY',20,1,1)",
  77. ).run();
  78. } finally {
  79. db.close();
  80. }
  81. },
  82. });
  83. // WebDriver 元素绑定旧 session;完整重启后必须从新 renderer 重新取得引用。
  84. project = $(PROJECT);
  85. single = $(SINGLE_PROJECT);
  86. toggle = project.$('[data-testid="virtual-project-toggle"]');
  87. const empty = $('[data-project-name="E2E_EMPTY_PRIMARY"]');
  88. await empty.waitForDisplayed();
  89. const readActive = () =>
  90. browser.execute(
  91. () => (window as TestWindow).__zcodeTabStoreE2E!.getState().activeWorkspacePath,
  92. );
  93. if ((await toggle.getAttribute("aria-expanded")) === "true") await toggle.click();
  94. const activeBefore = await readActive();
  95. try {
  96. // 真实文件系统变更后触发窗口 focus;不注入 availability 或替换项目服务结果。
  97. await rename(primary, moved);
  98. await rename(singlePrimary, singleMoved);
  99. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  100. await browser.waitUntil(
  101. async () => (await project.getAttribute("data-primary-root-status")) === "missing",
  102. {
  103. timeout: 15_000,
  104. timeoutMsg: "主目录移走后未更新目录状态",
  105. },
  106. );
  107. await project.moveTo();
  108. const create = project.$('[data-testid="virtual-project-create-task"]');
  109. expect(await create.isEnabled()).toBe(false);
  110. const files = project.$('[data-testid="virtual-project-files"]');
  111. const singleFiles = single.$('[data-testid="virtual-project-files"]');
  112. expect(await files.isEnabled()).toBe(false);
  113. expect(await singleFiles.isEnabled()).toBe(false);
  114. expect(await toggle.getAttribute("aria-expanded")).toBe("false");
  115. expect(await toggle.isEnabled()).toBe(true);
  116. expect(await toggle.getAttribute("aria-disabled")).toBe("false");
  117. expect(await empty.$('[data-testid="virtual-project-toggle"]').isEnabled()).toBe(true);
  118. expect(await empty.$('[data-testid="virtual-project-create-task"]').isEnabled()).toBe(true);
  119. expect(await empty.$('[data-testid="virtual-project-files"]').isEnabled()).toBe(false);
  120. for (const theme of ["zai-dark", "zai-light"]) {
  121. await browser.execute(
  122. (value) => (window as TestWindow).__testActions!.setTheme(value),
  123. theme,
  124. );
  125. await leaveTooltip();
  126. await toggle.parentElement().moveTo();
  127. await expectNoReason();
  128. await browser.saveScreenshot(
  129. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `missing-primary-${theme}.png`),
  130. );
  131. await leaveTooltip();
  132. await create.parentElement().moveTo({ xOffset: -2 });
  133. await create.parentElement().moveTo({ xOffset: 2 });
  134. await waitForReason();
  135. await browser.saveScreenshot(
  136. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `missing-primary-create-${theme}.png`),
  137. );
  138. for (const [name, button] of [
  139. ["multi", files],
  140. ["single", singleFiles],
  141. ] as const) {
  142. await leaveTooltip();
  143. await button.parentElement().moveTo({ xOffset: -2 });
  144. await button.parentElement().moveTo({ xOffset: 2 });
  145. await waitForReason();
  146. await browser.saveScreenshot(
  147. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `missing-primary-files-${name}-${theme}.png`),
  148. );
  149. await browser.execute(
  150. (selector) => {
  151. document
  152. .querySelector<HTMLButtonElement>(
  153. `${selector} [data-testid="virtual-project-files"]`,
  154. )!
  155. .click();
  156. },
  157. name === "multi" ? PROJECT : SINGLE_PROJECT,
  158. );
  159. expect(await $('[data-testid="virtual-project-files-0"]').isExisting()).toBe(false);
  160. expect(await project.isDisplayed()).toBe(true);
  161. expect(await readActive()).toBe(activeBefore);
  162. }
  163. }
  164. // 目录失效阻止新建和文件入口;标题仍通过原折叠状态打开真实历史。
  165. await browser.execute((selector) => {
  166. document
  167. .querySelector<HTMLButtonElement>(
  168. `${selector} [data-testid="virtual-project-create-task"]`,
  169. )!
  170. .click();
  171. }, PROJECT);
  172. expect(await readActive()).toBe(activeBefore);
  173. await toggle.click();
  174. const history = project.$(`[data-testid="task-item-${HISTORY_ID}"]`);
  175. await history.waitForDisplayed();
  176. await toggle.click();
  177. await history.waitForDisplayed({ reverse: true });
  178. await browser.execute((selector) => {
  179. document
  180. .querySelector<HTMLElement>(`${selector} [data-testid="virtual-project-toggle"]`)!
  181. .focus();
  182. }, PROJECT);
  183. await browser.keys("Enter");
  184. await history.waitForDisplayed();
  185. expect(await toggle.getAttribute("aria-expanded")).toBe("true");
  186. await history.click();
  187. await $(`//*[normalize-space(.)="${HISTORY_BODY}" and not(*)]`).waitForDisplayed({
  188. timeout: 30_000,
  189. });
  190. expect(await create.isEnabled()).toBe(false);
  191. await expect(stat(primary)).rejects.toMatchObject({ code: "ENOENT" });
  192. await browser.saveScreenshot(
  193. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "missing-primary-history.png"),
  194. );
  195. // 旧 E2E 只验证项目行禁用;顶部按钮和原生菜单仍会请求创建,必须独立断言可见失败反馈。
  196. const beforeNewTask = await readTaskState(primary);
  197. for (const locale of ["zh-CN", "en-US"] as const) {
  198. await browser.execute(
  199. (value) => (window as TestWindow).__testActions!.setLocale(value),
  200. locale,
  201. );
  202. const reason =
  203. locale === "zh-CN" ? REASON : "This project's main folder has been deleted or moved";
  204. for (const theme of ["zai-dark", "zai-light"]) {
  205. await browser.execute(
  206. (value) => (window as TestWindow).__testActions!.setTheme(value),
  207. theme,
  208. );
  209. for (const action of ["button", "shortcut"] as const) {
  210. await waitForNewTaskToastToClose();
  211. if (action === "button") await $('[data-testid="task-new-button"]').click();
  212. else await invokeNewTaskShortcut();
  213. await browser.waitUntil(
  214. async () => (await $("#zcode-toast-host").getText()).includes(reason),
  215. {
  216. timeout: 5_000,
  217. timeoutMsg: `VP-ROOT-03 ${locale}/${theme}/${action} 未显示目录失效提示`,
  218. },
  219. );
  220. expect(await readTaskState(primary)).toEqual(beforeNewTask);
  221. await expect(stat(primary)).rejects.toMatchObject({ code: "ENOENT" });
  222. await browser.saveScreenshot(
  223. join(
  224. process.env.ZCODE_E2E_ARTIFACT_DIR!,
  225. `missing-primary-new-task-${locale}-${theme}-${action}.png`,
  226. ),
  227. );
  228. }
  229. }
  230. }
  231. await waitForNewTaskToastToClose();
  232. await browser.execute(() => (window as TestWindow).__testActions!.setLocale("zh-CN"));
  233. await project.$('[data-testid="virtual-project-row"]').click({ button: "right" });
  234. const contextCreate = $('[data-testid="virtual-project-context-create-task"]');
  235. await contextCreate.waitForDisplayed();
  236. expect(await contextCreate.getAttribute("aria-disabled")).toBe("true");
  237. for (const index of [0, 1]) {
  238. expect(
  239. await $(`[data-testid="virtual-project-context-files-${index}"]`).getAttribute(
  240. "aria-disabled",
  241. ),
  242. ).toBe("true");
  243. }
  244. await browser.keys("Escape");
  245. await single.$('[data-testid="virtual-project-row"]').click({ button: "right" });
  246. await $('[data-testid="virtual-project-context-files-0"]').waitForDisplayed();
  247. expect(
  248. await $('[data-testid="virtual-project-context-files-0"]').getAttribute("aria-disabled"),
  249. ).toBe("true");
  250. await browser.keys("Escape");
  251. await project.moveTo();
  252. await project.$('[data-testid="virtual-project-menu"]').click();
  253. await $('[data-testid="virtual-project-edit"]').click();
  254. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  255. await browser.keys("Escape");
  256. await $('[data-testid="virtual-project-name"]').waitForExist({ reverse: true });
  257. await browser.refresh();
  258. await $(PROJECT).waitForDisplayed({ timeout: 45_000 });
  259. expect(await $(PROJECT).$('[data-testid="virtual-project-toggle"]').isEnabled()).toBe(true);
  260. expect(await $(PROJECT).getAttribute("data-primary-root-status")).toBe("missing");
  261. expect(await $(PROJECT).$('[data-testid="virtual-project-files"]').isEnabled()).toBe(false);
  262. await rename(moved, primary);
  263. await rename(singleMoved, singlePrimary);
  264. await rm(extra, { recursive: true });
  265. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  266. await browser.waitUntil(
  267. async () => $(PROJECT).$('[data-testid="virtual-project-create-task"]').isEnabled(),
  268. {
  269. timeout: 15_000,
  270. timeoutMsg: "主目录恢复后项目仍被禁用",
  271. },
  272. );
  273. await $(PROJECT).moveTo();
  274. const recoveredCreate = $(PROJECT).$('[data-testid="virtual-project-create-task"]');
  275. expect(await recoveredCreate.isEnabled()).toBe(true);
  276. expect(await $(PROJECT).$('[data-testid="virtual-project-files"]').isEnabled()).toBe(true);
  277. expect(await $(SINGLE_PROJECT).$('[data-testid="virtual-project-files"]').isEnabled()).toBe(
  278. true,
  279. );
  280. await recoveredCreate.click();
  281. await waitForWorkspaceApp(primary, 30_000);
  282. for (const action of ["button", "shortcut"] as const) {
  283. const before = await readTaskState(primary);
  284. if (action === "button") await $('[data-testid="task-new-button"]').click();
  285. else await invokeNewTaskShortcut();
  286. await browser.waitUntil(async () => (await readTaskState(primary)).focus > before.focus);
  287. expect((await readTaskState(primary)).task).toBeNull();
  288. expect((await readTaskState(primary)).project).toBe(beforeNewTask.project);
  289. expect(await readActive()).toBe(primary);
  290. }
  291. await rename(primary, moved);
  292. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  293. await browser.waitUntil(
  294. async () => (await $(PROJECT).getAttribute("data-primary-root-status")) === "missing",
  295. );
  296. expect(await toggle.isEnabled()).toBe(true);
  297. // 共享侧栏的窄布局检查,不把设备尺寸模拟计为实际手机 shared-host 链路覆盖。
  298. await emulateViewport(390);
  299. await browser.waitUntil(() => browser.execute(() => innerWidth === 390));
  300. // 窄布局会自动收起侧栏;通过原切换入口展开后,再验证标题和提示布局。
  301. await browser.waitUntil(() =>
  302. browser.execute(() =>
  303. document
  304. .querySelector('[data-workspace-sidebar-panel="true"]')!
  305. .classList.contains("pointer-events-none"),
  306. ),
  307. );
  308. await browser.execute(() =>
  309. document.querySelector<HTMLButtonElement>('button[aria-label="切换侧边栏"]')!.click(),
  310. );
  311. await browser.waitUntil(() =>
  312. browser.execute(() => {
  313. const panel = document.querySelector('[data-workspace-sidebar-panel="true"]')!;
  314. return (
  315. panel.getBoundingClientRect().width > 30 &&
  316. panel.getAnimations().every((animation) => animation.playState !== "running")
  317. );
  318. }),
  319. );
  320. for (const theme of ["zai-dark", "zai-light"]) {
  321. await browser.execute(
  322. (value) => (window as TestWindow).__testActions!.setTheme(value),
  323. theme,
  324. );
  325. for (const testId of [
  326. "virtual-project-toggle",
  327. "virtual-project-create-task",
  328. "virtual-project-files",
  329. ]) {
  330. await browser.keys("Escape");
  331. await browser.waitUntil(() =>
  332. browser.execute(() => !document.querySelector('[data-slot="tooltip-content"]')),
  333. );
  334. // CDP 尺寸模拟后 WebDriver 的指针坐标仍受原生窗口缩放影响;直接发送 CSS 视口坐标。
  335. const point = await browser.execute(
  336. ({ selector, testId }) => {
  337. const rect = document
  338. .querySelector(`${selector} [data-testid="${testId}"]`)!
  339. .parentElement!.getBoundingClientRect();
  340. return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
  341. },
  342. { selector: PROJECT, testId },
  343. );
  344. await browser.electron.execute(async (electron, point) => {
  345. const window = electron.BrowserWindow.getAllWindows().find((item) => item.isVisible())!;
  346. for (const offset of [-2, 0])
  347. await window.webContents.debugger.sendCommand("Input.dispatchMouseEvent", {
  348. type: "mouseMoved",
  349. x: point.x + offset,
  350. y: point.y,
  351. buttons: 0,
  352. pointerType: "mouse",
  353. });
  354. }, point);
  355. if (testId === "virtual-project-toggle") {
  356. await expectNoReason();
  357. continue;
  358. }
  359. await waitForReason();
  360. const bounds = await browser.execute((selector) => {
  361. const row = document
  362. .querySelector(`${selector} [data-testid="virtual-project-row"]`)!
  363. .getBoundingClientRect();
  364. const hint = document
  365. .querySelector('[data-slot="tooltip-content"]:not([data-state="closed"])')!
  366. .getBoundingClientRect();
  367. return { rowRight: row.right, hintLeft: hint.left, hintRight: hint.right };
  368. }, PROJECT);
  369. expect(bounds.rowRight).toBeLessThanOrEqual(390);
  370. expect(bounds.hintLeft).toBeGreaterThanOrEqual(0);
  371. expect(bounds.hintRight).toBeLessThanOrEqual(390);
  372. await browser.saveScreenshot(
  373. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `missing-primary-390-${testId}-${theme}.png`),
  374. );
  375. }
  376. }
  377. } finally {
  378. // 不删除已成为活动 cwd 的主目录;runner 回收整个隔离 HOME。
  379. await emulateViewport();
  380. await browser.execute(() => (window as TestWindow).__testActions!.setTheme("system"));
  381. }
  382. });
  383. });
  384. async function readTaskState(path: string) {
  385. return browser.execute((path) => {
  386. const state = (window as TestWindow).__zcodeSessionStoreE2E!.getState().getWorkspaceState(path);
  387. return {
  388. task: state.activeTaskId,
  389. project: state.draftProjectId,
  390. focus: state.draftFocusVersion,
  391. };
  392. }, path);
  393. }
  394. async function waitForNewTaskToastToClose() {
  395. await browser.waitUntil(
  396. () => browser.execute(() => !document.getElementById("zcode-toast-host")?.textContent?.trim()),
  397. { timeout: 5_000 },
  398. );
  399. }
  400. async function invokeNewTaskShortcut() {
  401. const url = await browser.getUrl();
  402. await browser.electron.execute((electron, url) => {
  403. const window = electron.BrowserWindow.getAllWindows().find(
  404. (candidate) => candidate.webContents.getURL() === url,
  405. );
  406. if (!window) throw new Error("Missing new-task shortcut window");
  407. window.focus();
  408. const item = electron.Menu.getApplicationMenu()
  409. ?.items.flatMap((menu) => menu.submenu?.items ?? [])
  410. .find((entry) => entry.accelerator === "CmdOrCtrl+N");
  411. if (!item) throw new Error("Missing CmdOrCtrl+N binding");
  412. // WebDriver DOM 按键不经过系统菜单;验证真实 accelerator 绑定并执行相同命令。
  413. item.click(undefined as never, window, undefined as never);
  414. }, url);
  415. }
  416. async function emulateViewport(width?: number) {
  417. await browser.electron.execute(async (electron, width) => {
  418. const window = electron.BrowserWindow.getAllWindows().find(
  419. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  420. );
  421. if (!window) throw new Error("No visible renderer");
  422. if (!window.webContents.debugger.isAttached()) window.webContents.debugger.attach("1.3");
  423. await window.webContents.debugger.sendCommand(
  424. width ? "Emulation.setDeviceMetricsOverride" : "Emulation.clearDeviceMetricsOverride",
  425. width ? { width, height: 844, deviceScaleFactor: 1, mobile: false } : {},
  426. );
  427. }, width);
  428. }
  429. async function openEditor(name: string) {
  430. await $('[data-testid="project-section"]').moveTo();
  431. await $('[data-testid="virtual-project-add"]').click();
  432. await $('[data-testid="virtual-project-name"]').setValue(name);
  433. }
  434. async function chooseRoot(path: string) {
  435. await selectNativeProjectDirectories([path]);
  436. }
  437. async function expectNoReason() {
  438. // 负向 hover 断言需停留超过 Tooltip 延迟,防止在提示尚未打开时误判通过。
  439. await browser.pause(1_000);
  440. const hints = await browser.execute(() =>
  441. [...document.querySelectorAll('[data-slot="tooltip-content"]:not([data-state="closed"])')].map(
  442. (element) => element.textContent,
  443. ),
  444. );
  445. expect(hints.some((text) => text?.includes(REASON))).toBe(false);
  446. }
  447. async function waitForReason() {
  448. // 同文案提示切换时旧节点会保留到退出动画结束;只验收已展开、动画完成的可见提示。
  449. // Radix 的 role=tooltip 是裁剪的读屏副本,用户可见文字在 tooltip-content。
  450. await browser
  451. .waitUntil(() =>
  452. browser.execute((reason) => {
  453. const hint = document.querySelector<HTMLElement>(
  454. '[data-slot="tooltip-content"]:not([data-state="closed"])',
  455. );
  456. return Boolean(
  457. hint?.textContent?.includes(reason) &&
  458. Number(getComputedStyle(hint).opacity) === 1 &&
  459. hint.getAnimations().every((animation) => animation.playState !== "running"),
  460. );
  461. }, REASON),
  462. )
  463. .catch(async (error) => {
  464. const state = await browser.execute(
  465. (selector) => ({
  466. hints: [...document.querySelectorAll('[data-slot="tooltip-content"]')].map((el) => ({
  467. html: el.outerHTML,
  468. opacity: getComputedStyle(el).opacity,
  469. })),
  470. hovered: [...document.querySelectorAll(":hover")]
  471. .slice(-6)
  472. .map((el) => el.outerHTML.slice(0, 500)),
  473. trigger: document.querySelector(`${selector} [data-testid="virtual-project-create-task"]`)
  474. ?.parentElement?.outerHTML,
  475. }),
  476. PROJECT,
  477. );
  478. await browser.saveScreenshot(
  479. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "tooltip-failure.png"),
  480. );
  481. throw new Error(JSON.stringify(state), { cause: error });
  482. });
  483. }
  484. async function leaveTooltip() {
  485. // 关闭上一提示并移出,再独立验证下个入口的 hover,避免同文案旧提示造成假阳性。
  486. if (await $('[data-slot="tooltip-content"]').isExisting()) await browser.keys("Escape");
  487. await $(
  488. '[data-project-name="E2E_EMPTY_PRIMARY"] [data-testid="virtual-project-toggle"]',
  489. ).moveTo();
  490. await browser.waitUntil(async () => !(await $('[data-slot="tooltip-content"]').isExisting()));
  491. }
  492. function seedHistory(workspacePath: string) {
  493. // 只写 runner 的隔离 HOME;复用真实 Host/CLI 两库数据合同,不 mock 消息或目录状态。
  494. const home = process.env.ZCODE_E2E_HOME_DIR;
  495. if (!home || !DEFAULT_WORKSPACE.startsWith(home)) throw new Error("isolated HOME required");
  496. const app = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"));
  497. const cli = new DatabaseSync(join(home, ".zcode/cli/db/db.sqlite"));
  498. try {
  499. const projectId = app
  500. .prepare("SELECT project_id FROM project_roots WHERE root_path=? LIMIT 1")
  501. .get(workspacePath)?.project_id;
  502. if (typeof projectId !== "string") throw new Error("fixture project missing");
  503. const now = Date.now();
  504. cli
  505. .prepare(
  506. "INSERT INTO session(id,project_id,slug,directory,title,version,time_created,time_updated,title_source,last_outcome) VALUES(?,?,?,?,?,'1',?,?,'custom','completed')",
  507. )
  508. .run(
  509. HISTORY_ID,
  510. "e2e-primary-history",
  511. HISTORY_ID,
  512. workspacePath,
  513. "E2E_PRIMARY_HISTORY",
  514. now,
  515. now,
  516. );
  517. cli
  518. .prepare(
  519. "INSERT INTO message(id,session_id,time_created,time_updated,data,sequence) VALUES(?,?,?,?,?,0)",
  520. )
  521. .run(
  522. `${HISTORY_ID}_message`,
  523. HISTORY_ID,
  524. now,
  525. now,
  526. JSON.stringify({ role: "user", time: { created: now }, agent: "build" }),
  527. );
  528. cli
  529. .prepare(
  530. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data,sequence) VALUES(?,?,?,?,?,?,0)",
  531. )
  532. .run(
  533. `${HISTORY_ID}_part`,
  534. `${HISTORY_ID}_message`,
  535. HISTORY_ID,
  536. now,
  537. now,
  538. JSON.stringify({ type: "text", text: HISTORY_BODY }),
  539. );
  540. app
  541. .prepare(
  542. "INSERT INTO tasks(workspace_key,workspace_path,task_id,title,provider,mode,created_at,updated_at,host_id,root_path,project_id,cli_title,cli_title_source,cli_created_at,cli_updated_at,cli_last_outcome,cli_deleted,meta_json) VALUES(?,?,?,?,'glm','default',?,?,'local',?,?,?,'custom',?,?,'completed',0,?)",
  543. )
  544. .run(
  545. workspacePath,
  546. workspacePath,
  547. HISTORY_ID,
  548. "E2E_PRIMARY_HISTORY",
  549. now,
  550. now,
  551. workspacePath,
  552. projectId,
  553. "E2E_PRIMARY_HISTORY",
  554. now,
  555. now,
  556. JSON.stringify({
  557. taskId: HISTORY_ID,
  558. traceId: HISTORY_ID,
  559. title: "E2E_PRIMARY_HISTORY",
  560. workspacePath,
  561. createdAt: now,
  562. updatedAt: now,
  563. mode: "build",
  564. }),
  565. );
  566. } finally {
  567. cli.close();
  568. app.close();
  569. }
  570. }