conversation-session-preinstalled-tools-controls.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import { preinstalledFixtureRecordPath } from "#e2e/helpers/preinstalled-tools-fixture";
  2. import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  5. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  6. import { setPluginPresentation } from "#e2e/helpers/plugin-management-lifecycle";
  7. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  8. const fixtureUrl = () => process.env.ZCODE_E2E_PREINSTALL_FIXTURE_URL!;
  9. const fixtureStatus = async () =>
  10. (await fetch(`${fixtureUrl()}/status`)).json() as Promise<{
  11. requests: number;
  12. pending: number;
  13. runtimeChecks: number;
  14. lateWrites: number;
  15. }>;
  16. async function openDialog() {
  17. await $('[data-testid="workspace-help-menu-trigger"]').click();
  18. await $('[data-testid="workspace-help-menu-preinstalled-tools"]').click();
  19. await $('[data-testid="preinstalled-tools-dialog"]').waitForDisplayed();
  20. }
  21. async function waitStatus(status: string) {
  22. await browser.waitUntil(
  23. async () =>
  24. (await $(
  25. '[data-tool-id="libreoffice"] [data-testid="preinstalled-tools-status"]',
  26. ).getAttribute("data-status")) === status,
  27. { timeout: 30000, timeoutMsg: `预装状态未达到 ${status}` },
  28. );
  29. }
  30. async function toggleAuto(enabled: boolean) {
  31. const toggle = $('[data-testid="preinstalled-tools-auto-install"]');
  32. await toggle.waitForDisplayed();
  33. if ((await toggle.getAttribute("aria-checked")) !== String(enabled)) await toggle.click();
  34. await browser.waitUntil(
  35. async () =>
  36. (await toggle.getAttribute("aria-checked")) === String(enabled) && (await toggle.isEnabled()),
  37. { timeout: 10000 },
  38. );
  39. }
  40. async function repeatPrepare() {
  41. const result = await browser.executeAsync((done: (error: string | null) => void) => {
  42. const api = (
  43. window as typeof window & {
  44. zcode: {
  45. executePreinstalledToolsCommand(command: {
  46. type: "prepare";
  47. toolId: string;
  48. }): Promise<void>;
  49. };
  50. }
  51. ).zcode;
  52. void Promise.all(
  53. Array.from({ length: 4 }, () =>
  54. api.executePreinstalledToolsCommand({ type: "prepare", toolId: "libreoffice" }),
  55. ),
  56. ).then(
  57. () => done(null),
  58. (error) => done(String(error)),
  59. );
  60. });
  61. expect(result).toBeNull();
  62. }
  63. async function visualMatrix(phase: string) {
  64. // 仅用现有展示动作设置语言和主题;不改预装状态、操作归属或安装事实。
  65. for (const locale of ["zh-CN", "en-US"] as const)
  66. for (const theme of ["zai-dark", "zai-light"] as const) {
  67. await setPluginPresentation({ locale, theme, width: 1000, height: 760 });
  68. await browser.waitUntil(
  69. async () =>
  70. (await $('[data-testid="preinstalled-tools-dialog"]').getText()).includes(
  71. locale === "zh-CN" ? "自动预装" : "Automatic preinstall",
  72. ),
  73. { timeout: 10000 },
  74. );
  75. await assertDialogFits();
  76. await browser.saveScreenshot(
  77. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/lop-controls-${phase}-${locale}-${theme}.png`,
  78. );
  79. }
  80. await setPluginPresentation({ locale: "en-US", theme: "zai-light", width: 760, height: 640 });
  81. await assertDialogFits();
  82. await browser.saveScreenshot(
  83. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/lop-controls-${phase}-small.png`,
  84. );
  85. await setPluginPresentation({ locale: "zh-CN", theme: "zai-dark", width: 1000, height: 760 });
  86. await browser.waitUntil(
  87. async () =>
  88. browser.execute(() => {
  89. const dialog = document.querySelector('[data-testid="preinstalled-tools-dialog"]');
  90. return (
  91. dialog
  92. ?.getAnimations({ subtree: true })
  93. .every(
  94. (animation) =>
  95. animation.effect?.getComputedTiming().iterations === Infinity ||
  96. animation.playState === "finished" ||
  97. animation.playState === "idle",
  98. ) ?? false
  99. );
  100. }),
  101. { timeout: 10000 },
  102. );
  103. }
  104. async function emulateMotion(value?: "reduce" | "no-preference") {
  105. await browser.electron.execute(async (electron, preference) => {
  106. const window = electron.BrowserWindow.getAllWindows().find(
  107. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  108. );
  109. if (!window) throw new Error("没有可见的预装工具窗口");
  110. if (!window.webContents.debugger.isAttached()) window.webContents.debugger.attach("1.3");
  111. await window.webContents.debugger.sendCommand("Emulation.setEmulatedMedia", {
  112. features: preference ? [{ name: "prefers-reduced-motion", value: preference }] : [],
  113. });
  114. }, value);
  115. }
  116. async function assertDialogFits() {
  117. const layout = await browser.execute(() => {
  118. const dialog = document.querySelector<HTMLElement>(
  119. '[data-testid="preinstalled-tools-dialog"]',
  120. )!;
  121. const rect = dialog.getBoundingClientRect();
  122. return {
  123. scrollWidth: dialog.scrollWidth,
  124. width: dialog.clientWidth,
  125. left: rect.left,
  126. right: rect.right,
  127. top: rect.top,
  128. bottom: rect.bottom,
  129. viewportWidth: innerWidth,
  130. viewportHeight: innerHeight,
  131. };
  132. });
  133. expect(layout.scrollWidth).toBeLessThanOrEqual(layout.width + 1);
  134. expect(layout.left).toBeGreaterThanOrEqual(0);
  135. expect(layout.right).toBeLessThanOrEqual(layout.viewportWidth + 1);
  136. expect(layout.top).toBeGreaterThanOrEqual(0);
  137. expect(layout.bottom).toBeLessThanOrEqual(layout.viewportHeight + 1);
  138. }
  139. describe("预装工具完整控制(待审核)", () => {
  140. it("LOP-03/04/06/07/09/10/14/15: 偏好、取消、重试与可访问对话框", async function () {
  141. this.timeout(360000);
  142. await prepareV4ConversationE2E();
  143. await openDialog();
  144. await waitStatus("preparing");
  145. await $('[data-testid="preinstalled-tools-auto-install"]').execute((element) =>
  146. element.focus(),
  147. );
  148. await browser.keys("Space");
  149. await browser.waitUntil(
  150. async () =>
  151. (await $('[data-testid="preinstalled-tools-auto-install"]').getAttribute(
  152. "aria-checked",
  153. )) === "false",
  154. { timeout: 10000 },
  155. );
  156. await repeatPrepare();
  157. expect((await fixtureStatus()).requests).toBe(1);
  158. await waitStatus("preparing");
  159. await $('[data-testid="preinstalled-tools-cancel"]').click();
  160. await waitStatus("not-installed");
  161. const roots = join(resolveE2EStorageRoot(), "preinstalled-tools");
  162. const root = join(roots, (await readdir(roots))[0]!);
  163. const recordPath = await preinstalledFixtureRecordPath(root);
  164. await expect(stat(recordPath)).rejects.toHaveProperty("code", "ENOENT");
  165. expect(await readdir(join(root, "tools", "libreoffice", "staging"))).toEqual([]);
  166. await visualMatrix("not-installed");
  167. await browser.keys("Escape");
  168. await $('[data-testid="preinstalled-tools-dialog"]').waitForDisplayed({ reverse: true });
  169. await reloadElectronSessionPreservingBrowserProfile(browser);
  170. await prepareV4ConversationE2E();
  171. await openDialog();
  172. await waitStatus("not-installed");
  173. expect(
  174. await $('[data-testid="preinstalled-tools-auto-install"]').getAttribute("aria-checked"),
  175. ).toBe("false");
  176. expect((await fixtureStatus()).requests).toBe(1);
  177. await $('[data-testid="preinstalled-tools-download"]').click();
  178. await waitStatus("preparing");
  179. await browser.waitUntil(async () => (await fixtureStatus()).requests === 2, { timeout: 10000 });
  180. await repeatPrepare();
  181. expect((await fixtureStatus()).requests).toBe(2);
  182. // 使用公开平台命令紧邻提交取消和重试,不写 owner、store 或私有 Promise。
  183. await browser.execute(async () => {
  184. const api = (
  185. window as typeof window & {
  186. zcode: {
  187. executePreinstalledToolsCommand(command: {
  188. type: "cancel" | "prepare";
  189. toolId: string;
  190. }): Promise<void>;
  191. };
  192. }
  193. ).zcode;
  194. await Promise.all([
  195. api.executePreinstalledToolsCommand({ type: "cancel", toolId: "libreoffice" }),
  196. api.executePreinstalledToolsCommand({ type: "prepare", toolId: "libreoffice" }),
  197. ]);
  198. });
  199. await browser.waitUntil(async () => (await fixtureStatus()).requests === 3, { timeout: 10000 });
  200. await fetch(`${fixtureUrl()}/release-request/2`);
  201. expect((await fixtureStatus()).lateWrites).toBe(1);
  202. await waitStatus("preparing");
  203. await expect(stat(recordPath)).rejects.toHaveProperty("code", "ENOENT");
  204. await visualMatrix("downloading");
  205. await fetch(`${fixtureUrl()}/break-request/3`);
  206. await waitStatus("failed");
  207. expect(await $('[data-testid="preinstalled-tools-dialog"]').getText()).toContain(
  208. "下载中断,请重试。",
  209. );
  210. await visualMatrix("failed");
  211. await $('[data-testid="preinstalled-tools-retry"]').click();
  212. await browser.waitUntil(async () => (await fixtureStatus()).requests === 4, { timeout: 10000 });
  213. await fetch(`${fixtureUrl()}/release-request/4`);
  214. await browser.waitUntil(
  215. async () =>
  216. (await $(
  217. '[data-tool-id="libreoffice"] [data-testid="preinstalled-tools-status"]',
  218. ).getAttribute("data-phase")) === "checking",
  219. { timeout: 30000 },
  220. );
  221. await visualMatrix("checking");
  222. // 动画类存在并不代表位置会变;缺少定位时 left 动画曾静止在 35%。
  223. const indicatorX = () =>
  224. browser.execute(
  225. () =>
  226. document
  227. .querySelector(
  228. '[data-testid="preinstalled-tools-dialog"] [data-slot="progress-indicator"]',
  229. )!
  230. .getBoundingClientRect().x,
  231. );
  232. await emulateMotion("no-preference");
  233. const initialX = await indicatorX();
  234. await browser.waitUntil(async () => Math.abs((await indicatorX()) - initialX) > 2, {
  235. timeout: 4000,
  236. interval: 50,
  237. timeoutMsg: "检查阶段的滚动指示条没有移动",
  238. });
  239. await writeFile(
  240. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "lop-indeterminate-motion.json"),
  241. JSON.stringify({ phase: "checking", initialX, movedX: await indicatorX() }),
  242. );
  243. try {
  244. await emulateMotion("reduce");
  245. const reduced = await browser.execute(() => ({
  246. media: matchMedia("(prefers-reduced-motion: reduce)").matches,
  247. animation: getComputedStyle(
  248. document.querySelector(
  249. '[data-testid="preinstalled-tools-dialog"] [data-slot="progress-indicator"]',
  250. )!,
  251. ).animationName,
  252. }));
  253. expect(reduced).toEqual({ media: true, animation: "none" });
  254. } finally {
  255. await emulateMotion();
  256. }
  257. expect(
  258. await $('[data-testid="preinstalled-tools-dialog"] [role="progressbar"]').getAttribute(
  259. "aria-valuenow",
  260. ),
  261. ).toBeNull();
  262. await fetch(`${fixtureUrl()}/finish-check`);
  263. await waitStatus("ready");
  264. await visualMatrix("ready");
  265. // 发布后到达的取消只能读取已就绪结果,不能撤销记录。
  266. await browser.execute(async () => {
  267. await (
  268. window as typeof window & {
  269. zcode: {
  270. executePreinstalledToolsCommand(command: {
  271. type: "cancel";
  272. toolId: string;
  273. }): Promise<void>;
  274. };
  275. }
  276. ).zcode.executePreinstalledToolsCommand({ type: "cancel", toolId: "libreoffice" });
  277. });
  278. await waitStatus("ready");
  279. const record = JSON.parse(await readFile(recordPath, "utf8"));
  280. expect(await stat(record.installationDir)).toBeDefined();
  281. expect(
  282. await $('[data-testid="preinstalled-tools-auto-install"]').getAttribute("aria-checked"),
  283. ).toBe("false");
  284. expect(await $$("[data-sonner-toast]").length).toBe(0);
  285. await browser.keys("Escape");
  286. await reloadElectronSessionPreservingBrowserProfile(browser, {
  287. afterElectronProcessExit: async () => {
  288. await rm(recordPath);
  289. await rm(record.installationDir, { recursive: true, force: true });
  290. },
  291. });
  292. await fetch(`${fixtureUrl()}/hold`);
  293. await fetch(`${fixtureUrl()}/hold-check`);
  294. await prepareV4ConversationE2E();
  295. await openDialog();
  296. await waitStatus("not-installed");
  297. await toggleAuto(true);
  298. await waitStatus("preparing");
  299. await browser.waitUntil(async () => (await fixtureStatus()).requests === 5, { timeout: 10000 });
  300. await fetch(`${fixtureUrl()}/release-request/5`);
  301. await browser.waitUntil(async () => (await fixtureStatus()).runtimeChecks === 2, {
  302. timeout: 30000,
  303. });
  304. await $('[data-testid="preinstalled-tools-cancel"]').click();
  305. await waitStatus("not-installed");
  306. expect(
  307. await $('[data-testid="preinstalled-tools-auto-install"]').getAttribute("aria-checked"),
  308. ).toBe("true");
  309. await expect(stat(recordPath)).rejects.toHaveProperty("code", "ENOENT");
  310. expect(await readdir(join(root, "tools", "libreoffice", "staging"))).toEqual([]);
  311. // 从外部文件系统制造原子发布失败;运行检查通过也不能留下可用记录或半成品路径。
  312. await $('[data-testid="preinstalled-tools-download"]').click();
  313. await browser.waitUntil(async () => (await fixtureStatus()).requests === 6, { timeout: 10000 });
  314. await fetch(`${fixtureUrl()}/release-request/6`);
  315. await browser.waitUntil(async () => (await fixtureStatus()).runtimeChecks === 3, {
  316. timeout: 30000,
  317. });
  318. await mkdir(recordPath);
  319. await fetch(`${fixtureUrl()}/finish-check`);
  320. await waitStatus("failed");
  321. expect((await stat(recordPath)).isDirectory()).toBe(true);
  322. expect(await readdir(join(root, "tools", "libreoffice", "versions"))).toEqual([]);
  323. expect(await readdir(join(root, "tools", "libreoffice", "staging"))).toEqual([]);
  324. await browser.saveScreenshot(
  325. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/lop-controls-publication-failed.png`,
  326. );
  327. await rm(recordPath, { recursive: true });
  328. await $('[data-testid="preinstalled-tools-retry"]').click();
  329. await browser.waitUntil(async () => (await fixtureStatus()).requests === 7, { timeout: 10000 });
  330. await fetch(`${fixtureUrl()}/release-request/7`);
  331. await waitStatus("ready");
  332. expect((await stat(recordPath)).isFile()).toBe(true);
  333. });
  334. });