conversation-session-preinstalled-tools-faults.test.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { pinE2ELocale } from "#e2e/helpers/desktop-app";
  2. import {
  3. PREINSTALLED_FIXTURE_PROGRAM,
  4. preinstalledFixtureRecordPath,
  5. readPreinstalledEntryDefinition,
  6. } from "#e2e/helpers/preinstalled-tools-fixture";
  7. import { readFile, readdir, mkdir, stat, writeFile } from "node:fs/promises";
  8. import { join } from "node:path";
  9. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  10. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  11. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  12. interface FixtureStatus {
  13. requests: Array<{ id: number; resource: string; mode: string; range: string | null }>;
  14. pending: number[];
  15. runtimeChecks: number;
  16. }
  17. const fixtureUrl = () => process.env.ZCODE_E2E_PREINSTALL_FIXTURE_URL!;
  18. const status = async () => (await (await fetch(`${fixtureUrl()}/status`)).json()) as FixtureStatus;
  19. async function openDialog() {
  20. await $('[data-testid="workspace-help-menu-trigger"]').click();
  21. await $('[data-testid="workspace-help-menu-preinstalled-tools"]').click();
  22. await $('[data-testid="preinstalled-tools-dialog"]').waitForDisplayed();
  23. }
  24. async function waitStatus(value: string) {
  25. await browser.waitUntil(
  26. async () =>
  27. (await $(
  28. '[data-tool-id="libreoffice"] [data-testid="preinstalled-tools-status"]',
  29. ).getAttribute("data-status")) === value,
  30. { timeout: 30000, timeoutMsg: `预装状态未达到 ${value}` },
  31. );
  32. }
  33. async function terminalStatus() {
  34. await browser.waitUntil(
  35. async () =>
  36. ["ready", "failed"].includes(
  37. (await $(
  38. '[data-tool-id="libreoffice"] [data-testid="preinstalled-tools-status"]',
  39. ).getAttribute("data-status")) ?? "",
  40. ),
  41. { timeout: 30000 },
  42. );
  43. return $('[data-tool-id="libreoffice"] [data-testid="preinstalled-tools-status"]').getAttribute(
  44. "data-status",
  45. );
  46. }
  47. async function restart(scenario: string, afterExit?: () => Promise<void>) {
  48. await reloadElectronSessionPreservingBrowserProfile(browser, {
  49. afterElectronProcessExit: async () => {
  50. const response = await fetch(`${fixtureUrl()}/scenario/${scenario}`);
  51. expect(response.ok).toBe(true);
  52. await afterExit?.();
  53. },
  54. });
  55. await prepareV4ConversationE2E();
  56. // 宿主可能使用英文,环境变量不能保证 macOS 界面语言;固定语言后再核对中文文案。
  57. await pinE2ELocale("zh-CN");
  58. await openDialog();
  59. }
  60. async function screenshot(name: string) {
  61. await browser.saveScreenshot(`${process.env.ZCODE_E2E_ARTIFACT_DIR}/lop-fault-${name}.png`);
  62. }
  63. // 代理与私有 CA 需要只能经代理访问的基址,见 conversation-session-preinstalled-tools-proxy。
  64. describe("预装工具下载故障与网络策略(待审核)", () => {
  65. it("LOP-08/11/12/13: 故障不发布,重启不续传,主备候选按基址顺序回退", async function () {
  66. this.timeout(900000);
  67. await prepareV4ConversationE2E();
  68. await pinE2ELocale("zh-CN");
  69. await openDialog();
  70. expect(await terminalStatus()).toBe("failed");
  71. expect(await $('[data-testid="preinstalled-tools-dialog"]').getText()).toContain(
  72. "磁盘空间不足",
  73. );
  74. const spaceManifest = JSON.parse(
  75. await readFile(process.env.ZCODE_E2E_PREINSTALLED_TOOLS_CATALOG!, "utf8"),
  76. )[0].resources[0] as { archive: { sizeBytes: number }; installedSizeBytes: number };
  77. const requiredSpace = new Intl.NumberFormat("zh-CN", { maximumFractionDigits: 1 }).format(
  78. (spaceManifest.archive.sizeBytes + spaceManifest.installedSizeBytes) / 1024 ** 3,
  79. );
  80. expect(await $('[data-testid="preinstalled-tools-dialog"]').getText()).toContain(
  81. `需要约 ${requiredSpace} GB 可用空间`,
  82. );
  83. expect((await status()).requests).toEqual([]);
  84. expect((await status()).runtimeChecks).toBe(0);
  85. await screenshot("disk-space");
  86. const roots = join(resolveE2EStorageRoot(), "preinstalled-tools");
  87. const root = join(roots, (await readdir(roots))[0]!);
  88. await restart("unsupported");
  89. await waitStatus("not-installed");
  90. expect(await $('[data-testid="preinstalled-tools-dialog"]').getText()).toContain(
  91. "当前版本暂未提供此工具",
  92. );
  93. expect((await status()).requests).toEqual([]);
  94. await screenshot("unsupported");
  95. await restart("ready");
  96. await waitStatus("ready");
  97. const originalRecordPath = await preinstalledFixtureRecordPath(root);
  98. const original = JSON.parse(await readFile(originalRecordPath, "utf8"));
  99. const originalExecutable = await readFile(
  100. join(original.installationDir, PREINSTALLED_FIXTURE_PROGRAM),
  101. );
  102. for (const [scenario, message] of [
  103. ["network", "无法连接下载服务器"],
  104. ["interrupted", "下载中断"],
  105. ["checksum", "下载的文件已损坏"],
  106. ["truncated", "下载的文件已损坏"],
  107. ["oversize", "下载的文件已损坏"],
  108. ["extract", "解压失败"],
  109. ["missing", "下载的文件已损坏"],
  110. ["unsafe-link", "解压失败"],
  111. ["runtime", "工具无法在这台电脑上运行"],
  112. ["checksum-then-network", "下载的文件已损坏"],
  113. ] as const) {
  114. const before = await status();
  115. await restart(scenario);
  116. if (scenario === "interrupted") {
  117. await waitStatus("preparing");
  118. await browser.waitUntil(async () => (await status()).pending.length > 0, {
  119. timeout: 10000,
  120. });
  121. const pending = (await status()).pending.at(-1)!;
  122. await fetch(`${fixtureUrl()}/break/${pending}`);
  123. }
  124. expect(await terminalStatus()).toBe("failed");
  125. expect(await $('[data-testid="preinstalled-tools-dialog"]').getText()).toContain(message);
  126. await $('[data-testid="preinstalled-tools-retry"]').waitForDisplayed();
  127. // 固定发布点仍保留旧完整记录;失败不能发布本次资源或撤销旧入口。
  128. expect(JSON.parse(await readFile(originalRecordPath, "utf8"))).toEqual(original);
  129. expect(await readPreinstalledEntryDefinition(join(root, "bin"), "zcode-soffice")).toContain(
  130. original.installationDir,
  131. );
  132. expect(await readdir(join(root, "tools", "libreoffice", "staging"))).toEqual([]);
  133. expect(await readFile(join(original.installationDir, PREINSTALLED_FIXTURE_PROGRAM))).toEqual(
  134. originalExecutable,
  135. );
  136. expect((await status()).runtimeChecks - before.runtimeChecks).toBe(
  137. scenario === "runtime" ? 1 : 0,
  138. );
  139. expect(await $$("[data-sonner-toast]").length).toBe(0);
  140. await screenshot(scenario);
  141. }
  142. const fallbackBefore = (await status()).requests.length;
  143. await restart("fallback");
  144. await waitStatus("ready");
  145. expect((await status()).requests.slice(fallbackBefore).map((item) => item.mode)).toEqual([
  146. "http-error",
  147. "complete",
  148. ]);
  149. await screenshot("fallback-ready");
  150. await restart("slow");
  151. await waitStatus("preparing");
  152. await browser.waitUntil(async () => (await status()).pending.length > 0, { timeout: 10000 });
  153. const firstSlow = (await status()).requests.length;
  154. const orphan = join(root, "tools", "libreoffice", "staging", "interrupted-before-start");
  155. await restart("slow", async () => {
  156. await mkdir(orphan, { recursive: true });
  157. await writeFile(join(orphan, "partial.tar.gz"), "unfinished");
  158. await writeFile(join(root, "tools", "libreoffice", "staging", "loose.partial"), "unfinished");
  159. });
  160. await waitStatus("preparing");
  161. await browser.waitUntil(async () => (await status()).requests.length === firstSlow + 1, {
  162. timeout: 10000,
  163. });
  164. await expect(stat(orphan)).rejects.toHaveProperty("code", "ENOENT");
  165. expect((await status()).requests.at(-1)?.range).toBeNull();
  166. await $('[data-testid="preinstalled-tools-auto-install"]').click();
  167. await browser.waitUntil(
  168. async () =>
  169. (await $('[data-testid="preinstalled-tools-auto-install"]').getAttribute(
  170. "aria-checked",
  171. )) === "false",
  172. { timeout: 10000 },
  173. );
  174. const beforeOffRestart = (await status()).requests.length;
  175. await restart("slow");
  176. await waitStatus("not-installed");
  177. expect((await status()).requests.length).toBe(beforeOffRestart);
  178. expect(await readdir(join(root, "tools", "libreoffice", "staging"))).toEqual([]);
  179. // fallback 已装上旧资源,目标换成 slow 后卡片显示“可更新”,按钮是“更新”而不是“下载”。
  180. await $('[data-testid="preinstalled-tools-update"]').click();
  181. await waitStatus("preparing");
  182. await browser.waitUntil(async () => (await status()).pending.length > 0, { timeout: 10000 });
  183. const slowId = (await status()).pending.at(-1)!;
  184. const progress = $('[data-testid="preinstalled-tools-dialog"] [role="progressbar"]');
  185. await browser.waitUntil(async () => Number(await progress.getAttribute("aria-valuenow")) > 0, {
  186. timeout: 10000,
  187. });
  188. const firstProgress = Number(await progress.getAttribute("aria-valuenow"));
  189. await fetch(`${fixtureUrl()}/step/${slowId}`);
  190. await browser.waitUntil(
  191. async () => Number(await progress.getAttribute("aria-valuenow")) > firstProgress,
  192. { timeout: 10000 },
  193. );
  194. await screenshot("slow-progress");
  195. await $('[data-testid="preinstalled-tools-cancel"]').click();
  196. await waitStatus("not-installed");
  197. });
  198. });