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

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