conversation-session-virtual-project.test.ts 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. // 统一 runner 与旧手工入口均使用隔离 HOME;不能因 runId 前缀不同拒绝安全夹具。
  2. import {
  3. installHandoffRpcProbe,
  4. callHandoffHost,
  5. removeRemoteProjectEntryForRow,
  6. restoreHandoffProbes,
  7. } from "#e2e/helpers/remote-project-handoff-probe";
  8. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  9. import { setRendererViewport, clearRendererViewport } from "#e2e/helpers/renderer-viewport";
  10. import type { VirtualProject } from "@zcode/services";
  11. import { selectNativeProjectDirectories } from "#e2e/helpers/project-sidebar";
  12. import { openScopeProjectSubmenu } from "#e2e/helpers/settings-scope-menu";
  13. import { spawn } from "node:child_process";
  14. import { once } from "node:events";
  15. import { join, basename, resolve } from "node:path";
  16. import { DatabaseSync } from "node:sqlite";
  17. import { readFile, writeFile, mkdir } from "node:fs/promises";
  18. import { ServiceChannels } from "@zcode/shared";
  19. import {
  20. TID_TASK_SETTINGS_BUTTON,
  21. TID_TASK_ITEM,
  22. TID_TASK_ARCHIVE,
  23. TID_V4_COMPOSER_INPUT,
  24. TID_V4_COMPOSER_SEND,
  25. TID_SETTINGS_SECTION_NAV,
  26. TID_SETTINGS_BACK_BUTTON,
  27. TID_AUTOMATIONS_OPEN,
  28. TID_AUTOMATION_CREATE_MENU,
  29. TID_AUTOMATION_CREATE_MANUALLY,
  30. TID_AUTOMATION_FORM_TITLE,
  31. TID_AUTOMATION_FORM_PROMPT,
  32. TID_AUTOMATION_SCHEDULE_ADD,
  33. TID_AUTOMATION_FREQUENCY_OPTION,
  34. TID_AUTOMATION_FORM_SUBMIT,
  35. TID_AUTOMATIONS_LIST,
  36. testId,
  37. } from "@zcode/shared/test-ids";
  38. import {
  39. clearAppData,
  40. setInputValueByTestIdDom,
  41. clickTestIdByDom,
  42. waitForWorkspaceApp,
  43. DEFAULT_WORKSPACE,
  44. } from "#e2e/helpers/desktop-app";
  45. import { waitForUpstreamNetworkCapture } from "#e2e/helpers/upstream-capture";
  46. import { loginWithApiKey, prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  47. describe("虚拟项目", () => {
  48. before(async () => {
  49. await prepareV4ConversationE2E({ skipProvider: true });
  50. // 本文件保留中文文案断言,显式设置语言,避免跟随测试机系统语言产生假失败。
  51. await browser.execute(() => {
  52. const actions = (window as Window & { __testActions?: { setLocale(locale: "zh-CN"): void } })
  53. .__testActions;
  54. if (!actions) throw new Error("missing E2E locale bridge");
  55. actions.setLocale("zh-CN");
  56. });
  57. });
  58. it("VP19/20:直接创建表单、源文件夹布局、旧分区折叠与 hover 入口", async function () {
  59. this.timeout(60_000);
  60. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  61. const projects = $('[data-testid="project-section"]');
  62. const tasks = $('[data-testid="conversation-section"]');
  63. await projects.waitForDisplayed();
  64. expect(await $('button[aria-label="时间线"]').isExisting()).toBe(false);
  65. expect(await $('[data-testid="virtual-project-menu"]').isExisting()).toBe(true);
  66. expect(await $("aside").$("button=添加连接").isExisting()).toBe(false);
  67. for (const section of [projects, tasks]) {
  68. const toggle = section.$('button[data-slot="collapsible-trigger"]');
  69. for (const expanded of ["false", "true"]) {
  70. // 上方折叠动画会移动下方分区;等浏览器动画完成再做一次原生点击,不重复补点。
  71. await browser.execute(async () => {
  72. await Promise.all(
  73. (document.querySelector("aside")?.getAnimations({ subtree: true }) ?? [])
  74. .filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity)
  75. .map((animation) => animation.finished.catch(() => {})),
  76. );
  77. });
  78. await toggle.click();
  79. await browser.waitUntil(
  80. async () => (await toggle.getAttribute("aria-expanded")) === expanded,
  81. );
  82. }
  83. }
  84. await projects.moveTo();
  85. expect(await $('[data-testid="virtual-project-add"] svg.lucide-plus').isExisting()).toBe(true);
  86. expect(
  87. await $(
  88. '[data-testid="virtual-project-new-task"] svg.lucide-message-circle-plus',
  89. ).isExisting(),
  90. ).toBe(true);
  91. await $('[data-testid="virtual-project-add"]').click();
  92. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  93. expect(await $('[data-testid="virtual-project-device"]').getText()).toContain("此电脑");
  94. expect(await $('[data-testid="virtual-project-type-next"]').isExisting()).toBe(false);
  95. await captureProjectDialogLayouts("form");
  96. expect(await $('[data-testid="virtual-project-root"]').isExisting()).toBe(false);
  97. expect(await $('[data-testid="virtual-project-browse"]').getText()).toMatch(
  98. /可读取和编辑|can read and edit/,
  99. );
  100. await browser.saveScreenshot(
  101. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "virtual-project-editor.png"),
  102. );
  103. await captureProjectDialogLayouts("editor");
  104. await browser.keys("Escape");
  105. await $('[role="dialog"]').waitForExist({ reverse: true });
  106. // aside 保留内部宽度,即使容器已收起;必须读 Shell 面板实际宽度,不能无条件 toggle。
  107. const sidebarExpanded = () =>
  108. browser.execute(() => {
  109. const shell = document.querySelector('[data-workspace-shell="true"]');
  110. return shell
  111. ? Number.parseFloat(
  112. getComputedStyle(shell).getPropertyValue("--workspace-sidebar-panel-width"),
  113. ) > 200
  114. : false;
  115. });
  116. if (!(await sidebarExpanded())) {
  117. const sidebarToggle = $(
  118. 'button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]',
  119. );
  120. await sidebarToggle.waitForClickable();
  121. await sidebarToggle.click();
  122. }
  123. await browser.waitUntil(sidebarExpanded);
  124. await tasks.$('button[data-slot="collapsible-trigger"]').click();
  125. await browser.refresh();
  126. await tasks.waitForDisplayed();
  127. expect(
  128. await tasks.$('button[data-slot="collapsible-trigger"]').getAttribute("aria-expanded"),
  129. ).toBe("false");
  130. await tasks.$('button[data-slot="collapsible-trigger"]').click();
  131. });
  132. it("VP20:项目图标、hover 三入口和右键操作保持一致", async function () {
  133. this.timeout(90_000);
  134. const root = join(DEFAULT_WORKSPACE, ".zcode-e2e", "project-row-actions");
  135. const paths = [join(root, "one"), join(root, "two")] as const;
  136. await Promise.all(
  137. paths.map(async (path, index) => {
  138. await mkdir(path, { recursive: true });
  139. await writeFile(join(path, `E2E_PROJECT_ROW_${index}.txt`), `root ${index}`);
  140. }),
  141. );
  142. await openLocalProjectEditor();
  143. await $('[data-testid="virtual-project-name"]').setValue("E2E_PROJECT_ROW");
  144. for (const path of paths) await chooseProjectRoot(path);
  145. await $('[data-testid="virtual-project-save"]').click();
  146. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  147. await $('[data-testid="project-folder-trust-confirm"]').click();
  148. const project = $('[data-project-name="E2E_PROJECT_ROW"]');
  149. await project.waitForDisplayed();
  150. const row = project.$('[data-testid="virtual-project-row"]');
  151. const toggle = row.$('[data-testid="virtual-project-toggle"]');
  152. expect(await row.$("svg.lucide-chevron-right, svg.lucide-chevron-down").isExisting()).toBe(
  153. false,
  154. );
  155. // 多 root 已使用叠层图标,开合断言仍分别验证展开和折叠。
  156. expect(await toggle.$("svg.lucide-folders-open").isExisting()).toBe(true);
  157. await toggle.click();
  158. expect(await toggle.$("svg.lucide-folders").isExisting()).toBe(true);
  159. await browser.execute(() => (document.activeElement as HTMLElement)?.blur());
  160. await $('[data-testid="task-new-button"]').moveTo();
  161. const opacity = () =>
  162. browser.execute(
  163. () =>
  164. getComputedStyle(
  165. document.querySelector(
  166. '[data-project-name="E2E_PROJECT_ROW"] [data-testid="virtual-project-actions"]',
  167. )!,
  168. ).opacity,
  169. );
  170. await browser.waitUntil(async () => (await opacity()) === "0");
  171. await row.moveTo();
  172. await browser.waitUntil(async () => (await opacity()) === "1");
  173. for (const icon of ["ellipsis", "list-tree", "message-circle-plus"])
  174. expect(await row.$(`svg.lucide-${icon}`).isExisting()).toBe(true);
  175. await browser.saveScreenshot(
  176. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP20-project-row-hover.png"),
  177. );
  178. await row.$('[data-testid="virtual-project-menu"]').click();
  179. await $('[data-testid="virtual-project-edit"]').click();
  180. await $('[data-testid="virtual-project-save"]').click();
  181. await $('[role="dialog"]').waitForExist({ reverse: true });
  182. expect(await toggle.getAttribute("aria-expanded")).toBe("false");
  183. await row.moveTo();
  184. await row.$('[data-testid="virtual-project-files"]').click();
  185. await $('[data-testid="virtual-project-files-1"]').click();
  186. const panel = $('[data-testid="workspace-file-tree-panel"]');
  187. await panel.waitForDisplayed();
  188. await browser.waitUntil(async () => (await panel.getText()).includes("E2E_PROJECT_ROW_1.txt"));
  189. expect(await panel.getText()).not.toContain("E2E_PROJECT_ROW_0.txt");
  190. // 项目文件现已在右侧文件标签展示,关闭当前标签回到原草稿。
  191. await $('[data-side-pane-tab-id][data-state="active"] button[aria-label]').click();
  192. await panel.waitForExist({ reverse: true });
  193. await row.click({ button: "right" });
  194. expect(await $('[data-testid="virtual-project-edit"]').isExisting()).toBe(true);
  195. expect(await $('[data-testid="virtual-project-context-create-task"]').isExisting()).toBe(true);
  196. await $('[data-testid="virtual-project-context-files-0"]').click();
  197. await panel.waitForDisplayed();
  198. await browser.waitUntil(async () => (await panel.getText()).includes("E2E_PROJECT_ROW_0.txt"));
  199. // 项目文件现已在右侧文件标签展示,关闭当前标签回到原草稿。
  200. await $('[data-side-pane-tab-id][data-state="active"] button[aria-label]').click();
  201. await row.moveTo();
  202. await row.$('[data-testid="virtual-project-create-task"]').click();
  203. await waitForWorkspaceApp(paths[0], 30_000);
  204. expect(await toggle.getAttribute("aria-expanded")).toBe("false");
  205. const original = $('[data-project-name="ZCodeProject"]');
  206. await original.moveTo();
  207. await original.$('[data-testid="virtual-project-create-task"]').click();
  208. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30_000);
  209. });
  210. it("VP20:单 workspace 查看文件显示完整路径并适配窄屏", async function () {
  211. this.timeout(60_000);
  212. const original = $('[data-project-name="ZCodeProject"]');
  213. await original.waitForDisplayed();
  214. const appearance = await browser.execute(() => ({
  215. width: innerWidth,
  216. theme: (
  217. window as Window & { __testActions?: { getTheme(): string } }
  218. ).__testActions!.getTheme(),
  219. }));
  220. const ensureSidebarExpanded = async () => {
  221. const expanded = () =>
  222. browser.execute(() => {
  223. const shell = document.querySelector('[data-workspace-shell="true"]')!;
  224. return (
  225. Number.parseFloat(
  226. getComputedStyle(shell).getPropertyValue("--workspace-sidebar-panel-width"),
  227. ) > 200
  228. );
  229. });
  230. if (!(await expanded()))
  231. await $('button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]').click();
  232. await browser.waitUntil(expanded);
  233. await original.waitForDisplayed();
  234. };
  235. const files = $('[data-testid="virtual-project-context-files-0"]');
  236. try {
  237. await original.$('[data-testid="virtual-project-row"]').click({ button: "right" });
  238. await files.waitForDisplayed();
  239. // 与弹窗布局验收一致:先打开菜单,再缩放;桌面窄屏会自动收起侧栏,不代表手机导航入口。
  240. for (const width of [1200, 390]) {
  241. await setRendererViewport(width, 844);
  242. for (const theme of ["zai-light", "zai-dark"]) {
  243. await browser.execute((value) => {
  244. (
  245. window as Window & { __testActions?: { setTheme(theme: string): void } }
  246. ).__testActions!.setTheme(value);
  247. }, theme);
  248. await browser.waitUntil(() =>
  249. browser.execute(
  250. (value) => document.documentElement.classList.contains(`theme-${value}`),
  251. theme,
  252. ),
  253. );
  254. expect(await files.getText()).toBe(`查看文件 · ${DEFAULT_WORKSPACE}`);
  255. const fit = await browser.execute(async () => {
  256. const menu = document.querySelector('[data-slot="context-menu-content"]')!;
  257. await Promise.all(menu.getAnimations().map((animation) => animation.finished));
  258. const bounds = menu.getBoundingClientRect();
  259. return { left: bounds.left, right: bounds.right, viewport: innerWidth };
  260. });
  261. expect(fit.left).toBeGreaterThanOrEqual(0);
  262. expect(fit.right).toBeLessThanOrEqual(fit.viewport);
  263. await browser.saveScreenshot(
  264. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `VP20-single-root-${width}-${theme}.png`),
  265. );
  266. }
  267. }
  268. } finally {
  269. // 新增项目详情后 Escape 先交给详情层;先离开 hover 区再关闭右键菜单。
  270. const outside = await browser.execute(() => ({ x: innerWidth - 8, y: 8 }));
  271. await browser.action("pointer").move(outside).perform();
  272. await $('[data-testid="project-identity-details"]').waitForExist({ reverse: true });
  273. await browser.keys("Escape");
  274. await files.waitForExist({ reverse: true });
  275. await clearRendererViewport();
  276. await browser.waitUntil(() =>
  277. browser.execute((width) => innerWidth === width, appearance.width),
  278. );
  279. await ensureSidebarExpanded();
  280. await browser.execute((value) => {
  281. (
  282. window as Window & { __testActions?: { setTheme(theme: string): void } }
  283. ).__testActions!.setTheme(value);
  284. }, appearance.theme);
  285. }
  286. });
  287. it("VP20:本地项目共用详情,单多目录完整展示且不重复名称", async function () {
  288. this.timeout(180_000);
  289. const paths = ["one", "two-with-a-long-directory-name-for-hover-layout"].map((name) =>
  290. join(DEFAULT_WORKSPACE, ".zcode-e2e", "project-hover-details", name),
  291. );
  292. await Promise.all(paths.map((path) => mkdir(path, { recursive: true })));
  293. const cases = [
  294. { name: "ZCodeProject", paths: [DEFAULT_WORKSPACE] },
  295. { name: "E2E_PROJECT_HOVER_MULTI", paths },
  296. { name: "E2E_PROJECT_HOVER_EMPTY", paths: [] },
  297. ];
  298. for (const project of cases.slice(1)) {
  299. if (!project.paths.length) {
  300. // UI 创建后进入草稿会分配默认 root;通过真实 Host 仅登记空项目,不触发任务创建。
  301. await installHandoffRpcProbe();
  302. try {
  303. await callHandoffHost(ServiceChannels.Project, "saveProject", [
  304. { name: project.name, roots: [] },
  305. ]);
  306. } finally {
  307. await restoreHandoffProbes();
  308. }
  309. continue;
  310. }
  311. await openLocalProjectEditor();
  312. await $('[data-testid="virtual-project-name"]').setValue(project.name);
  313. for (const path of project.paths) await chooseProjectRoot(path);
  314. await $('[data-testid="virtual-project-save"]').click();
  315. if (project.paths.length) {
  316. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  317. await $('[data-testid="project-folder-trust-confirm"]').click();
  318. }
  319. await $('[data-slot="dialog-overlay"]').waitForExist({ reverse: true });
  320. }
  321. const appearance = await browser.execute(() => ({
  322. width: innerWidth,
  323. theme: (
  324. window as Window & { __testActions?: { getTheme(): string } }
  325. ).__testActions!.getTheme(),
  326. }));
  327. const details = $('[data-testid="project-identity-details"]');
  328. const closeDetails = async () => {
  329. const outside = await browser.execute(() => ({ x: innerWidth - 8, y: 8 }));
  330. await browser.action("pointer").move(outside).perform();
  331. await browser.executeAsync((done) => requestAnimationFrame(() => done()));
  332. expect(await details.isExisting()).toBe(false);
  333. };
  334. try {
  335. for (const project of cases) {
  336. const layouts =
  337. project.paths.length === 2
  338. ? ([
  339. { width: 1200, theme: "zai-light", locale: "zh-CN" },
  340. { width: 1200, theme: "zai-dark", locale: "en-US" },
  341. { width: 390, theme: "zai-light", locale: "en-US" },
  342. { width: 390, theme: "zai-dark", locale: "zh-CN" },
  343. ] as const)
  344. : ([{ width: 1200, theme: "zai-light", locale: "zh-CN" }] as const);
  345. for (const { width, theme, locale } of layouts) {
  346. const previousWidth = await browser.execute(() => innerWidth);
  347. await setRendererViewport(width, 844);
  348. await browser.execute(
  349. (theme, locale) => {
  350. const actions = (
  351. window as Window & {
  352. __testActions?: {
  353. setTheme(value: string): void;
  354. setLocale(value: "zh-CN" | "en-US"): void;
  355. };
  356. }
  357. ).__testActions!;
  358. actions.setTheme(theme);
  359. actions.setLocale(locale);
  360. },
  361. theme,
  362. locale,
  363. );
  364. // viewport 更新后 Shell 在后续帧收起侧栏,先完成布局再读取开关状态。
  365. await browser.executeAsync((done) =>
  366. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  367. );
  368. const sidebarExpanded = () =>
  369. browser.execute(() => {
  370. const shell = document.querySelector('[data-workspace-shell="true"]')!;
  371. return (
  372. Number.parseFloat(
  373. getComputedStyle(shell).getPropertyValue("--workspace-sidebar-panel-width"),
  374. ) > 200
  375. );
  376. });
  377. // 真实 resize 会等 idle 后自动收起;等待实际状态,不能在收起前抢先 hover。
  378. if (width === 390 && previousWidth !== width) {
  379. await browser.waitUntil(async () => !(await sidebarExpanded()));
  380. }
  381. if (!(await sidebarExpanded())) {
  382. await $('button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]').click();
  383. }
  384. await browser.waitUntil(sidebarExpanded);
  385. for (const entry of ["sidebar", "composer"]) {
  386. if (entry === "composer") {
  387. await $('[data-testid="composer-workspace-trigger"]').click();
  388. await $('[data-testid="composer-project-menu"] input').setValue(project.name);
  389. }
  390. const scope = entry === "sidebar" ? "aside" : '[data-testid="composer-project-menu"]';
  391. const target = $(`${scope} [data-project-name="${project.name}"]`);
  392. await (
  393. entry === "sidebar" ? target.$('[data-testid="virtual-project-toggle"]') : target
  394. ).moveTo();
  395. await details.waitForDisplayed();
  396. expect(await details.$("strong").getText()).toBe(project.name);
  397. expect(await details.$$("dt").map((field) => field.getText())).toEqual([
  398. locale === "zh-CN" ? "目录" : "Directory",
  399. ]);
  400. expect(await details.$$("dd > div").map((path) => path.getText())).toEqual(
  401. project.paths,
  402. );
  403. if (!project.paths.length) expect(await details.$("dd").getText()).toBe("—");
  404. const geometry = await browser.execute(async () => {
  405. const card = document.querySelector('[data-testid="project-identity-details"]')!;
  406. await Promise.all(card.getAnimations().map((animation) => animation.finished));
  407. const bounds = card.getBoundingClientRect();
  408. return {
  409. left: bounds.left,
  410. right: bounds.right,
  411. top: bounds.top,
  412. bottom: bounds.bottom,
  413. width: innerWidth,
  414. height: innerHeight,
  415. cardWidth: bounds.width,
  416. valueWidth: card.querySelector("dd")!.getBoundingClientRect().width,
  417. };
  418. });
  419. expect(geometry.left).toBeGreaterThanOrEqual(0);
  420. expect(geometry.right).toBeLessThanOrEqual(geometry.width);
  421. expect(geometry.top).toBeGreaterThanOrEqual(0);
  422. expect(geometry.bottom).toBeLessThanOrEqual(geometry.height);
  423. expect(geometry.valueWidth).toBeGreaterThanOrEqual(
  424. Math.min(120, geometry.cardWidth - 32),
  425. );
  426. await browser.saveScreenshot(
  427. join(
  428. process.env.ZCODE_E2E_ARTIFACT_DIR!,
  429. `VP20-hover-${project.paths.length}-${entry}-${width}-${theme}-${locale}.png`,
  430. ),
  431. );
  432. await details.moveTo();
  433. expect(await details.isDisplayed()).toBe(true);
  434. await closeDetails();
  435. if (entry === "composer") {
  436. await browser.keys("Escape");
  437. await $('[data-testid="composer-project-menu"]').waitForExist({ reverse: true });
  438. }
  439. }
  440. }
  441. }
  442. } finally {
  443. await browser.keys("Escape");
  444. await clearRendererViewport();
  445. await browser.execute((theme) => {
  446. const actions = (
  447. window as Window & {
  448. __testActions?: {
  449. setTheme(value: string): void;
  450. setLocale(value: "zh-CN"): void;
  451. };
  452. }
  453. ).__testActions!;
  454. actions.setTheme(theme);
  455. actions.setLocale("zh-CN");
  456. }, appearance.theme);
  457. }
  458. });
  459. it("VP22:已有目录列表、设为主要与编辑器删除", async function () {
  460. this.timeout(90_000);
  461. const testHome = process.env.ZCODE_E2E_HOME_DIR!;
  462. if (
  463. ![".e2e-home-", "zcode-virtual-project-e2e-"].some((prefix) =>
  464. basename(testHome).startsWith(prefix),
  465. )
  466. )
  467. throw new Error("隔离 HOME required");
  468. const paths = ["test-aaa", "test-bbb"].map((name) =>
  469. join(DEFAULT_WORKSPACE, ".zcode-e2e", "project-editor", name),
  470. );
  471. await Promise.all(
  472. paths.map(async (path) => {
  473. await mkdir(path, { recursive: true });
  474. await writeFile(join(path, "keep.txt"), "preserve project files");
  475. }),
  476. );
  477. await openLocalProjectEditor();
  478. expect(await $('[data-testid="virtual-project-editor-delete"]').isExisting()).toBe(false);
  479. for (const path of paths) await chooseProjectRoot(path);
  480. await $('[data-testid="virtual-project-name"]').setValue("E2E_PROJECT_EDITOR");
  481. expect(
  482. await $(
  483. '[data-testid="virtual-project-roots"] [data-testid="virtual-project-browse"]',
  484. ).getText(),
  485. ).toMatch(/添加文件夹|Add folder/);
  486. expect(await $('[role="dialog"] input[type="radio"]').isExisting()).toBe(false);
  487. await $('[data-testid="virtual-project-save"]').click();
  488. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  489. await $('[data-testid="project-folder-trust-confirm"]').click();
  490. const project = $('[data-project-name="E2E_PROJECT_EDITOR"]');
  491. await project.waitForDisplayed();
  492. const id = await project.getAttribute("data-project-id");
  493. const db = new DatabaseSync(join(testHome, ".zcode", "v2", "tasks-index.sqlite"), {
  494. readOnly: true,
  495. });
  496. const primary = () =>
  497. db.prepare("SELECT root_path FROM project_roots WHERE project_id=? AND is_primary=1").get(id)
  498. ?.root_path;
  499. const edit = async () => {
  500. await project.$('[data-testid="virtual-project-row"]').click({ button: "right" });
  501. await $('[data-testid="virtual-project-edit"]').click();
  502. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  503. };
  504. try {
  505. await edit();
  506. const rows = await $$('[data-testid="virtual-project-root-row"]');
  507. expect(await rows[0]!.$('[data-testid="virtual-project-root-name"]').getText()).toBe(
  508. "test-aaa",
  509. );
  510. expect(await rows[1]!.$('[data-testid="virtual-project-root-name"]').getText()).toBe(
  511. "test-bbb",
  512. );
  513. await rows[1]!.$('[data-testid="virtual-project-set-primary"]').click();
  514. expect(primary()).toBe(paths[0]);
  515. await rows[1]!.$('[data-testid="virtual-project-primary"]').waitForDisplayed();
  516. await captureProjectDialogLayouts("populated-editor");
  517. await $('[data-testid="virtual-project-save"]').click();
  518. await $('[role="dialog"]').waitForExist({ reverse: true });
  519. await browser.waitUntil(() => primary() === paths[1]);
  520. // 窄屏采样会按既有策略收起侧栏,通过真实入口恢复后继续操作。
  521. if (
  522. await browser.execute(
  523. () => (document.querySelector("aside")?.getBoundingClientRect().width ?? 0) < 200,
  524. )
  525. ) {
  526. await $('button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]').click();
  527. await browser.waitUntil(() =>
  528. browser.execute(
  529. () => (document.querySelector("aside")?.getBoundingClientRect().width ?? 0) > 200,
  530. ),
  531. );
  532. }
  533. await edit();
  534. const reopened = await $$('[data-testid="virtual-project-root-row"]');
  535. await reopened[1]!.$('[data-testid="virtual-project-primary"]').waitForDisplayed();
  536. await reopened[1]!.$('[data-testid="virtual-project-remove-folder"]').click();
  537. await reopened[0]!.$('[data-testid="virtual-project-primary"]').waitForDisplayed();
  538. await $('[role="dialog"]')
  539. .$('.//button[normalize-space(.)="取消" or normalize-space(.)="Cancel"]')
  540. .click();
  541. await $('[role="dialog"]').waitForExist({ reverse: true });
  542. expect(primary()).toBe(paths[1]);
  543. await project.moveTo();
  544. await project.$('[data-testid="virtual-project-create-task"]').click();
  545. await waitForWorkspaceApp(paths[1]!, 30_000);
  546. await edit();
  547. await $('[data-testid="virtual-project-editor-delete"]').click();
  548. await $('[role="dialog"]').waitForExist({ reverse: true });
  549. await project.waitForExist({ reverse: true });
  550. expect(db.prepare("SELECT deleted FROM projects WHERE project_id=?").get(id)?.deleted).toBe(
  551. 1,
  552. );
  553. expect(
  554. db.prepare("SELECT count(*) AS n FROM project_roots WHERE project_id=?").get(id)?.n,
  555. ).toBe(2);
  556. for (const path of paths)
  557. expect(await readFile(join(path, "keep.txt"), "utf8")).toBe("preserve project files");
  558. } finally {
  559. db.close();
  560. await browser.keys("Escape");
  561. const original = $('[data-project-name="ZCodeProject"]');
  562. await original.moveTo();
  563. await original.$('[data-testid="virtual-project-create-task"]').click();
  564. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30_000);
  565. }
  566. });
  567. it("VP12:Bot 访问范围选择项目 ID,同 cwd 的项目分别保存", async function () {
  568. this.timeout(90_000);
  569. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  570. const testHome = process.env.ZCODE_E2E_HOME_DIR!;
  571. if (
  572. !testHome ||
  573. ![".e2e-home-", "zcode-virtual-project-e2e-"].some((prefix) =>
  574. basename(testHome).startsWith(prefix),
  575. )
  576. )
  577. throw new Error("隔离 HOME required");
  578. const cwd = join(testHome, "E2E_VP12_SHARED_ROOT");
  579. await mkdir(cwd, { recursive: true });
  580. const names = ["E2E_VP12_A", "E2E_VP12_B"];
  581. const ids: string[] = [];
  582. for (const name of names) {
  583. await openLocalProjectEditor();
  584. await $('[data-testid="virtual-project-name"]').setValue(name);
  585. await chooseProjectRoot(cwd);
  586. await $('[data-testid="virtual-project-save"]').click();
  587. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  588. await $('[data-testid="project-folder-trust-confirm"]').click();
  589. const project = $(`[data-project-name="${name}"]`);
  590. await project.waitForDisplayed();
  591. const projectId = await project.getAttribute("data-project-id");
  592. if (!projectId) throw new Error("项目 ID 缺失");
  593. ids.push(projectId);
  594. }
  595. // 创建项目会打开草稿;访问范围编辑本身不能增加或切换 workspace。
  596. const readBotTabs = () =>
  597. browser.execute(() => {
  598. const store = (
  599. window as Window & {
  600. __zcodeTabStoreE2E?: { getState(): { tabs: Array<{ workspacePath?: string }> } };
  601. }
  602. ).__zcodeTabStoreE2E;
  603. return store?.getState().tabs.map((tab) => tab.workspacePath) ?? [];
  604. });
  605. const tabsBeforeBotAccess = await readBotTabs();
  606. const configPath = join(testHome, ".zcode/v2/bot-config.v3.json");
  607. await writeFile(
  608. configPath,
  609. JSON.stringify({
  610. version: 3,
  611. bots: [
  612. {
  613. id: "E2E_VP12_BOT",
  614. name: "E2E_VP12_BOT",
  615. provider: "webhook",
  616. enabled: false,
  617. allowedWorkspaces: ["*"],
  618. allowedCommands: {
  619. status: true,
  620. new: true,
  621. workspace: true,
  622. model: true,
  623. thoughtLevel: true,
  624. reply: true,
  625. },
  626. currentOptions: {},
  627. replyMode: "assistant_changes",
  628. },
  629. ],
  630. }),
  631. );
  632. const remoteControl = $(
  633. 'button[aria-label="移动端远程控制"], button[aria-label="Mobile remote control"]',
  634. );
  635. await remoteControl.waitForClickable();
  636. await remoteControl.click();
  637. await $('[data-testid="web-remote-control-open-bots"]').waitForClickable();
  638. await $('[data-testid="web-remote-control-open-bots"]').click();
  639. try {
  640. const access = $('[data-testid="bots-project-access-trigger"]');
  641. await access.waitForClickable();
  642. await access.click();
  643. // Radix 选项文本承载于内部 span,点击公开 option 元素。
  644. await browser.waitUntil(async () => (await $$('[role="option"]').length) > 0);
  645. await browser.execute(() => {
  646. const item = Array.from(document.querySelectorAll<HTMLElement>('[role="option"]')).find(
  647. (node) => /指定项目|Selected projects/.test(node.textContent ?? ""),
  648. );
  649. if (!item) throw new Error("指定项目选项缺失");
  650. item.click();
  651. });
  652. for (let index = 0; index < names.length; index++) {
  653. const button = $(`button[title="${names[index]}"]`);
  654. await button.waitForClickable();
  655. const readAllowed = async () =>
  656. JSON.parse(await readFile(configPath, "utf8")).bots[0].allowedWorkspaces as string[];
  657. const id = JSON.stringify(["local", ids[index]]);
  658. if (!(await readAllowed()).includes(id)) await button.click();
  659. await browser.waitUntil(async () => (await readAllowed()).includes(id));
  660. }
  661. const allowed = JSON.parse(await readFile(configPath, "utf8")).bots[0]
  662. .allowedWorkspaces as string[];
  663. expect(ids.every((id) => allowed.includes(JSON.stringify(["local", id])))).toBe(true);
  664. expect(allowed.includes(cwd)).toBe(false);
  665. expect(await readBotTabs()).toEqual(tabsBeforeBotAccess);
  666. } finally {
  667. await browser.keys("Escape");
  668. await browser.keys("Escape");
  669. }
  670. });
  671. it("VP01:首个窗口可用时 app 与 CLI 两库的版本化迁移已经完成", async function () {
  672. this.timeout(60_000);
  673. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  674. const testHome = process.env.ZCODE_E2E_HOME_DIR;
  675. if (
  676. !testHome ||
  677. ![".e2e-home-", "zcode-virtual-project-e2e-"].some((prefix) =>
  678. basename(testHome).startsWith(prefix),
  679. )
  680. )
  681. throw new Error("isolated temporary E2E HOME required");
  682. for (const [path, migrationId] of [
  683. [join(testHome, ".zcode", "v2", "tasks-index.sqlite"), "0005_projects"],
  684. [join(testHome, ".zcode", "cli", "db", "db.sqlite"), "0023_session_soft_delete_outcome"],
  685. ] as const) {
  686. const db = new DatabaseSync(path, { readOnly: true });
  687. try {
  688. expect(
  689. db.prepare("SELECT id FROM schema_migration WHERE id=?").get(migrationId),
  690. ).toBeDefined();
  691. } finally {
  692. db.close();
  693. }
  694. }
  695. });
  696. it("VP08:离线远端项目只显示缓存,移除入口后重载不复活", async function () {
  697. this.timeout(90_000);
  698. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  699. const testHome = process.env.ZCODE_E2E_HOME_DIR;
  700. if (
  701. !testHome ||
  702. ![".e2e-home-", "zcode-virtual-project-e2e-"].some((prefix) =>
  703. basename(testHome).startsWith(prefix),
  704. )
  705. )
  706. throw new Error("isolated temporary E2E HOME required");
  707. const db = new DatabaseSync(join(testHome, ".zcode", "v2", "tasks-index.sqlite"));
  708. try {
  709. // 只在隔离 HOME 注入离线缓存,不接触真实设备、网络或用户目录。
  710. db.prepare("INSERT INTO hosts(host_id,kind,target_json,membership_id) VALUES(?,?,?,?)").run(
  711. "remote:server:e2e-offline",
  712. "docker",
  713. JSON.stringify({ kind: "docker", container: "e2e-offline-fixture" }),
  714. "e2e-member",
  715. );
  716. db.prepare(
  717. "INSERT INTO remote_project_entries(entry_id,host_id,remote_project_id,cached_name,cached_roots_json) VALUES(?,?,?,?,?)",
  718. ).run(
  719. "e2e-offline-entry",
  720. "remote:server:e2e-offline",
  721. "offline-project",
  722. "E2E_VP08_Offline",
  723. JSON.stringify([{ rootPath: "/e2e/offline-root", position: 0, isPrimary: true }]),
  724. );
  725. } finally {
  726. db.close();
  727. }
  728. await browser.refresh();
  729. // 隔离测试刷新后可能重新进入欢迎页;复用既有登录准备,不放宽离线项目断言。
  730. const apiKeyEntry = $('[data-testid="login-use-api-key-button"]');
  731. await browser.waitUntil(
  732. async () =>
  733. (await apiKeyEntry.isDisplayed()) ||
  734. (await $('[data-workspace-shell="true"]').isDisplayed()),
  735. { timeout: 45_000 },
  736. );
  737. if (await apiKeyEntry.isDisplayed()) await loginWithApiKey();
  738. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  739. const offline = $('[data-project-name="E2E_VP08_Offline"]');
  740. try {
  741. await offline.waitForDisplayed({ timeout: 30_000 });
  742. } catch (error) {
  743. const geometry = await browser.execute(() => {
  744. const target = document.querySelector('[data-project-name="E2E_VP08_Offline"]');
  745. const rows = [];
  746. for (let node = target; node; node = node.parentElement) {
  747. const style = getComputedStyle(node),
  748. rect = node.getBoundingClientRect();
  749. rows.push({
  750. tag: node.tagName,
  751. slot: node.getAttribute("data-slot"),
  752. state: node.getAttribute("data-state"),
  753. box: { height: rect.height, width: rect.width },
  754. visibility: style.visibility,
  755. display: style.display,
  756. opacity: style.opacity,
  757. overflow: style.overflow,
  758. animation: style.animation,
  759. });
  760. }
  761. return rows;
  762. });
  763. throw new Error(String(error) + JSON.stringify(geometry));
  764. }
  765. const readSettings = async () =>
  766. JSON.parse(await readFile(join(testHome, ".zcode/v2/setting.json"), "utf8"));
  767. await browser.waitUntil(async () =>
  768. (await readSettings()).lastWorkspaceSession.some(
  769. (entry: { workspacePath: string }) => entry.workspacePath === "/e2e/offline-root",
  770. ),
  771. );
  772. expect(await $('[data-testid="remote-project-host"]').isExisting()).toBe(false);
  773. expect(await offline.$('[data-testid="project-device"]').getText()).toContain(
  774. "e2e-offline-fixture",
  775. );
  776. expect(
  777. await offline.$('[data-testid="virtual-project-toggle"]').getAttribute("aria-expanded"),
  778. ).toBe("false");
  779. expect(await offline.$('[data-testid="virtual-project-create-task"]').isExisting()).toBe(false);
  780. await offline.$('[data-testid="virtual-project-row"]').click({ button: "right" });
  781. expect(await $('[data-testid="virtual-project-edit"]').isExisting()).toBe(false);
  782. await $('[data-testid="virtual-project-remove-entry"]').click();
  783. await offline.waitForDisplayed({ reverse: true });
  784. expect(
  785. (await readSettings()).lastWorkspaceSession.some(
  786. (entry: { workspacePath: string }) => entry.workspacePath === "/e2e/offline-root",
  787. ),
  788. ).toBe(false);
  789. await refreshVirtualProjectWorkspace();
  790. expect(await offline.isExisting()).toBe(false);
  791. const check = new DatabaseSync(join(testHome, ".zcode", "v2", "tasks-index.sqlite"), {
  792. readOnly: true,
  793. });
  794. try {
  795. expect(
  796. check
  797. .prepare("SELECT entry_id FROM remote_project_entries WHERE entry_id='e2e-offline-entry'")
  798. .get(),
  799. ).toBeUndefined();
  800. expect(
  801. check.prepare("SELECT host_id FROM hosts WHERE host_id='remote:server:e2e-offline'").get(),
  802. ).toBeDefined();
  803. } finally {
  804. check.close();
  805. }
  806. });
  807. it("VP08/VP17/VP18 URL:元数据无 tab,远端任务执行、重开与 CLI 冷恢复", async function () {
  808. this.timeout(120_000);
  809. const testHome = process.env.ZCODE_E2E_HOME_DIR;
  810. if (
  811. !testHome ||
  812. ![".e2e-home-", "zcode-virtual-project-e2e-"].some((prefix) =>
  813. basename(testHome).startsWith(prefix),
  814. )
  815. )
  816. throw new Error("isolated E2E HOME required");
  817. const serverHome = join(testHome, "url-server");
  818. await mkdir(join(serverHome, ".zcode", "v2"), { recursive: true });
  819. const child = spawn(
  820. process.execPath,
  821. ["--import", "tsx", "test/e2e/fixtures/virtual-project/server.ts"],
  822. {
  823. cwd: resolve(process.cwd()),
  824. env: {
  825. ...process.env,
  826. HOME: serverHome,
  827. USERPROFILE: serverHome,
  828. ZCODE_DATA_BASE_DIR: serverHome,
  829. ZCODE_DESKTOP_HOME_DIR: serverHome,
  830. },
  831. stdio: ["pipe", "pipe", "pipe"],
  832. },
  833. );
  834. let output = "";
  835. child.stderr.on("data", (data) => {
  836. output += data.toString();
  837. });
  838. try {
  839. const ready = await new Promise<{
  840. port: number;
  841. hostId: string;
  842. serverId: string;
  843. projectId: string;
  844. }>((resolveReady, reject) => {
  845. const deadline = setTimeout(
  846. () => reject(new Error(`URL fixture did not start: ${output.slice(-4000)}`)),
  847. 30_000,
  848. );
  849. child.once("error", (error) => {
  850. clearTimeout(deadline);
  851. reject(error);
  852. });
  853. child.once("exit", (code) => {
  854. clearTimeout(deadline);
  855. reject(new Error(`URL fixture exited ${code}: ${output.slice(-4000)}`));
  856. });
  857. child.stdout.on("data", (data) => {
  858. output += data.toString();
  859. const match = output.match(/E2E_VP_SERVER_READY ([^\n]+)\n/);
  860. if (match) {
  861. clearTimeout(deadline);
  862. resolveReady(JSON.parse(match[1]!));
  863. }
  864. });
  865. });
  866. const dbPath = join(testHome, ".zcode/v2/tasks-index.sqlite");
  867. const db = new DatabaseSync(dbPath);
  868. try {
  869. db.prepare("INSERT INTO hosts(host_id,kind,target_json,membership_id) VALUES(?,?,?,?)").run(
  870. ready.hostId,
  871. "server",
  872. JSON.stringify({
  873. kind: "server",
  874. url: `http://127.0.0.1:${ready.port}`,
  875. serverId: ready.serverId,
  876. name: "E2E_URL_HOST",
  877. }),
  878. "e2e-url-member",
  879. );
  880. } finally {
  881. db.close();
  882. }
  883. await refreshVirtualProjectWorkspace();
  884. await installHandoffRpcProbe();
  885. const addExistingProject = async () => {
  886. // Direct URL 不属于 Source 设备选择器;通过专用元数据服务准备入口,下面继续验真实项目 UI。
  887. const tree = await callHandoffHost<{ projects: VirtualProject[] }>(
  888. ServiceChannels.Project,
  889. "readTree",
  890. [{ hostId: ready.hostId }],
  891. );
  892. const remoteProject = tree.projects.find((project) => project.id === ready.projectId)!;
  893. await callHandoffHost(ServiceChannels.RemoteProjects, "addEntry", [
  894. {
  895. hostId: ready.hostId,
  896. expectedMembershipId: "e2e-url-member",
  897. project: {
  898. projectId: remoteProject.id,
  899. name: remoteProject.name,
  900. roots: remoteProject.roots,
  901. },
  902. },
  903. ]);
  904. };
  905. const readTabs = () =>
  906. browser.execute(() => {
  907. const state = (
  908. window as Window & {
  909. __zcodeTabStoreE2E?: {
  910. getState(): {
  911. tabs: { workspacePath?: string; workspaceIdentity?: string; kind?: string }[];
  912. };
  913. };
  914. }
  915. ).__zcodeTabStoreE2E?.getState();
  916. return state?.tabs.map((tab) => tab.workspaceIdentity || tab.workspacePath || tab.kind);
  917. });
  918. const tabs = await readTabs();
  919. // 保留 Host 记录不会建立连接;先走真实连接服务,避免离线调用被误判为项目业务失败。
  920. const connected = await callHandoffHost<{ id: string; connectionStatus: string }>(
  921. ServiceChannels.RemoteProjects,
  922. "connectHost",
  923. [ready.hostId],
  924. );
  925. expect(connected.id).toBe(ready.hostId);
  926. expect(connected.connectionStatus).toBe("online");
  927. expect(await readTabs()).toEqual(tabs);
  928. const createdMetadata = await callHandoffHost<VirtualProject>(
  929. ServiceChannels.Project,
  930. "saveProject",
  931. [
  932. {
  933. hostId: ready.hostId,
  934. name: "E2E_VP19_REMOTE_CREATED",
  935. roots: [join(serverHome, "work", "repo")],
  936. },
  937. ],
  938. );
  939. await callHandoffHost(ServiceChannels.RemoteProjects, "addEntry", [
  940. {
  941. hostId: ready.hostId,
  942. expectedMembershipId: "e2e-url-member",
  943. project: {
  944. projectId: createdMetadata.id,
  945. name: createdMetadata.name,
  946. roots: createdMetadata.roots,
  947. },
  948. },
  949. ]);
  950. const createdRemote = $('[data-project-name="E2E_VP19_REMOTE_CREATED"]');
  951. await createdRemote.waitForDisplayed();
  952. expect(await readTabs()).toEqual(tabs);
  953. await removeRemoteProjectEntryForRow('[data-project-name="E2E_VP19_REMOTE_CREATED"]');
  954. await createdRemote.waitForExist({ reverse: true });
  955. await addExistingProject();
  956. let project = $('[data-project-name="E2E_VP08_URL"]');
  957. await project.waitForDisplayed();
  958. expect(await readTabs()).toEqual(tabs);
  959. child.stdin.write("rename-externally\n");
  960. project = $('[data-project-name="E2E_VP08_URL_EXTERNAL"]');
  961. await project.waitForDisplayed({ timeout: 15_000 });
  962. await project.$('[data-testid="virtual-project-row"]').click({ button: "right" });
  963. await $('[data-testid="virtual-project-edit"]').click();
  964. await $('[data-testid="virtual-project-name"]').setValue("E2E_VP08_URL_RENAMED");
  965. expect(await $('[data-testid="virtual-project-browse"]').isExisting()).toBe(false);
  966. expect(await readTabs()).toEqual(tabs);
  967. await $('[data-testid="virtual-project-save"]').click();
  968. const renamed = $('[data-project-name="E2E_VP08_URL_RENAMED"]');
  969. await renamed.waitForDisplayed();
  970. const remoteDb = new DatabaseSync(join(serverHome, ".zcode/v2/tasks-index.sqlite"), {
  971. readOnly: true,
  972. });
  973. try {
  974. expect(
  975. remoteDb.prepare("SELECT name FROM projects WHERE project_id=?").get(ready.projectId)
  976. ?.name,
  977. ).toBe("E2E_VP08_URL_RENAMED");
  978. } finally {
  979. remoteDb.close();
  980. }
  981. await removeRemoteProjectEntryForRow('[data-project-name="E2E_VP08_URL_RENAMED"]');
  982. await renamed.waitForDisplayed({ reverse: true });
  983. await refreshVirtualProjectWorkspace();
  984. // 刷新会销毁旧 renderer 的 RPC 探针;重新装配当前端口后才能继续准备元数据。
  985. await installHandoffRpcProbe();
  986. expect(await renamed.isExisting()).toBe(false);
  987. expect(await readTabs()).toEqual(tabs);
  988. const check = new DatabaseSync(dbPath, { readOnly: true });
  989. try {
  990. expect(
  991. check.prepare("SELECT count(*) AS n FROM projects WHERE host_id=?").get(ready.hostId)?.n,
  992. ).toBe(0);
  993. expect(
  994. check
  995. .prepare("SELECT count(*) AS n FROM remote_project_entries WHERE host_id=?")
  996. .get(ready.hostId)?.n,
  997. ).toBe(0);
  998. } finally {
  999. check.close();
  1000. }
  1001. // 主动重新添加同一个远端项目,元数据路径已验证无 tab;下面单独验证真实执行。
  1002. await addExistingProject();
  1003. await renamed.waitForDisplayed();
  1004. expect(await renamed.getAttribute("data-project-id")).toBe(ready.projectId);
  1005. // 显式查看尚未打开的远端 root 才申请绑定;文件树必须读 Source 的文件。
  1006. await writeFile(
  1007. join(serverHome, "work", "repo", "E2E_PROJECT_REMOTE_FILE.txt"),
  1008. "remote owner",
  1009. );
  1010. await renamed.moveTo();
  1011. await renamed.$('[data-testid="virtual-project-files"]').click();
  1012. const fileRoot = $('[data-testid="virtual-project-files-0"]');
  1013. if (await fileRoot.isExisting()) await fileRoot.click();
  1014. const remoteFiles = $('[data-testid="workspace-file-tree-panel"]');
  1015. await remoteFiles.waitForDisplayed();
  1016. await browser.waitUntil(async () =>
  1017. (await remoteFiles.getText()).includes("E2E_PROJECT_REMOTE_FILE.txt"),
  1018. );
  1019. await $('[data-side-pane-tab-id][data-state="active"] button[aria-label]').click();
  1020. await remoteFiles.waitForExist({ reverse: true });
  1021. await renamed.moveTo();
  1022. await renamed.$('[data-testid="virtual-project-create-task"]').click();
  1023. await waitForWorkspaceApp(join(serverHome, "work", "repo"), 30_000);
  1024. await $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).waitForDisplayed();
  1025. const draftOwner = await browser.execute(() => {
  1026. const testWindow = window as Window & {
  1027. __zcodeTabStoreE2E?: {
  1028. getState(): {
  1029. activeWorkspacePath: string | null;
  1030. activeWorkspaceIdentity?: string | null;
  1031. };
  1032. };
  1033. __zcodeSessionStoreE2E?: {
  1034. getState(): {
  1035. getWorkspaceState(
  1036. path: string,
  1037. identity?: string,
  1038. ): { draftProjectId?: string | null; activeTaskId: string | null };
  1039. };
  1040. };
  1041. };
  1042. const tabs = testWindow.__zcodeTabStoreE2E?.getState();
  1043. const draft = tabs?.activeWorkspacePath
  1044. ? testWindow.__zcodeSessionStoreE2E
  1045. ?.getState()
  1046. .getWorkspaceState(
  1047. tabs.activeWorkspacePath,
  1048. tabs.activeWorkspaceIdentity ?? undefined,
  1049. )
  1050. : undefined;
  1051. return {
  1052. path: tabs?.activeWorkspacePath,
  1053. identity: tabs?.activeWorkspaceIdentity,
  1054. projectId: draft?.draftProjectId,
  1055. activeTaskId: draft?.activeTaskId,
  1056. };
  1057. });
  1058. await writeFile(
  1059. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP17-draft.json"),
  1060. JSON.stringify(draftOwner, null, 2),
  1061. );
  1062. expect(draftOwner.projectId).toBe(ready.projectId);
  1063. await setInputValueByTestIdDom(
  1064. TID_V4_COMPOSER_INPUT,
  1065. "E2E_VP17_REMOTE: Reply with E2E_VP17_READY.",
  1066. );
  1067. await $(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).waitForEnabled({ timeout: 30_000 });
  1068. await $(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).click();
  1069. await $('//*[normalize-space(.)="E2E_VP17_READY" and not(*)]').waitForDisplayed({
  1070. timeout: 60_000,
  1071. });
  1072. const captured = await waitForUpstreamNetworkCapture("E2E_VP17_REMOTE");
  1073. expect(JSON.stringify(captured.requestJson).includes("E2E_VP17_REMOTE_EXTRA_SKILL")).toBe(
  1074. true,
  1075. );
  1076. const remoteFacts = new DatabaseSync(join(serverHome, ".zcode/v2/tasks-index.sqlite"), {
  1077. readOnly: true,
  1078. });
  1079. let remoteTaskId: string;
  1080. try {
  1081. await browser.waitUntil(
  1082. () =>
  1083. Boolean(
  1084. remoteFacts
  1085. .prepare(
  1086. "SELECT task_id FROM tasks WHERE project_id=? AND cli_last_outcome='completed'",
  1087. )
  1088. .get(ready.projectId),
  1089. ),
  1090. { timeout: 10_000 },
  1091. );
  1092. const task = remoteFacts
  1093. .prepare(
  1094. "SELECT task_id,host_id,workspace_path,workspace_identity FROM tasks WHERE project_id=? AND cli_last_outcome='completed'",
  1095. )
  1096. .get(ready.projectId)!;
  1097. remoteTaskId = String(task.task_id);
  1098. expect(task.host_id).toBe(ready.hostId);
  1099. expect(task.workspace_path).toBe(join(serverHome, "work", "repo"));
  1100. expect(String(task.workspace_identity)).toContain(ready.serverId);
  1101. } finally {
  1102. remoteFacts.close();
  1103. }
  1104. const controllerFacts = new DatabaseSync(dbPath, { readOnly: true });
  1105. try {
  1106. expect(
  1107. controllerFacts
  1108. .prepare("SELECT count(*) AS n FROM tasks WHERE host_id=?")
  1109. .get(ready.hostId)?.n,
  1110. ).toBe(0);
  1111. } finally {
  1112. controllerFacts.close();
  1113. }
  1114. await $('[data-testid="task-new-button"]').click();
  1115. await $('//*[normalize-space(.)="E2E_VP17_READY" and not(*)]').waitForDisplayed({
  1116. reverse: true,
  1117. });
  1118. await renamed.$(`[data-testid="${testId(TID_TASK_ITEM, remoteTaskId)}"]`).click();
  1119. await $('//*[normalize-space(.)="E2E_VP17_READY" and not(*)]').waitForDisplayed();
  1120. await browser.saveScreenshot(
  1121. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP17-remote-task.png"),
  1122. );
  1123. const currentRuntime = () =>
  1124. Array.from(output.matchAll(/E2E_VP18_RUNTIME ([^\n]+)\n/g))
  1125. .map((match) => JSON.parse(match[1]!) as { state: string; identity: string })
  1126. .filter((event) => event.state === "available")
  1127. .at(-1)?.identity;
  1128. const previousRuntime = currentRuntime();
  1129. expect(previousRuntime).toBeTruthy();
  1130. await $('[data-testid="task-new-button"]').click();
  1131. await $('//*[normalize-space(.)="E2E_VP17_READY" and not(*)]').waitForDisplayed({
  1132. reverse: true,
  1133. });
  1134. child.stdin.write("refresh-skills-and-dispose\n");
  1135. await browser.waitUntil(() => output.includes("E2E_VP18_DISPOSED"), { timeout: 30_000 });
  1136. await renamed.$(`[data-testid="${testId(TID_TASK_ITEM, remoteTaskId)}"]`).click();
  1137. await $('//*[normalize-space(.)="E2E_VP17_READY" and not(*)]').waitForDisplayed();
  1138. await setInputValueByTestIdDom(
  1139. TID_V4_COMPOSER_INPUT,
  1140. "E2E_VP18_COLD: Reply with E2E_VP18_READY.",
  1141. );
  1142. await $(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).waitForEnabled({ timeout: 30_000 });
  1143. await $(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).click();
  1144. await $('//*[normalize-space(.)="E2E_VP18_READY" and not(*)]').waitForDisplayed({
  1145. timeout: 60_000,
  1146. });
  1147. const coldCapture = await waitForUpstreamNetworkCapture("E2E_VP18_COLD");
  1148. const coldRequest = JSON.stringify(coldCapture.requestJson);
  1149. expect(coldRequest.includes("E2E_VP18_REMOTE_COLD_SKILL")).toBe(true);
  1150. expect(coldRequest.includes("E2E_VP17_REMOTE_EXTRA_SKILL")).toBe(false);
  1151. expect(currentRuntime()).toBeTruthy();
  1152. expect(currentRuntime()).not.toBe(previousRuntime);
  1153. await browser.saveScreenshot(
  1154. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP18-remote-cold.png"),
  1155. );
  1156. // VP25:远端留存 activeTaskId 不能让离开的行继续高亮;归档当前任务后必须退出正文。
  1157. const taskRow = renamed.$(`[data-testid="${testId(TID_TASK_ITEM, remoteTaskId)}"]`);
  1158. expect(await taskRow.getAttribute("class")).toContain("bg-selected");
  1159. await $('[data-testid="task-new-button"]').click();
  1160. await browser.waitUntil(
  1161. async () => !(await taskRow.getAttribute("class"))?.includes("bg-selected"),
  1162. );
  1163. await taskRow.click();
  1164. await $('//*[normalize-space(.)="E2E_VP18_READY" and not(*)]').waitForDisplayed();
  1165. await taskRow.moveTo();
  1166. const archive = taskRow.$(`[data-testid="${testId(TID_TASK_ARCHIVE, remoteTaskId)}"]`);
  1167. await archive.click();
  1168. if (
  1169. (await taskRow.isExisting()) &&
  1170. (await taskRow.getAttribute("data-archive-confirming-task-id")) === remoteTaskId
  1171. )
  1172. await archive.click();
  1173. await taskRow.waitForExist({ reverse: true });
  1174. await $('//*[normalize-space(.)="E2E_VP18_READY" and not(*)]').waitForDisplayed({
  1175. reverse: true,
  1176. });
  1177. const archiveFacts = new DatabaseSync(join(serverHome, ".zcode/v2/tasks-index.sqlite"), {
  1178. readOnly: true,
  1179. });
  1180. try {
  1181. expect(
  1182. archiveFacts.prepare("SELECT archived FROM tasks WHERE task_id=?").get(remoteTaskId)
  1183. ?.archived,
  1184. ).toBe(1);
  1185. } finally {
  1186. archiveFacts.close();
  1187. }
  1188. await $('[data-project-name="ZCodeProject"]')
  1189. .$('[data-testid="virtual-project-create-task"]')
  1190. .click();
  1191. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30_000);
  1192. await removeRemoteProjectEntryForRow('[data-project-name="E2E_VP08_URL_RENAMED"]');
  1193. await renamed.waitForDisplayed({ reverse: true });
  1194. const cliDb = new DatabaseSync(join(serverHome, ".zcode", "cli", "db", "db.sqlite"), {
  1195. readOnly: true,
  1196. });
  1197. try {
  1198. expect(
  1199. cliDb.prepare("SELECT directory FROM session WHERE id=?").get(remoteTaskId)?.directory,
  1200. ).toBe(join(serverHome, "work", "repo"));
  1201. expect(
  1202. Number(
  1203. cliDb.prepare("SELECT count(*) AS n FROM message WHERE session_id=?").get(remoteTaskId)
  1204. ?.n,
  1205. ),
  1206. ).toBeGreaterThanOrEqual(4);
  1207. } finally {
  1208. cliDb.close();
  1209. }
  1210. } finally {
  1211. try {
  1212. await browser.saveScreenshot(join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP17-final.png"));
  1213. // 测试服务退出前回到本地,防止后续用例被已关闭 Source 的活动 tab 阻塞。
  1214. await $('[data-project-name="ZCodeProject"]')
  1215. .$('[data-testid="virtual-project-create-task"]')
  1216. .click();
  1217. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30_000);
  1218. } catch (error) {
  1219. await writeFile(
  1220. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP17-cleanup-error.log"),
  1221. String(error),
  1222. );
  1223. } finally {
  1224. if (child.exitCode === null) {
  1225. child.kill("SIGTERM");
  1226. await once(child, "exit");
  1227. }
  1228. }
  1229. const factsDb = new DatabaseSync(join(serverHome, ".zcode/v2/tasks-index.sqlite"), {
  1230. readOnly: true,
  1231. });
  1232. try {
  1233. await writeFile(
  1234. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP17-facts.json"),
  1235. JSON.stringify(
  1236. factsDb
  1237. .prepare(
  1238. "SELECT task_id,project_id,host_id,workspace_path,workspace_identity,cli_last_outcome FROM tasks",
  1239. )
  1240. .all(),
  1241. null,
  1242. 2,
  1243. ),
  1244. );
  1245. } finally {
  1246. factsDb.close();
  1247. }
  1248. await writeFile(join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP17-server.log"), output);
  1249. if (process.env.DEEPSEEK_E2E_CAPTURE_PATH)
  1250. await writeFile(
  1251. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP17-network.json"),
  1252. await readFile(process.env.DEEPSEEK_E2E_CAPTURE_PATH),
  1253. );
  1254. }
  1255. });
  1256. after(async () => {
  1257. await browser.electron.restoreAllMocks();
  1258. await clearAppData();
  1259. });
  1260. it("VP05:重复新建未归类草稿复用待发送目录,刷新后归属不变", async function () {
  1261. this.timeout(60_000);
  1262. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  1263. const readDraft = () =>
  1264. browser.execute(() => {
  1265. const bridge = window as Window & {
  1266. __zcodeTabStoreE2E?: {
  1267. getState(): {
  1268. activeWorkspacePath: string | null;
  1269. activeWorkspaceIdentity?: string | null;
  1270. };
  1271. };
  1272. __zcodeSessionStoreE2E?: {
  1273. getState(): {
  1274. getWorkspaceState(
  1275. path: string,
  1276. identity?: string,
  1277. ): { draftProjectId?: string | null; activeTaskId: string | null };
  1278. };
  1279. };
  1280. };
  1281. const tabs = bridge.__zcodeTabStoreE2E?.getState();
  1282. const path = tabs?.activeWorkspacePath;
  1283. const state = path
  1284. ? bridge.__zcodeSessionStoreE2E
  1285. ?.getState()
  1286. .getWorkspaceState(path, tabs?.activeWorkspaceIdentity ?? undefined)
  1287. : undefined;
  1288. return { path, projectId: state?.draftProjectId, activeTaskId: state?.activeTaskId };
  1289. });
  1290. const before = await readDraft();
  1291. // 左上角新建继承当前项目;任务分区加号才是显式未归类入口。
  1292. const newTask = $('[data-testid="virtual-project-new-task"]');
  1293. await newTask.click();
  1294. await browser.waitUntil(async () => (await readDraft()).path !== before.path);
  1295. const first = await readDraft();
  1296. expect(first.projectId).toBeNull();
  1297. expect(first.activeTaskId).toBeNull();
  1298. await newTask.click();
  1299. const second = await readDraft();
  1300. expect(second.projectId).toBeNull();
  1301. expect(second.activeTaskId).toBeNull();
  1302. expect(second.path).toBe(first.path);
  1303. const testHome = process.env.ZCODE_E2E_HOME_DIR!;
  1304. await browser.waitUntil(async () => {
  1305. const settings = JSON.parse(await readFile(join(testHome, ".zcode/v2/setting.json"), "utf8"));
  1306. return settings.lastActiveWorkspace?.workspacePath === second.path;
  1307. });
  1308. // 此场景使用内存登录夹具;刷新后沿已有真实 API key 入口恢复认证,再检查原目录。
  1309. await refreshVirtualProjectWorkspace();
  1310. await browser.waitUntil(async () => (await readDraft()).path === second.path, {
  1311. timeout: 30_000,
  1312. });
  1313. expect((await readDraft()).projectId).toBeNull();
  1314. });
  1315. it("新建空项目、修改名称、软删除后从同 roots 新建恢复", async function () {
  1316. this.timeout(120_000);
  1317. await $('[data-testid="project-section"]').waitForDisplayed();
  1318. await openLocalProjectEditor();
  1319. await $('[data-testid="virtual-project-name"]').setValue("E2E_VP04_Project");
  1320. await $('[data-testid="virtual-project-save"]').click();
  1321. const project = $('[data-project-name="E2E_VP04_Project"]');
  1322. await project.waitForDisplayed();
  1323. const projectId = await project.getAttribute("data-project-id");
  1324. await project.$('[data-testid="virtual-project-row"]').click({ button: "right" });
  1325. await $('[data-testid="virtual-project-edit"]').click();
  1326. await $('[data-testid="virtual-project-name"]').setValue("E2E_VP04_Renamed");
  1327. await $('[data-testid="virtual-project-save"]').click();
  1328. await $('[data-project-name="E2E_VP04_Renamed"]').waitForDisplayed();
  1329. await $('[role="dialog"]').waitForDisplayed({ reverse: true });
  1330. const modalState = await browser.execute(() => ({
  1331. bodyPointerEvents: getComputedStyle(document.body).pointerEvents,
  1332. dialogs: document.querySelectorAll('[role="dialog"]').length,
  1333. menus: document.querySelectorAll('[role="menu"]').length,
  1334. }));
  1335. console.info("[VP04] after project editor close", modalState);
  1336. expect(modalState.bodyPointerEvents).not.toBe("none");
  1337. await $('[data-project-name="E2E_VP04_Renamed"] [data-testid="virtual-project-row"]').click({
  1338. button: "right",
  1339. });
  1340. // 从草稿新建项目会初始化主目录;恢复必须选回实际 roots,不能再次用空 roots 比较。
  1341. const db = new DatabaseSync(
  1342. join(process.env.ZCODE_E2E_HOME_DIR!, ".zcode/v2/tasks-index.sqlite"),
  1343. { readOnly: true },
  1344. );
  1345. let restoreRoots: string[];
  1346. try {
  1347. restoreRoots = (
  1348. db
  1349. .prepare("SELECT root_path FROM project_roots WHERE project_id=? ORDER BY position")
  1350. .all(projectId) as { root_path: string }[]
  1351. ).map((row) => row.root_path);
  1352. } finally {
  1353. db.close();
  1354. }
  1355. expect(restoreRoots).toHaveLength(1);
  1356. await $('[data-testid="virtual-project-delete"]').click();
  1357. await $('[data-project-name="E2E_VP04_Renamed"]').waitForDisplayed({ reverse: true });
  1358. await openLocalProjectEditor();
  1359. await $('[data-testid="virtual-project-name"]').setValue("E2E_VP04_Restored");
  1360. for (const root of restoreRoots) await chooseProjectRoot(root);
  1361. await $('[data-testid="virtual-project-save"]').click();
  1362. await $('[data-testid="confirm-dialog-confirm"]').waitForClickable();
  1363. await $('[data-testid="confirm-dialog-confirm"]').click();
  1364. await $('[data-testid="project-folder-trust-confirm"]').waitForClickable();
  1365. await $('[data-testid="project-folder-trust-confirm"]').click();
  1366. const restored = $('[data-project-name="E2E_VP04_Restored"]');
  1367. await restored.waitForDisplayed();
  1368. expect(await restored.getAttribute("data-project-id")).toBe(projectId);
  1369. });
  1370. it("VP11:设置目录来自去重 roots,未打开的目录可以选择", async function () {
  1371. this.timeout(90_000);
  1372. const testHome = process.env.ZCODE_E2E_HOME_DIR!;
  1373. if (
  1374. ![".e2e-home-", "zcode-virtual-project-e2e-"].some((prefix) =>
  1375. basename(testHome).startsWith(prefix),
  1376. )
  1377. )
  1378. throw new Error("隔离 HOME required");
  1379. const roots = [join(testHome, "E2E_VP11_A"), join(testHome, "E2E_VP11_B")];
  1380. await Promise.all(roots.map((path) => mkdir(path, { recursive: true })));
  1381. for (const [name, paths] of [
  1382. ["E2E_VP11_MULTI", roots],
  1383. ["E2E_VP11_SHARED", roots.slice(0, 1)],
  1384. ] as const) {
  1385. await openLocalProjectEditor();
  1386. await $('[data-testid="virtual-project-name"]').setValue(name);
  1387. for (const path of paths) {
  1388. await chooseProjectRoot(path);
  1389. }
  1390. await $('[data-testid="virtual-project-save"]').click();
  1391. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  1392. await $('[data-testid="project-folder-trust-confirm"]').click();
  1393. await $(`[data-project-name="${name}"]`).waitForDisplayed();
  1394. }
  1395. const workspacePaths = () =>
  1396. browser.execute(() => {
  1397. const store = (
  1398. window as Window & {
  1399. __zcodeTabStoreE2E?: { getState(): { tabs: Array<{ workspacePath?: string }> } };
  1400. }
  1401. ).__zcodeTabStoreE2E;
  1402. return (
  1403. store
  1404. ?.getState()
  1405. .tabs.map((tab) => tab.workspacePath)
  1406. .filter(Boolean) ?? []
  1407. );
  1408. });
  1409. // 创建时可能打开主要 root A;目录选择用 root B 验证不隐式打开 tab。
  1410. expect(await workspacePaths()).not.toContain(roots[1]);
  1411. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  1412. try {
  1413. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "commands"));
  1414. const scope = $('[data-testid="plugin-settings-scope-trigger"]');
  1415. await scope.waitForDisplayed();
  1416. await scope.click();
  1417. // 项目在「本机」的「项目」子菜单里(19 号票)。
  1418. await openScopeProjectSubmenu("local");
  1419. for (const root of roots) {
  1420. const selector = `[data-testid="${testId("plugin-settings-scope-option", root)}"]`;
  1421. await $(selector).waitForDisplayed();
  1422. expect(await $$(selector).length).toBe(1);
  1423. }
  1424. await $(`[data-testid="${testId("plugin-settings-scope-option", roots[1]!)}"]`).click();
  1425. expect(await scope.getAttribute("data-plugin-scope-key")).toBe(roots[1]);
  1426. expect(await workspacePaths()).not.toContain(roots[1]);
  1427. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "hooks"));
  1428. const hooksScope = $('[data-plugin-scope-trigger="true"]');
  1429. await hooksScope.waitForDisplayed();
  1430. await hooksScope.click();
  1431. await openScopeProjectSubmenu("local");
  1432. let labels: string[] = [];
  1433. await browser.waitUntil(
  1434. async () => {
  1435. const choices = await $$('[role="menuitemradio"]');
  1436. labels = await choices.map((choice) => choice.getText());
  1437. // Bug 原因:菜单动画期间 getText 可部分为空,不能只等最后一个 root。
  1438. return ["E2E_VP11_A", "E2E_VP11_B"].every((root) =>
  1439. labels.some((label) => label.includes(root)),
  1440. );
  1441. },
  1442. { timeout: 10_000, timeoutMsg: "Hooks 目录菜单尚未显示 root 选项" },
  1443. );
  1444. expect(labels.filter((label) => label.includes("E2E_VP11_A"))).toHaveLength(1);
  1445. expect(labels.filter((label) => label.includes("E2E_VP11_B"))).toHaveLength(1);
  1446. await browser.keys("Escape");
  1447. } finally {
  1448. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  1449. }
  1450. });
  1451. it("VP10:定时表单选择空 roots 虚拟项目,选项不依赖打开目录", async function () {
  1452. this.timeout(90_000);
  1453. for (const name of ["E2E_VP10_A", "E2E_VP10_B"]) {
  1454. await openLocalProjectEditor();
  1455. await $('[data-testid="virtual-project-name"]').setValue(name);
  1456. await $('[data-testid="virtual-project-save"]').click();
  1457. await $(`[data-project-name="${name}"]`).waitForDisplayed();
  1458. }
  1459. await browser.execute(() => {
  1460. const state = window as Window & { __vpErrors?: string[] };
  1461. state.__vpErrors = [];
  1462. window.addEventListener("error", (event) =>
  1463. state.__vpErrors?.push(event.error?.stack ?? event.message),
  1464. );
  1465. window.addEventListener("unhandledrejection", (event) =>
  1466. state.__vpErrors?.push(String(event.reason?.stack ?? event.reason)),
  1467. );
  1468. });
  1469. await $(`[data-testid="${TID_AUTOMATIONS_OPEN}"]`).click();
  1470. try {
  1471. await $(`[data-testid="${TID_AUTOMATION_CREATE_MENU}"]`).waitForDisplayed();
  1472. } catch (error) {
  1473. const diagnostics = await browser.execute(() => ({
  1474. errors: (window as Window & { __vpErrors?: string[] }).__vpErrors,
  1475. body: document.body.innerText.slice(0, 6000),
  1476. }));
  1477. throw new Error(`Automations open failed: ${JSON.stringify(diagnostics)}`, { cause: error });
  1478. }
  1479. await $(`[data-testid="${TID_AUTOMATION_CREATE_MENU}"]`).click();
  1480. await clickTestIdByDom(TID_AUTOMATION_CREATE_MANUALLY);
  1481. const select = $('[data-testid="automation-project-select"]');
  1482. await select.waitForDisplayed();
  1483. await select.click();
  1484. const second = $('[role="option"][data-project-name="E2E_VP10_B"]');
  1485. await second.waitForDisplayed();
  1486. const secondId = await second.getAttribute("data-project-id");
  1487. await second.click();
  1488. expect(await select.getText()).toContain("E2E_VP10_B");
  1489. await select.click();
  1490. expect(
  1491. await $(`[role="option"][data-project-id="${secondId}"]`).getAttribute("data-state"),
  1492. ).toBe("checked");
  1493. await browser.keys("Escape");
  1494. await $(`[data-testid="${TID_AUTOMATION_FORM_TITLE}"]`).setValue("E2E_VP10_SCHEDULE");
  1495. await $(`[data-testid="${TID_AUTOMATION_FORM_PROMPT}"]`).setValue("Inspect the project");
  1496. await $(`[data-testid="${TID_AUTOMATION_SCHEDULE_ADD}"]`).click();
  1497. await clickTestIdByDom(testId(TID_AUTOMATION_FREQUENCY_OPTION, "daily"));
  1498. await browser.waitUntil(
  1499. async () => await $(`[data-testid="${TID_AUTOMATION_FORM_SUBMIT}"]`).isEnabled(),
  1500. { timeout: 15_000 },
  1501. );
  1502. await clickTestIdByDom(TID_AUTOMATION_FORM_SUBMIT);
  1503. await $(`[data-testid="${TID_AUTOMATIONS_LIST}"]`).waitForDisplayed({ timeout: 15_000 });
  1504. const testHome = process.env.ZCODE_E2E_HOME_DIR;
  1505. if (!testHome) throw new Error("isolated E2E HOME required");
  1506. const db = new DatabaseSync(join(testHome, ".zcode", "v2", "tasks-index.sqlite"), {
  1507. readOnly: true,
  1508. });
  1509. try {
  1510. const row = db
  1511. .prepare(
  1512. "SELECT project_id,host_id,workspace_path,additional_directories FROM automations WHERE title=?",
  1513. )
  1514. .get("E2E_VP10_SCHEDULE");
  1515. expect(row).toMatchObject({
  1516. project_id: secondId,
  1517. host_id: "local",
  1518. additional_directories: "[]",
  1519. });
  1520. const root = db
  1521. .prepare("SELECT root_path FROM project_roots WHERE project_id=? AND is_primary=1")
  1522. .get(secondId);
  1523. expect(row?.workspace_path).toBe(root?.root_path);
  1524. expect(String(row?.workspace_path).startsWith(join(testHome, ".zcode", "workspace"))).toBe(
  1525. true,
  1526. );
  1527. } finally {
  1528. db.close();
  1529. }
  1530. });
  1531. });
  1532. async function openLocalProjectEditor() {
  1533. await $('[data-testid="project-section"]').moveTo();
  1534. await $('[data-testid="virtual-project-add"]').click();
  1535. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  1536. }
  1537. async function chooseProjectRoot(path: string) {
  1538. await selectNativeProjectDirectories([path]);
  1539. }
  1540. async function captureProjectDialogLayouts(stage: string) {
  1541. const original = await browser.execute(() => {
  1542. const actions = (window as typeof window & { __testActions?: { getTheme(): string } })
  1543. .__testActions;
  1544. if (!actions) throw new Error("缺少主题测试入口");
  1545. return { width: innerWidth, theme: actions.getTheme() };
  1546. });
  1547. const setTheme = async (theme: string) => {
  1548. await browser.execute((value) => {
  1549. const actions = (
  1550. window as typeof window & { __testActions?: { setTheme(value: string): void } }
  1551. ).__testActions;
  1552. if (!actions) throw new Error("缺少主题测试入口");
  1553. actions.setTheme(value);
  1554. }, theme);
  1555. await browser.waitUntil(() =>
  1556. browser.execute(
  1557. (value) => document.documentElement.classList.contains(`theme-${value}`),
  1558. theme,
  1559. ),
  1560. );
  1561. };
  1562. const emulate = async (width?: number) =>
  1563. browser.electron.execute(async (electron, width) => {
  1564. const window = electron.BrowserWindow.getAllWindows().find(
  1565. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  1566. );
  1567. if (!window) throw new Error("No visible renderer");
  1568. if (!window.webContents.debugger.isAttached()) window.webContents.debugger.attach("1.3");
  1569. await window.webContents.debugger.sendCommand(
  1570. width ? "Emulation.setDeviceMetricsOverride" : "Emulation.clearDeviceMetricsOverride",
  1571. width ? { width, height: 844, deviceScaleFactor: 1, mobile: false } : {},
  1572. );
  1573. }, width);
  1574. try {
  1575. for (const width of [1200, 390]) {
  1576. // 只验证共享组件的响应式布局;真实手机 shared-host 流程仍由 VP13 单独验证。
  1577. await emulate(width);
  1578. await browser.waitUntil(() => browser.execute((expected) => innerWidth === expected, width));
  1579. for (const dark of [false, true]) {
  1580. await setTheme(dark ? "zai-dark" : "zai-light");
  1581. const fit = await browser.execute(() => {
  1582. const dialog = document.querySelector('[role="dialog"]')!;
  1583. const bounds = dialog.getBoundingClientRect();
  1584. const input = dialog.querySelector("input");
  1585. return {
  1586. left: bounds.left,
  1587. right: bounds.right,
  1588. width: innerWidth,
  1589. inputSize: input ? Number.parseFloat(getComputedStyle(input).fontSize) : null,
  1590. };
  1591. });
  1592. expect(fit.left).toBeGreaterThanOrEqual(0);
  1593. expect(fit.right).toBeLessThanOrEqual(fit.width);
  1594. if (width === 390 && fit.inputSize !== null)
  1595. expect(fit.inputSize).toBeGreaterThanOrEqual(16);
  1596. await browser.saveScreenshot(
  1597. join(
  1598. process.env.ZCODE_E2E_ARTIFACT_DIR!,
  1599. `VP19-${stage}-${width}-${dark ? "dark" : "light"}.png`,
  1600. ),
  1601. );
  1602. }
  1603. }
  1604. } finally {
  1605. await emulate();
  1606. await browser.waitUntil(() =>
  1607. browser.execute((expected) => innerWidth === expected, original.width),
  1608. );
  1609. await setTheme(original.theme);
  1610. }
  1611. }
  1612. async function refreshVirtualProjectWorkspace() {
  1613. await browser.refresh();
  1614. const login = $('[data-testid="login-use-api-key-button"]');
  1615. await browser.waitUntil(
  1616. async () =>
  1617. (await login.isDisplayed()) || (await $('[data-testid="project-section"]').isDisplayed()),
  1618. { timeout: 45_000 },
  1619. );
  1620. if (await login.isDisplayed()) await loginWithApiKey();
  1621. await $('[data-testid="project-section"]').waitForDisplayed({ timeout: 30_000 });
  1622. }