help-menu-about.test.ts 12 KB

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