help-menu-about.test.ts 12 KB

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