help-menu-about.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { readFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import {
  5. TID_WORKSPACE_HELP_MENU_TRIGGER,
  6. TID_TASK_SETTINGS_BUTTON,
  7. TID_SETTINGS_PAGE,
  8. PlatformChannels,
  9. type UpdateStatePayload,
  10. type UpdateCheckResultPayload,
  11. } from "@zcode/shared";
  12. import {
  13. DEFAULT_WORKSPACE,
  14. clickTestIdByWebDriver,
  15. waitForWorkspaceApp,
  16. seedSettings,
  17. readSettings,
  18. } from "./helpers/desktop-app.js";
  19. import { startHelpConfigFixture } from "./helpers/help-client-config-fixture.js";
  20. // Node 侧 shared 常量没有 renderer 的编译 define,不能据此跳过 production 分支。
  21. // 默认正式套件构建 Preview;production 用显式参数独立验证,不能静默跳过。
  22. const expectedFlavor = process.env.ZCODE_E2E_HELP_MENU_FLAVOR ?? "preview";
  23. if (expectedFlavor !== "production" && expectedFlavor !== "preview") {
  24. throw new Error("请设置 ZCODE_E2E_HELP_MENU_FLAVOR=production 或 preview,并构建对应产品身份");
  25. }
  26. const production = expectedFlavor === "production";
  27. async function enterWorkspace() {
  28. // 隔离 HOME 首次启动与刷新都可能显示引导,使用产品支持的 Escape 退出。
  29. await browser.waitUntil(
  30. async () => {
  31. if (await $('[data-testid="onboarding-page"]').isDisplayed()) await browser.keys("Escape");
  32. return $(`[data-testid="${TID_TASK_SETTINGS_BUTTON}"]`).isExisting();
  33. },
  34. { timeout: 30_000, timeoutMsg: "首次使用引导关闭后未进入工作区" },
  35. );
  36. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30_000);
  37. }
  38. async function publishState(state: UpdateStatePayload) {
  39. await browser.electron.execute(
  40. (electron, channel, payload) => {
  41. for (const window of electron.BrowserWindow.getAllWindows()) {
  42. if (window.webContents.getURL().includes("/renderer/index.html")) {
  43. window.webContents.send(channel, payload);
  44. }
  45. }
  46. },
  47. PlatformChannels.UpdateStateChanged,
  48. state,
  49. );
  50. }
  51. async function menuLabels() {
  52. return $$('[role="menuitem"]').map((item) => item.getText());
  53. }
  54. async function openMenu() {
  55. await browser.waitUntil(
  56. async () => {
  57. for (const trigger of await $$(`[data-testid="${TID_WORKSPACE_HELP_MENU_TRIGGER}"]`)) {
  58. if (await trigger.isDisplayed()) return true;
  59. }
  60. return false;
  61. },
  62. { timeout: 10_000, timeoutMsg: "帮助按钮尚未挂载到可见页面" },
  63. );
  64. const triggers = await $$(`[data-testid="${TID_WORKSPACE_HELP_MENU_TRIGGER}"]`);
  65. for (const trigger of triggers) {
  66. if (await trigger.isDisplayed()) {
  67. await trigger.waitForClickable();
  68. await trigger.click();
  69. break;
  70. }
  71. }
  72. await $('[role="menu"]').waitForDisplayed();
  73. await $('[role="menuitem"][aria-busy="true"]').waitForExist({ reverse: true });
  74. }
  75. async function closeMenu() {
  76. await browser.keys("Escape");
  77. await $('[role="menu"]').waitForDisplayed({ reverse: true });
  78. }
  79. async function setTheme(theme: "zai-light" | "zai-dark") {
  80. await browser.execute((value) => {
  81. const actions = (
  82. window as typeof window & { __testActions?: { setTheme?: (theme: string) => void } }
  83. ).__testActions;
  84. if (!actions?.setTheme) throw new Error("缺少主题测试入口");
  85. actions.setTheme(value);
  86. }, theme);
  87. }
  88. async function assertLogExport(label: string, pendingLabel: string) {
  89. // 只拦截系统文件浏览器,保留菜单、preload、IPC 和主进程真实打包链路。
  90. const reveal = await browser.electron.mock("shell", "showItemInFolder");
  91. await reveal.mockReturnValue(undefined);
  92. try {
  93. await $(`[role="menuitem"]*=${label}`).click();
  94. await $('[role="menu"]').waitForDisplayed({ reverse: true });
  95. await browser.waitUntil(
  96. async () => {
  97. await reveal.update();
  98. return reveal.mock.calls.length === 1;
  99. },
  100. { timeout: 30_000, timeoutMsg: "点击导出日志后未生成归档并请求系统定位" },
  101. );
  102. const archivePath = String(reveal.mock.calls[0]?.[0]);
  103. expect(archivePath).toMatch(/zcode-logs-[^/\\]+\.zip$/);
  104. const archive = await readFile(archivePath);
  105. expect(archive.subarray(0, 4).toString("hex")).toBe("504b0304");
  106. await browser.waitUntil(
  107. async () => !(await $("#zcode-toast-host").getText()).includes(pendingLabel),
  108. { timeout: 10_000, timeoutMsg: "日志导出完成后提示未关闭" },
  109. );
  110. } finally {
  111. await reveal.mockRestore();
  112. }
  113. }
  114. async function assertAboutWindow() {
  115. try {
  116. await browser.waitUntil(
  117. async () =>
  118. browser.electron.execute(async (electron) => {
  119. const window = electron.BrowserWindow.getAllWindows().find(
  120. (candidate) =>
  121. candidate.webContents.getURL().startsWith("data:text/html") &&
  122. decodeURIComponent(candidate.webContents.getURL()).includes('id="about-title"'),
  123. );
  124. if (!window?.isVisible()) return false;
  125. const title = await window.webContents.executeJavaScript(
  126. 'document.querySelector("#about-title")?.textContent',
  127. );
  128. return (
  129. typeof title === "string" &&
  130. title.includes("ZCode") &&
  131. title.includes(electron.app.getVersion())
  132. );
  133. }),
  134. { timeout: 10_000, timeoutMsg: "关于窗口未显示应用名称和版本" },
  135. );
  136. } finally {
  137. await browser.electron.execute((electron) => {
  138. for (const window of electron.BrowserWindow.getAllWindows()) {
  139. if (
  140. window.webContents.getURL().startsWith("data:text/html") &&
  141. decodeURIComponent(window.webContents.getURL()).includes('id="about-title"')
  142. )
  143. window.close();
  144. }
  145. });
  146. }
  147. }
  148. describe(`问号菜单应用入口(${expectedFlavor})`, () => {
  149. let originalSettings: Awaited<ReturnType<typeof readSettings>>;
  150. let helpConfig: Awaited<ReturnType<typeof startHelpConfigFixture>>;
  151. before(async () => {
  152. await enterWorkspace();
  153. originalSettings = await readSettings();
  154. // 动态漏洞入口由配置决定;固定本地配置,避免远端配置或加载占位影响菜单顺序断言。
  155. helpConfig = await startHelpConfigFixture({});
  156. await seedSettings({
  157. locale: "en-US",
  158. localePreference: "en-US",
  159. zcodeEndpointOrigin: helpConfig.origin,
  160. });
  161. await browser.refresh();
  162. await enterWorkspace();
  163. });
  164. afterEach(async () => {
  165. if (await $('[role="menu"]').isDisplayed()) await closeMenu();
  166. await publishState({ kind: "idle", enabled: true });
  167. });
  168. after(async () => {
  169. try {
  170. await seedSettings(originalSettings);
  171. } finally {
  172. await helpConfig?.close();
  173. }
  174. });
  175. it("HM-01 英文草稿菜单顺序、导出日志和关于窗口", async function () {
  176. this.timeout(60_000);
  177. await setTheme("zai-light");
  178. await openMenu();
  179. const labels = await menuLabels();
  180. expect(labels).toEqual([
  181. "Product docs",
  182. "User community",
  183. "Report an issue",
  184. "Request a feature",
  185. "Export logs",
  186. "Resource manager",
  187. ...(production ? ["Check for updates"] : []),
  188. "About ZCode",
  189. ]);
  190. expect(await $$('[role="menu"] [role="separator"]')).toHaveLength(1);
  191. await browser.saveScreenshot(join(tmpdir(), "zcode-help-export-en-light.png"));
  192. await assertLogExport("Export logs", "Exporting logs...");
  193. await openMenu();
  194. await $('[role="menuitem"]*=About ZCode').click();
  195. await assertAboutWindow();
  196. });
  197. it("HM-02 更新状态事件、禁用状态与关闭重开", async function () {
  198. this.timeout(60_000);
  199. await openMenu();
  200. if (!production) {
  201. await publishState({ kind: "update-downloaded", enabled: true, version: "99.0.0" });
  202. expect((await menuLabels()).some((label) => label.includes("Restart to update"))).toBe(false);
  203. expect(await menuLabels()).not.toContain("Check for updates");
  204. await closeMenu();
  205. return;
  206. }
  207. for (const [state, label] of [
  208. [{ kind: "checking", enabled: false }, "Checking for updates..."],
  209. [{ kind: "update-available", enabled: true, version: "99.0.0" }, "Update available 99.0.0"],
  210. [{ kind: "download-progress", enabled: true, progress: "42%" }, "Downloading update... 42%"],
  211. [{ kind: "update-downloaded", enabled: true, version: "99.0.0" }, "Restart to update"],
  212. ] as const) {
  213. await publishState(state);
  214. const item = $(`[role="menuitem"]*=${label}`);
  215. await item.waitForDisplayed();
  216. // 下载完成后动作文案与版本 pill 分开渲染,避免依赖 WebDriver 的子节点空白拼接。
  217. if (state.kind === "update-downloaded") {
  218. await expect(item.$('[data-slot="badge"]')).toHaveText(state.version);
  219. }
  220. if (!state.enabled) await expect(item).toHaveAttribute("aria-disabled", "true");
  221. else expect(await item.getAttribute("aria-disabled")).not.toBe("true");
  222. }
  223. await closeMenu();
  224. await openMenu();
  225. const restartItem = $('[role="menuitem"]*=Restart to update');
  226. await expect(restartItem).toBeDisplayed();
  227. await expect(restartItem.$('[data-slot="badge"]')).toHaveText("99.0.0");
  228. await closeMenu();
  229. await publishState({ kind: "idle", enabled: true });
  230. });
  231. it("HM-03 production 真实检查命令收到开发包回执,Preview 无入口", async function () {
  232. this.timeout(60_000);
  233. await openMenu();
  234. if (!production) {
  235. expect(await menuLabels()).not.toContain("Check for updates");
  236. await closeMenu();
  237. return;
  238. }
  239. // 真实命令只在未打包的隔离 E2E 中执行,避免触发安装包的下载或安装。
  240. expect(await browser.electron.execute((electron) => electron.app.isPackaged)).toBe(false);
  241. await browser.execute(() => {
  242. const target = window as unknown as {
  243. zcode: {
  244. onUpdateCheckResult(callback: (payload: UpdateCheckResultPayload) => void): () => void;
  245. };
  246. __helpUpdateResult?: UpdateCheckResultPayload;
  247. __helpUpdateDispose?: () => void;
  248. };
  249. target.__helpUpdateResult = undefined;
  250. target.__helpUpdateDispose = target.zcode.onUpdateCheckResult((payload) => {
  251. target.__helpUpdateResult = payload;
  252. });
  253. });
  254. try {
  255. await $('[role="menuitem"]*=Check for updates').click();
  256. await browser.waitUntil(
  257. async () =>
  258. (await browser.execute(
  259. () =>
  260. (window as unknown as { __helpUpdateResult?: UpdateCheckResultPayload })
  261. .__helpUpdateResult?.kind,
  262. )) === "dev-skipped",
  263. { timeout: 10_000, timeoutMsg: "检查更新未收到真实 main 的开发包回执" },
  264. );
  265. } finally {
  266. await browser.execute(() => {
  267. const target = window as unknown as {
  268. __helpUpdateDispose?: () => void;
  269. __helpUpdateResult?: UpdateCheckResultPayload;
  270. };
  271. target.__helpUpdateDispose?.();
  272. delete target.__helpUpdateDispose;
  273. delete target.__helpUpdateResult;
  274. });
  275. }
  276. });
  277. it("HM-04 中文设置页的导出日志、关于及更新入口", async function () {
  278. this.timeout(60_000);
  279. await seedSettings({ locale: "zh-CN", localePreference: "zh-CN" });
  280. await browser.refresh();
  281. await enterWorkspace();
  282. await setTheme("zai-dark");
  283. await clickTestIdByWebDriver(TID_TASK_SETTINGS_BUTTON);
  284. await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).waitForDisplayed();
  285. await openMenu();
  286. const labels = await menuLabels();
  287. expect(labels).toEqual([
  288. "产品文档",
  289. "用户社群",
  290. "问题上报",
  291. "给产品提需求",
  292. "导出日志",
  293. "资源管理器",
  294. ...(production ? ["检查更新"] : []),
  295. "关于 ZCode",
  296. ]);
  297. expect(await $$('[role="menu"] [role="separator"]')).toHaveLength(1);
  298. await browser.saveScreenshot(join(tmpdir(), "zcode-help-export-zh-dark.png"));
  299. await assertLogExport("导出日志", "正在导出日志中");
  300. await openMenu();
  301. await $('[role="menuitem"]*=关于 ZCode').click();
  302. await assertAboutWindow();
  303. });
  304. });