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

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