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

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