help-client-config.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import { readFile, writeFile, rm } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { readSettings, seedSettings, waitForDefaultWorkspaceReady } from "./helpers/desktop-app.js";
  4. import { writeE2EJsonFileAtomically } from "./helpers/e2e-atomic-json-file.js";
  5. import {
  6. buildHelpBrowserFixture,
  7. readHelpFixture,
  8. startHelpConfigFixture,
  9. } from "./helpers/help-client-config-fixture.js";
  10. type DesktopBridge = {
  11. executeDesktopCommand(command: string): Promise<void>;
  12. canOpenCommunity(locale: "zh-CN" | "en-US"): Promise<boolean>;
  13. setApplicationLocale(locale: "zh-CN" | "en-US"): Promise<void>;
  14. getDeviceId(): Promise<string>;
  15. };
  16. async function command(command: string) {
  17. await browser.execute(async (value) => {
  18. await (window as unknown as { zcode: DesktopBridge }).zcode.executeDesktopCommand(value);
  19. }, command);
  20. }
  21. async function available(locale: "zh-CN" | "en-US") {
  22. return browser.execute(
  23. async (value) => (window as unknown as { zcode: DesktopBridge }).zcode.canOpenCommunity(value),
  24. locale,
  25. );
  26. }
  27. async function english() {
  28. await browser.execute(async () => {
  29. await (window as unknown as { zcode: DesktopBridge }).zcode.setApplicationLocale("en-US");
  30. });
  31. }
  32. describe("帮助配置 client/configs", () => {
  33. let originalSettings: Awaited<ReturnType<typeof readSettings>>;
  34. let localPath: string;
  35. let originalLocal: string | undefined;
  36. let fixture: Awaited<ReturnType<typeof readHelpFixture>>;
  37. let server: Awaited<ReturnType<typeof startHelpConfigFixture>>;
  38. let external: Awaited<ReturnType<typeof browser.electron.mock>>;
  39. before(async () => {
  40. await waitForDefaultWorkspaceReady(30000);
  41. originalSettings = await readSettings();
  42. fixture = await readHelpFixture();
  43. const appPath = await browser.electron.execute((electron) => electron.app.getAppPath());
  44. // E2E 必须只改 worker 的隔离默认配置,绝不写开发者的真实安装目录。
  45. if (!appPath.includes(".e2e-cache")) throw new Error(`Unexpected E2E app path: ${appPath}`);
  46. localPath = join(appPath, "../../config/default.json");
  47. originalLocal = await readFile(localPath, "utf8").catch(() => undefined);
  48. // Main 的 setApplicationLocale 只更新原生菜单,不修改 Renderer 的持久语言。
  49. // 先为隔离副本设置界面语言再加载,避免中文系统下用英文选择器误报帮助入口缺失。
  50. await seedSettings({ locale: "en-US", localePreference: "en-US" });
  51. await browser.refresh();
  52. await waitForDefaultWorkspaceReady(30000);
  53. });
  54. beforeEach(async () => {
  55. await english();
  56. await writeE2EJsonFileAtomically(localPath, fixture.local);
  57. external = await browser.electron.mock("shell", "openExternal");
  58. await external.mockResolvedValue(undefined);
  59. server = await startHelpConfigFixture(fixture.remote);
  60. await seedSettings({ zcodeEndpointOrigin: server.origin });
  61. });
  62. afterEach(async () => {
  63. await browser.keys("Escape");
  64. await browser.electron.restoreAllMocks();
  65. await seedSettings({ zcodeEndpointOrigin: originalSettings.zcodeEndpointOrigin });
  66. await server?.close();
  67. });
  68. after(async () => {
  69. if (originalLocal === undefined) await rm(localPath, { force: true });
  70. else await writeFile(localPath, originalLocal, "utf8");
  71. await seedSettings(originalSettings);
  72. await browser.execute(async (locale) => {
  73. await (window as unknown as { zcode: DesktopBridge }).zcode.setApplicationLocale(locale);
  74. }, originalSettings.locale ?? "en-US");
  75. });
  76. async function expectExternal(url: string) {
  77. await browser.waitUntil(
  78. async () => {
  79. try {
  80. await expect(external).toHaveBeenCalledWith(url);
  81. return true;
  82. } catch {
  83. return false;
  84. }
  85. },
  86. { timeout: 10000, timeoutMsg: `未打开外链 ${url}` },
  87. );
  88. }
  89. it("HC-01: 真实帮助菜单、语言与成功缓存", async () => {
  90. expect(await available("en-US")).toBe(true);
  91. await $('button[aria-label="Help"]').click();
  92. await $('//*[@role="menuitem" and contains(.,"User community")]').click();
  93. await expectExternal(fixture.remote.community_urls!["en-US"]!);
  94. expect(await available("zh-CN")).toBe(true);
  95. await browser.execute(async () => {
  96. await (window as unknown as { zcode: DesktopBridge }).zcode.setApplicationLocale("zh-CN");
  97. });
  98. await command("openCommunity");
  99. await expectExternal(fixture.remote.community_urls!["zh-CN"]!);
  100. // 同一端点也被 Host Provider Config 拉取(带 x-request-id);缓存断言只统计 Main 的帮助请求。
  101. const helpRequests = server.requests.filter((request) => !request.headers["x-request-id"]);
  102. expect(helpRequests).toHaveLength(1);
  103. const query = new URL(helpRequests[0]!.url, server.origin).searchParams;
  104. expect(query.get("app_version")).toBeTruthy();
  105. expect(query.get("platform")).toBe(`${process.platform}-${process.arch}`);
  106. expect(helpRequests[0]!.headers.authorization).toBeUndefined();
  107. });
  108. it("HC-01-copy-device-mid: 真实帮助菜单复制当前设备 MID", async () => {
  109. const expected = await browser.execute(async () => {
  110. return (window as unknown as { zcode: DesktopBridge }).zcode.getDeviceId();
  111. });
  112. await $('button[aria-label="Help"]').click();
  113. await $('[role="menuitem"]*=Copy device MID').click();
  114. await browser.waitUntil(
  115. async () =>
  116. (await browser.electron.execute((electron) => electron.clipboard.readText())) === expected,
  117. { timeout: 10_000, timeoutMsg: "系统剪贴板没有收到当前设备 MID" },
  118. );
  119. });
  120. it("HC-02: 英文缺失只回退英文内置值", async () => {
  121. server.setConfig({ community_urls: { "zh-CN": fixture.remote.community_urls!["zh-CN"] } });
  122. expect(await available("en-US")).toBe(true);
  123. await command("openCommunity");
  124. await expectExternal(fixture.local.community_urls!["en-US"]!);
  125. });
  126. it("HC-03: false 覆盖本地 true 并显示弹窗;新 endpoint 的 true 打开表单", async () => {
  127. await command("openFeedback");
  128. await $('[role="dialog"]').waitForDisplayed({ timeout: 10000 });
  129. await expect($('[role="dialog"]')).toHaveText(expect.stringContaining("Submit feedback"));
  130. if (process.platform === "linux") {
  131. const overlayTop = await browser.execute(() => {
  132. const overlay = document.querySelector<HTMLElement>('[data-slot="dialog-overlay"]');
  133. if (!overlay) throw new Error("反馈弹窗遮罩不存在");
  134. return overlay.getBoundingClientRect().top;
  135. });
  136. expect(overlayTop).toBe(0);
  137. }
  138. await expect(external).not.toHaveBeenCalled();
  139. await browser.keys("Escape");
  140. const other = await startHelpConfigFixture({
  141. ...fixture.remote,
  142. feedback_use_external_form: true,
  143. });
  144. try {
  145. await seedSettings({ zcodeEndpointOrigin: other.origin });
  146. await command("openFeedback");
  147. await expectExternal(fixture.remote.feedback_url!);
  148. expect(other.requests).toHaveLength(1);
  149. } finally {
  150. await other.close();
  151. }
  152. });
  153. for (const failure of ["http", "business", "json"] as const) {
  154. it(`HC-04-${failure}: 失败回退、不缓存失败、同 endpoint 恢复`, async () => {
  155. server.setFailure(failure);
  156. expect(await available("en-US")).toBe(true);
  157. await command("openCommunity");
  158. await expectExternal(fixture.local.community_urls!["en-US"]!);
  159. expect(server.requests.length).toBeGreaterThanOrEqual(2);
  160. server.setConfig(fixture.remote);
  161. await command("openCommunity");
  162. await expectExternal(fixture.remote.community_urls!["en-US"]!);
  163. });
  164. }
  165. it("HC-04-empty: 远端和内置均无当前语言时平台不可用", async () => {
  166. await writeE2EJsonFileAtomically(localPath, {});
  167. server.setConfig({});
  168. expect(await available("en-US")).toBe(false);
  169. expect(await available("zh-CN")).toBe(false);
  170. });
  171. it("HC-05: 窄屏 Chromium Web 解析、并发缓存与页面重载重新请求", async () => {
  172. const webServer = await startHelpConfigFixture(fixture.remote, await buildHelpBrowserFixture());
  173. const mainHandle = await browser.getWindowHandle();
  174. const existing = await browser.getWindowHandles();
  175. const id = await browser.electron.execute(async (electron, url) => {
  176. const win = new electron.BrowserWindow({
  177. width: 390,
  178. height: 844,
  179. show: false,
  180. webPreferences: { sandbox: true, nodeIntegration: false },
  181. });
  182. await win.loadURL(url);
  183. return win.id;
  184. }, webServer.origin);
  185. try {
  186. await browser.waitUntil(
  187. async () => (await browser.getWindowHandles()).length > existing.length,
  188. { timeout: 10000 },
  189. );
  190. const handle = (await browser.getWindowHandles()).find((item) => !existing.includes(item))!;
  191. await browser.switchToWindow(handle);
  192. const read = async () =>
  193. browser.execute(async () => {
  194. const help = (
  195. window as unknown as {
  196. helpFixture: {
  197. resolveWebCommunityUrl(
  198. locale: string,
  199. options: { endpointOrigin: string },
  200. ): Promise<string>;
  201. };
  202. }
  203. ).helpFixture;
  204. return Promise.all(
  205. ["zh-CN", "en-US"].map((locale) =>
  206. help.resolveWebCommunityUrl(locale, { endpointOrigin: location.origin }),
  207. ),
  208. );
  209. });
  210. expect(await read()).toEqual([
  211. fixture.remote.community_urls!["zh-CN"],
  212. fixture.remote.community_urls!["en-US"],
  213. ]);
  214. expect(webServer.requests).toHaveLength(1);
  215. expect(
  216. new URL(webServer.requests[0]!.url, webServer.origin).searchParams.has("platform"),
  217. ).toBe(false);
  218. webServer.setConfig({ community_urls: { "en-US": "https://example.com/E2E_WEB_CHANGED" } });
  219. expect((await read())[1]).toBe(fixture.remote.community_urls!["en-US"]);
  220. await browser.refresh();
  221. expect((await read())[1]).toBe("https://example.com/E2E_WEB_CHANGED");
  222. expect(webServer.requests).toHaveLength(2);
  223. } finally {
  224. await browser.electron.execute(
  225. (electron, windowId) => electron.BrowserWindow.fromId(windowId)?.destroy(),
  226. id,
  227. );
  228. await browser.switchToWindow(mainHandle);
  229. await webServer.close();
  230. }
  231. });
  232. });