help-client-config.test.ts 11 KB

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