project-native-directory-picker.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import { mkdir, rm } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. DEFAULT_WORKSPACE,
  5. waitForDefaultWorkspaceReady,
  6. waitForWorkspaceApp,
  7. } from "#e2e/helpers/desktop-app";
  8. import { selectNativeProjectDirectories } from "#e2e/helpers/project-sidebar";
  9. import { ServiceChannels } from "@zcode/shared";
  10. import type { VirtualProject } from "@zcode/services";
  11. import {
  12. installHandoffRpcProbe,
  13. callHandoffHost,
  14. restoreHandoffProbes,
  15. } from "#e2e/helpers/remote-project-handoff-probe";
  16. type ThemeWindow = typeof window & {
  17. __testActions?: {
  18. getTheme(): string;
  19. setTheme(theme: string): void;
  20. getLocale(): "zh-CN" | "en-US";
  21. setLocale(locale: "zh-CN" | "en-US"): void;
  22. };
  23. };
  24. describe("本地项目原生多目录选择", () => {
  25. const root = join(DEFAULT_WORKSPACE, ".zcode-e2e", "native-project-picker");
  26. const paths = ["one", "two", "three"].map((name) => join(root, name));
  27. const project = '[data-project-name="E2E_NATIVE_PROJECT_PICKER"]';
  28. before(async () => {
  29. await waitForDefaultWorkspaceReady(30_000);
  30. await Promise.all(paths.map((path) => mkdir(path, { recursive: true })));
  31. await installHandoffRpcProbe();
  32. });
  33. after(async () => {
  34. await browser.electron.restoreAllMocks();
  35. await restoreHandoffProbes();
  36. await rm(root, { recursive: true, force: true });
  37. });
  38. it("NDP01/NDP02/PRO01: 多目录新项目排首位,刷新与重开后保留", async () => {
  39. const readProjectOrder = () =>
  40. browser.execute(() =>
  41. [...document.querySelectorAll('[data-testid="project-section"] [data-project-name]')].map(
  42. (element) => element.getAttribute("data-project-name"),
  43. ),
  44. );
  45. const previousOrder = await readProjectOrder();
  46. expect(previousOrder.length).toBeGreaterThan(0);
  47. await $('[data-testid="project-section"]').moveTo();
  48. await $('[data-testid="virtual-project-add"]').click();
  49. await $('[data-testid="virtual-project-name"]').setValue("E2E_NATIVE_PROJECT_PICKER");
  50. await selectNativeProjectDirectories(paths.slice(0, 2));
  51. expect(await $$('[data-testid="virtual-project-root-row"]').length).toBe(2);
  52. await $$('[data-testid="virtual-project-root-row"]')[1]!
  53. .$('[data-testid="virtual-project-set-primary"]')
  54. .click();
  55. await selectNativeProjectDirectories([paths[1]!, paths[2]!]);
  56. expect(await $$('[data-testid="virtual-project-root-row"]').length).toBe(3);
  57. await selectNativeProjectDirectories([]);
  58. expect(await $$('[data-testid="virtual-project-root-row"]').length).toBe(3);
  59. expect(
  60. await $$('[data-testid="virtual-project-root-row"]')[1]!
  61. .$('[data-testid="virtual-project-primary"]')
  62. .isExisting(),
  63. ).toBe(true);
  64. // PCFT01/02/03:确认前读取真实 Host,取消不能留下项目或改写草稿。
  65. const readSaved = () =>
  66. callHandoffHost<VirtualProject[]>(ServiceChannels.Project, "readProjects");
  67. const before = await readSaved();
  68. for (const action of ["cancel", "close", "escape", "outside"]) {
  69. await $('[data-testid="virtual-project-save"]').click();
  70. const dialog = $('[data-testid="project-folder-trust-dialog"]');
  71. await dialog.waitForDisplayed();
  72. expect(
  73. await $$('[data-testid="project-folder-trust-path"]').map((row) => row.getText()),
  74. ).toEqual(paths);
  75. expect(await readSaved()).toEqual(before);
  76. if (action === "cancel") {
  77. expect(
  78. await browser.execute(() => document.activeElement?.getAttribute("data-testid")),
  79. ).toBe("project-folder-trust-cancel");
  80. await browser.keys("Enter");
  81. } else if (action === "close") {
  82. await dialog.$('[data-slot="dialog-close"]').click();
  83. } else if (action === "escape") {
  84. await browser.keys("Escape");
  85. } else {
  86. await browser.action("pointer").move({ x: 8, y: 8 }).down().up().perform();
  87. }
  88. await dialog.waitForExist({ reverse: true });
  89. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(
  90. "E2E_NATIVE_PROJECT_PICKER",
  91. );
  92. expect(await $$('[data-testid="virtual-project-root-row"]').length).toBe(3);
  93. await browser.waitUntil(() =>
  94. browser.execute(
  95. () => document.activeElement?.getAttribute("data-testid") === "virtual-project-save",
  96. ),
  97. );
  98. expect(await readSaved()).toEqual(before);
  99. }
  100. await $('[data-testid="virtual-project-save"]').click();
  101. await $('[data-testid="project-folder-trust-dialog"]').waitForDisplayed();
  102. // Electron 没有 Browser.getWindowForTarget,窗口尺寸通过真实 BrowserWindow 调整。
  103. const windowSize = await browser.electron.execute((electron) => {
  104. const appWindow = electron.BrowserWindow.getAllWindows()[0]!;
  105. return { bounds: appWindow.getBounds(), minimum: appWindow.getMinimumSize() };
  106. });
  107. const trustViewport = await browser.execute(() => ({ width: innerWidth, height: innerHeight }));
  108. const trustTheme = await browser.execute(() =>
  109. (window as ThemeWindow).__testActions!.getTheme(),
  110. );
  111. const trustLocale = await browser.execute(() =>
  112. (window as ThemeWindow).__testActions!.getLocale(),
  113. );
  114. try {
  115. for (const width of [1200, 390]) {
  116. await browser.execute(
  117. (viewportWidth) =>
  118. (window as ThemeWindow).__testActions!.setLocale(
  119. viewportWidth === 1200 ? "en-US" : "zh-CN",
  120. ),
  121. width,
  122. );
  123. await browser.electron.execute((electron, nextWidth) => {
  124. const appWindow = electron.BrowserWindow.getAllWindows()[0]!;
  125. appWindow.setMinimumSize(320, 480);
  126. appWindow.setSize(nextWidth, 844);
  127. }, width);
  128. await browser.waitUntil(() =>
  129. browser.execute((nextWidth) => innerWidth === nextWidth, width),
  130. );
  131. for (const theme of ["zai-light", "zai-dark"]) {
  132. await browser.execute(
  133. (value) => (window as ThemeWindow).__testActions!.setTheme(value),
  134. theme,
  135. );
  136. await waitForTrustLayout({ width, height: 844 });
  137. const geometry = await browser.execute(() => {
  138. const button = document.querySelector('[data-testid="project-folder-trust-confirm"]')!;
  139. const box = button.getBoundingClientRect();
  140. return {
  141. visible:
  142. box.left >= 0 &&
  143. box.right <= innerWidth &&
  144. box.top >= 0 &&
  145. box.bottom <= innerHeight,
  146. hit: button.contains(
  147. document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2),
  148. ),
  149. };
  150. });
  151. expect(geometry).toEqual({ visible: true, hit: true });
  152. expect(await $('[data-testid="project-folder-trust-dialog"]').getText()).toContain(
  153. width === 1200 ? "This computer" : "此电脑",
  154. );
  155. await browser.saveScreenshot(
  156. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `PCFT-trust-${width}-${theme}.png`),
  157. );
  158. }
  159. }
  160. } finally {
  161. await browser.electron.execute((electron, previous) => {
  162. const appWindow = electron.BrowserWindow.getAllWindows()[0]!;
  163. appWindow.setBounds(previous.bounds);
  164. appWindow.setMinimumSize(previous.minimum[0]!, previous.minimum[1]!);
  165. }, windowSize);
  166. await browser.execute(
  167. (value) => (window as ThemeWindow).__testActions!.setTheme(value),
  168. trustTheme,
  169. );
  170. await browser.execute(
  171. (locale) => (window as ThemeWindow).__testActions!.setLocale(locale),
  172. trustLocale,
  173. );
  174. }
  175. // 原生 resize 返回时弹窗尺寸过渡仍会移动按钮;等待实际布局收口,避免单次点击落空。
  176. await waitForTrustLayout(trustViewport);
  177. expect(
  178. await browser.execute(() =>
  179. document
  180. .getAnimations()
  181. .filter((animation) => {
  182. const dialog = document.querySelector('[data-testid="project-folder-trust-dialog"]');
  183. const target = (animation.effect as KeyframeEffect | null)?.target;
  184. return (
  185. animation.playState === "running" &&
  186. animation instanceof CSSTransition &&
  187. /^(max-)?(width|height)$|^transform$/.test(animation.transitionProperty) &&
  188. target instanceof Element &&
  189. dialog &&
  190. (dialog.contains(target) || target.contains(dialog))
  191. );
  192. })
  193. .map((animation) => (animation as CSSTransition).transitionProperty),
  194. ),
  195. ).toEqual([]);
  196. await $('[data-testid="project-folder-trust-confirm"]').click();
  197. await $('[data-testid="virtual-project-name"]').waitForExist({ reverse: true });
  198. expect(
  199. (await readSaved())
  200. .find((item) => item.name === "E2E_NATIVE_PROJECT_PICKER")
  201. ?.roots.map((item) => item.rootPath),
  202. ).toEqual(paths);
  203. // 窄屏布局会自动收起侧栏;还原尺寸后通过真实入口展开,再检查项目顺序。
  204. if (!(await $('[data-testid="project-section"]').isDisplayed())) {
  205. await $('button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]').click();
  206. }
  207. await $(project).waitForDisplayed();
  208. expect(await readProjectOrder()).toEqual(["E2E_NATIVE_PROJECT_PICKER", ...previousOrder]);
  209. await browser.refresh();
  210. // 创建项目已激活所选主要目录;刷新仍等待旧夹具目录会把正确恢复误报成导航失败。
  211. await waitForWorkspaceApp(paths[1]!, 30_000);
  212. await $(project).waitForDisplayed();
  213. expect(await readProjectOrder()).toEqual(["E2E_NATIVE_PROJECT_PICKER", ...previousOrder]);
  214. await $(project).$('[data-testid="virtual-project-menu"]').click();
  215. await $('[data-testid="virtual-project-edit"]').click();
  216. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  217. const rows = await $$('[data-testid="virtual-project-root-name"]');
  218. expect(await rows.map((row) => row.getAttribute("title"))).toEqual(paths);
  219. expect(
  220. await $$('[data-testid="virtual-project-root-row"]')[1]!
  221. .$('[data-testid="virtual-project-primary"]')
  222. .isExisting(),
  223. ).toBe(true);
  224. const originalTheme = await browser.execute(() =>
  225. (window as ThemeWindow).__testActions!.getTheme(),
  226. );
  227. try {
  228. for (const theme of ["zai-light", "zai-dark"]) {
  229. await browser.execute(
  230. (value) => (window as ThemeWindow).__testActions!.setTheme(value),
  231. theme,
  232. );
  233. await browser.waitUntil(() =>
  234. browser.execute(
  235. (value) => document.documentElement.classList.contains(`theme-${value}`),
  236. theme,
  237. ),
  238. );
  239. await browser.saveScreenshot(
  240. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `native-project-${theme}.png`),
  241. );
  242. }
  243. } finally {
  244. await browser.execute(
  245. (value) => (window as ThemeWindow).__testActions!.setTheme(value),
  246. originalTheme,
  247. );
  248. }
  249. await browser.keys("Escape");
  250. await $('[data-testid="virtual-project-name"]').waitForExist({ reverse: true });
  251. await $(project).$('[data-testid="virtual-project-menu"]').click();
  252. await $('[data-testid="virtual-project-delete"]').click();
  253. await $(project).waitForExist({ reverse: true });
  254. });
  255. });
  256. async function waitForTrustLayout(viewport: { width: number; height: number }): Promise<void> {
  257. await browser.waitUntil(
  258. () =>
  259. browser.execute((expected) => {
  260. const dialog = document.querySelector('[data-testid="project-folder-trust-dialog"]');
  261. if (!dialog || innerWidth !== expected.width || innerHeight !== expected.height)
  262. return false;
  263. return !document.getAnimations().some((animation) => {
  264. const target = (animation.effect as KeyframeEffect | null)?.target;
  265. return (
  266. animation.playState === "running" &&
  267. animation instanceof CSSTransition &&
  268. /^(max-)?(width|height)$|^transform$/.test(animation.transitionProperty) &&
  269. target instanceof Element &&
  270. (dialog.contains(target) || target.contains(dialog))
  271. );
  272. });
  273. }, viewport),
  274. { timeout: 10_000, timeoutMsg: "信任弹窗视口或布局过渡尚未完成" },
  275. );
  276. }