conversation-session-virtual-project-mentions.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import { execFile } from "node:child_process";
  2. import { promisify } from "node:util";
  3. import { selectNativeProjectDirectories } from "#e2e/helpers/project-sidebar";
  4. import { basename, join } from "node:path";
  5. import { DatabaseSync } from "node:sqlite";
  6. import { mkdir, writeFile } from "node:fs/promises";
  7. import {
  8. TID_V4_COMPOSER_INPUT,
  9. TID_V4_COMPOSER_SEND,
  10. TID_COMPOSER_WORKSPACE_TRIGGER,
  11. TID_PROMPT_SUGGESTION_PANEL,
  12. TID_TASK_ITEM,
  13. TID_CONFIRM_DIALOG_CONFIRM,
  14. testId,
  15. } from "@zcode/shared/test-ids";
  16. import {
  17. clearAppData,
  18. setInputValueByTestIdDom,
  19. waitForWorkspaceApp,
  20. DEFAULT_WORKSPACE,
  21. } from "#e2e/helpers/desktop-app";
  22. describe("虚拟项目 Composer 候选", () => {
  23. after(async () => {
  24. await clearAppData();
  25. });
  26. it("VP14:多 root 文件分别可选,# 在全局草稿显示已有项目任务", async () => {
  27. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
  28. const home = process.env.ZCODE_E2E_HOME_DIR!;
  29. // 同时接受统一 runner 与旧手工入口的隔离 HOME,禁止写入日常用户目录。
  30. if (
  31. !home ||
  32. ![".e2e-home-", "zcode-virtual-project-e2e-"].some((prefix) =>
  33. basename(home).startsWith(prefix),
  34. )
  35. )
  36. throw new Error("隔离 HOME required");
  37. const roots = [join(home, "E2E_VP14_A"), join(home, "E2E_VP14_B")];
  38. for (const root of roots) {
  39. await mkdir(join(root, "src"), { recursive: true });
  40. await writeFile(join(root, "src", "same.ts"), "export const same = 1;\n");
  41. }
  42. await promisify(execFile)("git", ["init", "--initial-branch=main", roots[0]!]);
  43. const initialProject = await $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`).getText();
  44. expect(await $('[data-testid="composer-edit-project"]').isExisting()).toBe(false);
  45. await openComposerProjectEditor();
  46. await $('[data-testid="virtual-project-name"]').setValue("E2E_COMPOSER_CANCELLED");
  47. await $('//button[normalize-space(.)="Cancel" or normalize-space(.)="取消"]').click();
  48. await $('[data-testid="virtual-project-name"]').waitForDisplayed({ reverse: true });
  49. expect(await $('[data-project-name="E2E_COMPOSER_CANCELLED"]').isExisting()).toBe(false);
  50. expect(await $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`).getText()).toBe(
  51. initialProject,
  52. );
  53. await openComposerProjectEditor();
  54. await $('[data-testid="virtual-project-name"]').setValue("E2E_VP14_PROJECT");
  55. for (const root of roots) {
  56. await chooseProjectRoot(root);
  57. }
  58. await $('[data-testid="virtual-project-save"]').click();
  59. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  60. await $('[data-testid="project-folder-trust-confirm"]').click();
  61. const project = $('[data-project-name="E2E_VP14_PROJECT"]');
  62. await project.waitForDisplayed();
  63. // PCD01:在草稿创建项目成功后自动选中新项目,取消仍保持原选择。
  64. await browser.waitUntil(async () =>
  65. (await $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`).getText()).includes(
  66. "E2E_VP14_PROJECT",
  67. ),
  68. );
  69. await project.$('[data-testid="virtual-project-create-task"]').click();
  70. const input = $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`);
  71. await input.waitForDisplayed();
  72. const workspaceTrigger = $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`);
  73. for (const theme of ["zai-light", "zai-dark"]) {
  74. await browser.execute(
  75. (theme) =>
  76. (
  77. window as Window & { __testActions?: { setTheme(theme: string): void } }
  78. ).__testActions!.setTheme(theme),
  79. theme,
  80. );
  81. const toggle = project.$('[data-testid="virtual-project-toggle"]');
  82. await toggle.$(".lucide-folders-open").waitForExist();
  83. await project.saveScreenshot(
  84. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `VP14-folders-open-${theme}.png`),
  85. );
  86. await toggle.click();
  87. await toggle.$(".lucide-folders").waitForExist();
  88. await project.saveScreenshot(
  89. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `VP14-folders-closed-${theme}.png`),
  90. );
  91. await toggle.click();
  92. await workspaceTrigger.$(".lucide-folders").waitForExist();
  93. await workspaceTrigger.click();
  94. const menu = $('[data-testid="composer-project-menu"]');
  95. await menu.$('[data-project-name="E2E_VP14_PROJECT"] .lucide-folders').waitForDisplayed();
  96. await menu.saveScreenshot(
  97. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `VP14-folders-composer-${theme}.png`),
  98. );
  99. await browser.keys("Escape");
  100. await menu.waitForDisplayed({ reverse: true });
  101. const edit = $('[data-testid="composer-edit-project"]');
  102. await edit.waitForDisplayed();
  103. await $('[data-branch-switcher-primary-icon="true"]').waitForDisplayed();
  104. const placement = await browser.execute(() => {
  105. const button = document.querySelector('[data-testid="composer-edit-project"]')!;
  106. const branch = button.parentElement!.querySelector(
  107. '[data-branch-switcher-primary-icon="true"]',
  108. )!.parentElement!;
  109. return {
  110. branchRight: branch.getBoundingClientRect().right,
  111. editLeft: button.getBoundingClientRect().left,
  112. };
  113. });
  114. expect(placement.editLeft).toBeGreaterThanOrEqual(placement.branchRight);
  115. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "E2E_COMPOSER_EDIT_DRAFT");
  116. await browser.saveScreenshot(
  117. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `VP14-composer-edit-${theme}.png`),
  118. );
  119. await edit.click();
  120. const name = $('[data-testid="virtual-project-name"]');
  121. await name.waitForDisplayed();
  122. expect(await name.getValue()).toBe("E2E_VP14_PROJECT");
  123. await browser.saveScreenshot(
  124. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `VP14-project-editor-${theme}.png`),
  125. );
  126. await name.setValue("E2E_EDIT_CANCELLED");
  127. await $('//button[normalize-space(.)="Cancel" or normalize-space(.)="取消"]').click();
  128. await name.waitForDisplayed({ reverse: true });
  129. expect(await workspaceTrigger.getText()).toContain("E2E_VP14_PROJECT");
  130. if (theme === "zai-light") {
  131. const originalId = await project.getAttribute("data-project-id");
  132. await edit.click();
  133. await name.setValue("E2E_VP14_EDITED");
  134. await $('[data-testid="virtual-project-save"]').click();
  135. await name.waitForDisplayed({ reverse: true });
  136. const renamed = $('[data-project-name="E2E_VP14_EDITED"]');
  137. await renamed.waitForDisplayed();
  138. expect(await renamed.getAttribute("data-project-id")).toBe(originalId);
  139. expect(await workspaceTrigger.getText()).toContain("E2E_VP14_EDITED");
  140. expect(await input.getText()).toBe("E2E_COMPOSER_EDIT_DRAFT");
  141. await edit.click();
  142. await name.setValue("E2E_VP14_PROJECT");
  143. await $('[data-testid="virtual-project-save"]').click();
  144. await name.waitForDisplayed({ reverse: true });
  145. await project.waitForDisplayed();
  146. }
  147. expect(await input.getText()).toBe("E2E_COMPOSER_EDIT_DRAFT");
  148. }
  149. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "@same.ts", {
  150. stabilizeLexicalCaretAtEnd: true,
  151. });
  152. const panel = $(`[data-testid="${TID_PROMPT_SUGGESTION_PANEL}"]`);
  153. await panel.waitForDisplayed();
  154. for (const root of roots) {
  155. const option = panel.$(`[data-option-id="file:${join(root, "src", "same.ts")}"]`);
  156. await option.waitForDisplayed();
  157. expect(await option.getText()).toContain(basename(root));
  158. }
  159. const readMarkdown = () =>
  160. browser.execute(
  161. (testId) =>
  162. (
  163. document.querySelector(`[data-testid="${testId}"]`) as HTMLElement & {
  164. __zcodeLexicalInputE2E?: { getText(): string };
  165. }
  166. )?.__zcodeLexicalInputE2E?.getText(),
  167. TID_V4_COMPOSER_INPUT,
  168. );
  169. await panel.$(`[data-option-id="file:${join(roots[0]!, "src", "same.ts")}"]`).click();
  170. await browser.waitUntil(
  171. async () => (await readMarkdown())?.includes("[same.ts](./src/same.ts)") ?? false,
  172. );
  173. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "@same.ts", {
  174. stabilizeLexicalCaretAtEnd: true,
  175. });
  176. await panel.waitForDisplayed();
  177. const second = panel.$(`[data-option-id="file:${join(roots[1]!, "src", "same.ts")}"]`);
  178. await second.click();
  179. expect(await input.$('[data-mention-category="files"]').getAttribute("data-mention-id")).toBe(
  180. `file:${join(roots[1]!, "src", "same.ts")}`,
  181. );
  182. expect(await readMarkdown()).toContain(`[same.ts](${join(roots[1]!, "src", "same.ts")})`);
  183. await setInputValueByTestIdDom(
  184. TID_V4_COMPOSER_INPUT,
  185. "E2E_VP14_HISTORY: Reply with E2E_VP14_READY.",
  186. );
  187. await $(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).click();
  188. await $('//*[normalize-space(.)="E2E_VP14_READY" and not(*)]').waitForDisplayed({
  189. timeout: 60_000,
  190. });
  191. const taskId = await browser.execute(() => {
  192. const state = (
  193. window as Window & {
  194. __zcodeSessionStoreE2E?: {
  195. getState(): { workspaces: Record<string, { activeTaskId?: string | null }> };
  196. };
  197. }
  198. ).__zcodeSessionStoreE2E?.getState();
  199. return (
  200. Object.values(state?.workspaces ?? {}).find((workspace) => workspace.activeTaskId)
  201. ?.activeTaskId ?? null
  202. );
  203. });
  204. expect(taskId).toBeTruthy();
  205. // 顶部新建继承当前项目;这里显式进入未归类草稿,才能覆盖跨项目 # 候选。
  206. await $('[data-testid="virtual-project-new-task"]').click();
  207. await input.waitForDisplayed();
  208. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "#", {
  209. stabilizeLexicalCaretAtEnd: true,
  210. });
  211. await panel.waitForDisplayed();
  212. await panel.$(`[data-option-id="session:${taskId}"]`).waitForDisplayed();
  213. expect(await panel.getText()).toContain("E2E_VP14_PROJECT");
  214. await browser.saveScreenshot(
  215. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP14-project-mentions.png"),
  216. );
  217. // # 候选验证结束后清空查询;只按 Escape 会在项目切换恢复草稿时再次弹出候选并遮住项目入口。
  218. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "");
  219. await panel.waitForDisplayed({ reverse: true });
  220. await openLocalProjectEditor();
  221. await $('[data-testid="virtual-project-name"]').setValue("E2E_VP15_TARGET");
  222. await chooseProjectRoot(roots[1]!);
  223. await $('[data-testid="virtual-project-save"]').click();
  224. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  225. await $('[data-testid="project-folder-trust-confirm"]').click();
  226. const destination = $('[data-project-name="E2E_VP15_TARGET"]');
  227. await destination.waitForDisplayed();
  228. // 创建完成先发布目录再关闭信任/编辑器;等待遮罩退出,避免点击被旧弹窗截获。
  229. await $('[data-slot="dialog-overlay"]').waitForExist({ reverse: true });
  230. // PCD01 会跨 root 切换草稿;列表出现并不表示新 workspace 的 Composer 已接管。
  231. await waitForWorkspaceApp(roots[1]!, 30000);
  232. const destinationTrigger = $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`);
  233. await browser.waitUntil(async () =>
  234. (await destinationTrigger.getText()).includes("E2E_VP15_TARGET"),
  235. );
  236. await destinationTrigger.waitForClickable();
  237. await destinationTrigger.click();
  238. const projectMenu = $('[data-testid="composer-project-menu"]');
  239. await projectMenu.$('[data-project-name="E2E_VP15_TARGET"] .lucide-folder').waitForDisplayed();
  240. await projectMenu
  241. .$('[data-project-name="E2E_VP14_PROJECT"] .lucide-folders')
  242. .waitForDisplayed();
  243. await browser.keys("Escape");
  244. await projectMenu.waitForDisplayed({ reverse: true });
  245. const targetId = await destination.getAttribute("data-project-id");
  246. const sourceId = await project.getAttribute("data-project-id");
  247. const row = project.$(`[data-testid="${testId(TID_TASK_ITEM, taskId!)}"]`);
  248. await row.waitForDisplayed();
  249. // 只观察原生拖动事件,不在测试里直接发组织命令或写 dataTransfer。
  250. await browser.execute(() => {
  251. const trace: unknown[] = [];
  252. (window as Window & { __vp15DragTrace?: unknown[] }).__vp15DragTrace = trace;
  253. for (const name of ["dragstart", "dragenter", "dragover", "drop", "dragend"]) {
  254. document.addEventListener(name, (event) => {
  255. const e = event as DragEvent;
  256. if (trace.length < 100)
  257. trace.push({
  258. type: e.type,
  259. allowed: e.dataTransfer?.effectAllowed,
  260. effect: e.dataTransfer?.dropEffect,
  261. project: (e.target as HTMLElement)
  262. .closest?.("[data-project-id]")
  263. ?.getAttribute("data-project-id"),
  264. });
  265. });
  266. }
  267. });
  268. const readOwnership = () => {
  269. const db = new DatabaseSync(join(home, ".zcode", "v2", "tasks-index.sqlite"), {
  270. readOnly: true,
  271. });
  272. try {
  273. return {
  274. task: db
  275. .prepare("SELECT project_id,workspace_path FROM tasks WHERE task_id=?")
  276. .get(taskId!),
  277. roots: db
  278. .prepare("SELECT root_path FROM project_roots WHERE project_id=? ORDER BY position")
  279. .all(targetId!),
  280. };
  281. } finally {
  282. db.close();
  283. }
  284. };
  285. const confirm = $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`);
  286. const rowSelector = `[data-testid="${testId(TID_TASK_ITEM, taskId!)}"]`;
  287. const targetSelector = '[data-project-name="E2E_VP15_TARGET"]';
  288. const sourceSelector = '[data-project-name="E2E_VP14_PROJECT"]';
  289. try {
  290. for (const theme of ["zai-light", "zai-dark"]) {
  291. await browser.execute(
  292. (theme) =>
  293. (
  294. window as Window & { __testActions?: { setTheme(theme: string): void } }
  295. ).__testActions!.setTheme(theme),
  296. theme,
  297. );
  298. const before = await destination.getSize();
  299. await hoverSessionOnProject(rowSelector, sourceSelector);
  300. const sourceIndicator = project.$('[data-testid="project-session-drop-target"]');
  301. await sourceIndicator.waitForDisplayed();
  302. expect((await sourceIndicator.getSize()).height).toBeGreaterThan(40);
  303. await moveSessionPointer(`${sourceSelector} [data-testid="virtual-project-toggle"]`);
  304. await sourceIndicator.waitForDisplayed();
  305. await browser.saveScreenshot(
  306. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `VP15-project-drop-${theme}.png`),
  307. );
  308. await project.saveScreenshot(
  309. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `VP15-project-drop-panel-${theme}.png`),
  310. );
  311. await moveSessionPointer(`${targetSelector} [data-testid="virtual-project-toggle"]`);
  312. await destination.$('[data-testid="project-session-drop-target"]').waitForDisplayed();
  313. expect(await sourceIndicator.isExisting()).toBe(false);
  314. expect(await destination.getSize()).toEqual(before);
  315. // WebDriver 的 Escape 不会取消原生拖拽;离开项目再松手,避免误触发落点确认。
  316. await moveSessionPointer('[data-testid="task-new-button"]');
  317. await $('[data-testid="project-session-drop-target"]').waitForExist({ reverse: true });
  318. await browser.releaseActions();
  319. await $('[data-testid="project-session-drop-target"]').waitForExist({ reverse: true });
  320. expect(readOwnership().task).toEqual({ project_id: sourceId, workspace_path: roots[0] });
  321. }
  322. await row.dragAndDrop(destination.$('[data-testid="virtual-project-toggle"]'), {
  323. duration: 700,
  324. });
  325. await confirm.waitForDisplayed({ timeout: 8_000 });
  326. expect(await $('[data-testid="project-session-drop-target"]').isExisting()).toBe(false);
  327. await browser.keys("Escape");
  328. await confirm.waitForDisplayed({ reverse: true });
  329. expect(readOwnership()).toEqual({
  330. task: { project_id: sourceId, workspace_path: roots[0] },
  331. roots: [{ root_path: roots[1] }],
  332. });
  333. await row.dragAndDrop(destination.$('[data-testid="virtual-project-toggle"]'), {
  334. duration: 700,
  335. });
  336. await confirm.waitForDisplayed();
  337. await confirm.click();
  338. await destination.$(`[data-testid="${testId(TID_TASK_ITEM, taskId!)}"]`).waitForDisplayed();
  339. expect(readOwnership()).toEqual({
  340. task: { project_id: targetId, workspace_path: roots[0] },
  341. roots: [{ root_path: roots[1] }, { root_path: roots[0] }],
  342. });
  343. // 确认框退出动画仍会接收指针;等它退出后再开始下一次真实拖拽。
  344. await confirm.waitForDisplayed({ reverse: true });
  345. await hoverSessionOnProject(`${targetSelector} ${rowSelector}`, sourceSelector);
  346. await project.$('[data-testid="project-session-drop-target"]').waitForDisplayed();
  347. await browser.performActions([
  348. {
  349. type: "pointer",
  350. id: "session-project-drag",
  351. parameters: { pointerType: "mouse" },
  352. actions: [{ type: "pointerUp", button: 0 }],
  353. },
  354. ]);
  355. await row.waitForDisplayed();
  356. expect(readOwnership().task).toEqual({ project_id: sourceId, workspace_path: roots[0] });
  357. expect(await $('[data-testid="project-session-drop-target"]').isExisting()).toBe(false);
  358. await row.click();
  359. await $('//*[normalize-space(.)="E2E_VP14_READY" and not(*)]').waitForDisplayed();
  360. await browser.saveScreenshot(
  361. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "VP15-project-move.png"),
  362. );
  363. } finally {
  364. await browser.releaseActions();
  365. process.stderr.write(
  366. `VP15 native drag: ${JSON.stringify(await browser.execute(() => (window as Window & { __vp15DragTrace?: unknown[] }).__vp15DragTrace))}\n`,
  367. );
  368. }
  369. });
  370. });
  371. async function openLocalProjectEditor() {
  372. await $('[data-testid="project-section"]').moveTo();
  373. await $('[data-testid="virtual-project-add"]').click();
  374. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  375. }
  376. async function openComposerProjectEditor() {
  377. await $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`).click();
  378. const menu = $('[data-testid="composer-project-menu"]');
  379. const create = menu.$('[data-testid="composer-create-project"]');
  380. expect(await create.getText()).toMatch(/^(创建项目|Create project)$/);
  381. await create.click();
  382. await menu.waitForDisplayed({ reverse: true });
  383. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  384. }
  385. async function chooseProjectRoot(path: string) {
  386. await selectNativeProjectDirectories([path]);
  387. }
  388. async function moveSessionPointer(selector: string) {
  389. const point = await browser.execute((selector) => {
  390. const r = document.querySelector(selector)!.getBoundingClientRect();
  391. return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };
  392. }, selector);
  393. await browser.performActions([
  394. {
  395. type: "pointer",
  396. id: "session-project-drag",
  397. parameters: { pointerType: "mouse" },
  398. actions: [{ type: "pointerMove", ...point, duration: 350 }],
  399. },
  400. ]);
  401. // 首次进入仅触发 dragenter;第二次真实位移触发 dragover,让浏览器采用目标的 move 效果。
  402. await browser.performActions([
  403. {
  404. type: "pointer",
  405. id: "session-project-drag",
  406. parameters: { pointerType: "mouse" },
  407. actions: [{ type: "pointerMove", x: point.x + 1, y: point.y, duration: 0 }],
  408. },
  409. ]);
  410. }
  411. async function hoverSessionOnProject(source: string, target: string) {
  412. await browser.releaseActions();
  413. const point = await browser.execute((selector) => {
  414. const r = document.querySelector(selector)!.getBoundingClientRect();
  415. return { x: Math.round(r.left + 60), y: Math.round(r.top + r.height / 2) };
  416. }, source);
  417. await browser.performActions([
  418. {
  419. type: "pointer",
  420. id: "session-project-drag",
  421. parameters: { pointerType: "mouse" },
  422. actions: [
  423. { type: "pointerMove", ...point, duration: 0 },
  424. { type: "pointerDown", button: 0 },
  425. { type: "pointerMove", x: point.x + 10, y: point.y, duration: 100 },
  426. ],
  427. },
  428. ]);
  429. await moveSessionPointer(`${target} [data-testid="virtual-project-toggle"]`);
  430. }