update-window-background-download.test.mjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
  3. import { createRequire } from "node:module";
  4. import { resolve } from "node:path";
  5. import test from "node:test";
  6. import ts from "typescript";
  7. import { build } from "esbuild";
  8. import { createServer } from "vite";
  9. import react from "@vitejs/plugin-react";
  10. import tailwind from "@tailwindcss/vite";
  11. import { _electron } from "playwright-core";
  12. const desktop = resolve(import.meta.dirname, "../../../../../..");
  13. const root = resolve(desktop, "../..");
  14. const require = createRequire(import.meta.url);
  15. // 编译并运行生产窗口函数,不复制关闭策略;替换完整应用启动,避免连接用户账号或实际安装器。
  16. async function windowSource() {
  17. const path = resolve(desktop, "src/main/index.ts");
  18. const source = await readFile(path, "utf8");
  19. const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  20. const names = new Set([
  21. "getApplicationWindowsExcludingCuaIndicator",
  22. "getMainApplicationWindows",
  23. "isUpdateStatusWindowCloseLocked",
  24. "syncUpdateStatusWindowClosePolicy",
  25. "syncUpdateStatusWindowChrome",
  26. "resolveUpdateStatusWindowHeight",
  27. "shouldUseUpdateStatusWindowContentSize",
  28. "syncUpdateStatusWindowLayout",
  29. "openUpdateStatusWindow",
  30. ]);
  31. const selected = file.statements.filter(
  32. (statement) => ts.isFunctionDeclaration(statement) && names.has(statement.name?.text),
  33. );
  34. assert(selected.some((node) => node.name?.text === "openUpdateStatusWindow"));
  35. const constants = file.statements.filter(
  36. (statement) =>
  37. ts.isVariableStatement(statement) &&
  38. statement.declarationList.declarations.some(
  39. (declaration) =>
  40. ts.isIdentifier(declaration.name) &&
  41. (declaration.name.text.startsWith("UPDATE_STATUS_WINDOW_") ||
  42. declaration.name.text === "closingUpdateStatusWindows"),
  43. ),
  44. );
  45. const quit = file.statements.filter(
  46. (statement) =>
  47. ts.isExpressionStatement(statement) &&
  48. ts.isCallExpression(statement.expression) &&
  49. statement.expression.expression.getText(file) === "app.on" &&
  50. statement.expression.arguments[0]?.getText(file) === '"before-quit"',
  51. );
  52. assert.equal(quit.length, 1);
  53. return [...constants, ...selected, ...quit].map((node) => node.getText(file)).join("\n");
  54. }
  55. async function runtime() {
  56. app.setPath("userData", FIXTURE_DIR + "/user-data");
  57. Object.defineProperty(app, "isPackaged", { value: true });
  58. autoUpdater.checkForUpdates = async () => null;
  59. let installCalls = 0;
  60. autoUpdater.quitAndInstall = () => {
  61. installCalls++;
  62. };
  63. const bytes = Buffer.alloc(256 * 1024, 37);
  64. const downloads = [];
  65. let starts = 0;
  66. let activeToken;
  67. const server = createHttpServer((_request, response) => {
  68. response.writeHead(200, { "Content-Length": bytes.length });
  69. downloads.push({ response, sent: 0 });
  70. });
  71. await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  72. const digest = createHash("sha512").update(bytes).digest("base64");
  73. autoUpdater.downloadUpdate = async (token) => {
  74. activeToken = token;
  75. starts++;
  76. const path = FIXTURE_DIR + "/download-" + starts + ".zip";
  77. await autoUpdater.httpExecutor.download(
  78. new URL("http://127.0.0.1:" + server.address().port + "/file"),
  79. path,
  80. {
  81. cancellationToken: token,
  82. sha512: digest,
  83. },
  84. );
  85. autoUpdater.emit("update-downloaded", { version: offeredVersion });
  86. return [path];
  87. };
  88. await app.whenReady();
  89. await initAutoUpdater({
  90. settingService: {
  91. get: async () => ({ autoDownloadAndInstallUpdates: false, receivePreviewUpdates: false }),
  92. update: async () => {},
  93. },
  94. });
  95. ipcMain.handle("zcode:open-update-status-window", () => openUpdateStatusWindow());
  96. let holdNextSnapshot = false;
  97. let releaseSnapshot;
  98. ipcMain.handle("zcode:get-update-state", () => {
  99. const state = getAutoUpdaterState();
  100. if (!holdNextSnapshot) return state;
  101. holdNextSnapshot = false;
  102. return new Promise((resolve) => {
  103. releaseSnapshot = () => {
  104. releaseSnapshot = undefined;
  105. resolve(state);
  106. };
  107. });
  108. });
  109. ipcMain.handle("zcode:get-auto-update-preferences", () => ({
  110. autoDownloadAndInstallUpdates: false,
  111. }));
  112. ipcMain.handle("zcode:get-desktop-session-activity", () => ({ runningAgentSessionCount: 0 }));
  113. const main = new BrowserWindow({
  114. width: 1100,
  115. height: 760,
  116. webPreferences: {
  117. preload: preloadPath,
  118. contextIsolation: true,
  119. nodeIntegration: false,
  120. },
  121. });
  122. await loadWindow(main, "index", {});
  123. globalThis.control = {
  124. holdSnapshot() {
  125. holdNextSnapshot = true;
  126. },
  127. snapshotHeld() {
  128. return Boolean(releaseSnapshot);
  129. },
  130. releaseSnapshot() {
  131. releaseSnapshot?.();
  132. },
  133. offer(version) {
  134. offeredVersion = version;
  135. autoUpdater.emit("update-available", { version });
  136. },
  137. snapshot() {
  138. return {
  139. state: getAutoUpdaterState(),
  140. starts,
  141. installCalls,
  142. tokenCancelled: activeToken?.cancelled ?? false,
  143. snapshotHeld: Boolean(releaseSnapshot),
  144. listenerCount,
  145. windowId: updateStatusWindow?.id ?? null,
  146. downloads: downloads.length,
  147. mainId: main.id,
  148. windowCount: BrowserWindow.getAllWindows().length,
  149. };
  150. },
  151. async bytes() {
  152. try {
  153. return (await stat(FIXTURE_DIR + "/download-" + starts + ".zip")).size;
  154. } catch {
  155. return 0;
  156. }
  157. },
  158. advance(count) {
  159. const download = downloads.at(-1);
  160. download.response.write(bytes.subarray(download.sent, count));
  161. download.sent = count;
  162. },
  163. progress(count) {
  164. autoUpdater.emit("download-progress", {
  165. bytesPerSecond: 0,
  166. percent: (count / bytes.length) * 100,
  167. transferred: count,
  168. total: bytes.length,
  169. });
  170. },
  171. finish() {
  172. const d = downloads.at(-1);
  173. d.response.end(bytes.subarray(d.sent));
  174. },
  175. fail() {
  176. downloads.at(-1).response.destroy();
  177. },
  178. open() {
  179. openUpdateStatusWindow();
  180. },
  181. close() {
  182. if (updateStatusWindow && !updateStatusWindow.isDestroyed()) updateStatusWindow.close();
  183. },
  184. closeAndReopen() {
  185. if (updateStatusWindow && !updateStatusWindow.isDestroyed()) updateStatusWindow.close();
  186. openUpdateStatusWindow();
  187. return {
  188. mainId: main.id,
  189. id: updateStatusWindow?.id,
  190. parentId: updateStatusWindow?.getParentWindow()?.id,
  191. };
  192. },
  193. holdLoad() {
  194. deferLoadResult = true;
  195. },
  196. loadHeld() {
  197. return Boolean(rejectLoadResult);
  198. },
  199. rejectLoad() {
  200. rejectLoadResult?.(new Error("late load aborted after close"));
  201. rejectLoadResult = undefined;
  202. },
  203. setView(nextLocale, nextTheme) {
  204. currentApplicationLocale = nextLocale;
  205. theme = nextTheme;
  206. },
  207. quit() {
  208. app.quit();
  209. },
  210. };
  211. const result = () => ({
  212. starts,
  213. installCalls,
  214. preparationCalls,
  215. windowCount: BrowserWindow.getAllWindows().length,
  216. });
  217. globalThis.finalEvidence = result;
  218. }
  219. test("普通更新窗口关闭、后台下载、快照恢复和退出", { timeout: 240_000 }, async () => {
  220. await mkdir(resolve(desktop, ".e2e-artifacts"), { recursive: true });
  221. const artifacts = await mkdtemp(resolve(desktop, ".e2e-artifacts/update-background-"));
  222. const entry = resolve(artifacts, "main.cjs");
  223. const preload = resolve(artifacts, "preload.cjs");
  224. const logs = [];
  225. let app;
  226. let vite;
  227. try {
  228. await writeFile(
  229. preload,
  230. [
  231. 'const {contextBridge,ipcRenderer}=require("electron");',
  232. "const on=(channel,fn)=>{const handler=(_event,value)=>fn(value);ipcRenderer.on(channel,handler);return()=>ipcRenderer.removeListener(channel,handler)};",
  233. 'contextBridge.exposeInMainWorld("updateFixture",{',
  234. 'getUpdateState:()=>ipcRenderer.invoke("zcode:get-update-state"),',
  235. 'onUpdateStateChanged:fn=>on("zcode:update-state-changed",fn),',
  236. 'onUpdateReady:fn=>on("zcode:update-ready",fn),',
  237. 'onApplicationLocaleChanged:fn=>on("zcode:application-locale-changed",fn),',
  238. 'getAutoUpdatePreferences:()=>ipcRenderer.invoke("zcode:get-auto-update-preferences"),',
  239. 'getDesktopSessionActivity:()=>ipcRenderer.invoke("zcode:get-desktop-session-activity"),',
  240. 'downloadUpdate:()=>ipcRenderer.invoke("zcode:download-update"),',
  241. 'cancelUpdateDownload:()=>ipcRenderer.invoke("zcode:cancel-update-download"),',
  242. 'quitAndInstallUpdate:()=>ipcRenderer.invoke("zcode:quit-and-install-update"),',
  243. 'openUpdateStatusWindow:()=>ipcRenderer.invoke("zcode:open-update-status-window"),',
  244. "openExternal:()=>{},",
  245. "});",
  246. ].join("\n"),
  247. );
  248. await writeFile(
  249. resolve(artifacts, "index.html"),
  250. '<!doctype html><html><body><div id="root"></div><script type="module" src="/entry.tsx"></script></body></html>',
  251. );
  252. await writeFile(
  253. resolve(artifacts, "entry.tsx"),
  254. [
  255. 'import React,{useEffect,useState} from "react";import {createRoot} from "react-dom/client";',
  256. 'import {UpdateStatusButton} from "@/UpdateStatusButton";import {TooltipProvider} from "@/components/ui/tooltip";',
  257. 'import {UpdateStatusWindowRoot} from "@/UpdateStatusWindowRoot";',
  258. 'import {ZCodeIntlProvider} from "@/i18n/IntlProvider";import "@/styles.css";',
  259. 'const params=new URLSearchParams(location.search);const locale=params.get("locale")||"zh-CN";',
  260. 'document.documentElement.classList.add("theme-"+(params.get("theme")||"zai-light"));',
  261. 'document.body.style.background="var(--color-background)";const platform=window.updateFixture;',
  262. 'function Main(){const[state,setState]=useState(null);useEffect(()=>{platform.getUpdateState().then(setState);return platform.onUpdateStateChanged(setState)},[]);return <ZCodeIntlProvider initialLocale={locale}><TooltipProvider><main style={{padding:32}}><UpdateStatusButton platform={platform} updateState={state} version={null}/><button id="workspace">Workspace</button></main></TooltipProvider></ZCodeIntlProvider>}',
  263. 'createRoot(document.getElementById("root")!).render(params.get("windowKind")==="update-status"?<UpdateStatusWindowRoot platform={platform} initialLocale={locale} onRequestClose={()=>window.close()}/>:<Main/>);',
  264. ].join("\n"),
  265. );
  266. vite = await createServer({
  267. configFile: false,
  268. root: artifacts,
  269. plugins: [react(), tailwind()],
  270. resolve: { alias: { "@": resolve(root, "packages/ui/src") } },
  271. server: { host: "127.0.0.1", port: 0, fs: { allow: [root] } },
  272. optimizeDeps: { include: ["react", "react-dom/client", "react/jsx-runtime"] },
  273. logLevel: "error",
  274. });
  275. await vite.listen();
  276. const source = [
  277. 'import {app,BrowserWindow,ipcMain} from "electron";',
  278. 'import {createServer as createHttpServer} from "node:http";',
  279. 'import {createHash} from "node:crypto";',
  280. 'import {stat,writeFile} from "node:fs/promises";',
  281. 'import {autoUpdater} from "electron-updater";',
  282. 'import {initAutoUpdater,getAutoUpdaterState,onAutoUpdaterStateChanged as subscribeState,syncAutoUpdaterStateToWindow,syncReadyUpdateToWindow,syncPostUpdateReleaseNotesToWindow} from "./src/main/autoUpdater.ts";',
  283. "const logger={info:console.log,warn:console.warn,error:console.error};",
  284. "let listenerCount=0;function onAutoUpdaterStateChanged(fn){listenerCount++;const dispose=subscribeState(fn);return()=>{listenerCount--;dispose()}}",
  285. "let updateStatusWindow=null;const forceQuitRef={current:false};const explicitQuitRef={current:false};",
  286. 'const windowsCuaOperationIndicator={ownsWindow:()=>false};const iconPath=undefined;const deviceMid="update-fixture";',
  287. 'const preloadPath=PRELOAD_PATH;let currentApplicationLocale="zh-CN";let theme="zai-light";let offeredVersion="99.0.1";',
  288. "const localMediaPreviewPathRegistry={clear(){}};let hasPreparedAppQuit=false;let preparationCalls=0;",
  289. "function shouldConfirmAppQuit(){return false}function confirmAppQuit(){return true}",
  290. 'async function prepareAppQuit(){preparationCalls++;hasPreparedAppQuit=true;forceQuitRef.current=true;await writeFile(FIXTURE_DIR+"/quit.json",JSON.stringify(globalThis.finalEvidence?.()??{}));}',
  291. "function exitPreparedApp(){app.exit(0)}",
  292. "let deferLoadResult=false;let rejectLoadResult;",
  293. 'function loadWindow(win,_page,bootstrap){const url=new URL(RENDERER_URL);url.searchParams.set("fixtureWindowId",String(win.id));url.searchParams.set("locale",currentApplicationLocale);url.searchParams.set("theme",theme);if(bootstrap?.windowKind)url.searchParams.set("windowKind",bootstrap.windowKind);const loaded=win.loadURL(url.toString());if(!deferLoadResult)return loaded;deferLoadResult=false;return loaded.then(()=>new Promise((_resolve,reject)=>{rejectLoadResult=reject}));}',
  294. await windowSource(),
  295. "(" + runtime.toString() + ")().catch(error=>{console.error(error);app.exit(1)})",
  296. ].join("\n");
  297. await build({
  298. stdin: { contents: source, resolveDir: desktop, loader: "ts" },
  299. outfile: entry,
  300. bundle: true,
  301. platform: "node",
  302. format: "cjs",
  303. external: ["electron", "electron-updater", "semver"],
  304. define: {
  305. FIXTURE_DIR: JSON.stringify(artifacts),
  306. PRELOAD_PATH: JSON.stringify(preload),
  307. RENDERER_URL: JSON.stringify(vite.resolvedUrls.local[0]),
  308. },
  309. alias: { "@zcode/shared": resolve(root, "packages/shared/src/index.ts") },
  310. plugins: [
  311. {
  312. name: "isolated-logger",
  313. setup(api) {
  314. api.onResolve({ filter: /^\.\/logger\.js$/ }, (args) =>
  315. args.importer.endsWith("/main/autoUpdater.ts")
  316. ? { path: "logger", namespace: "fixture" }
  317. : undefined,
  318. );
  319. api.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({
  320. contents:
  321. "export const logger={info:console.log,warn:console.warn,error:console.error}",
  322. }));
  323. },
  324. },
  325. ],
  326. });
  327. const env = { ...process.env };
  328. delete env.ELECTRON_RUN_AS_NODE;
  329. app = await _electron.launch({
  330. executablePath: require("electron"),
  331. args: [entry],
  332. env,
  333. timeout: 20_000,
  334. });
  335. for (const stream of [app.process().stdout, app.process().stderr])
  336. stream?.on("data", (chunk) => logs.push(chunk.toString()));
  337. const page = await app.firstWindow();
  338. const invoke = (method, argument) =>
  339. app.evaluate((_electron, { method, argument }) => globalThis.control[method](argument), {
  340. method,
  341. argument,
  342. });
  343. const snapshot = () => invoke("snapshot");
  344. const until = async (predicate, message) => {
  345. const deadline = Date.now() + 15_000;
  346. while (Date.now() < deadline) {
  347. if (await predicate()) return;
  348. await new Promise((resolve) => setTimeout(resolve, 25));
  349. }
  350. assert.fail(message);
  351. };
  352. const updatePage = async () => {
  353. let found;
  354. await until(async () => {
  355. const id = (await snapshot()).windowId;
  356. found = app.windows().find((candidate) => {
  357. const url = candidate.url();
  358. return (
  359. url.includes("windowKind=update-status") &&
  360. new URL(url).searchParams.get("fixtureWindowId") === String(id)
  361. );
  362. });
  363. return Boolean(found);
  364. }, "更新窗口的 renderer 尚未加载");
  365. return found;
  366. };
  367. await page.locator("#workspace").waitFor();
  368. const results = [];
  369. // 先覆盖没有旧 ready 包的真实失败分支,再执行四组成功下载。
  370. await invoke("offer", "99.0.0");
  371. await until(async () => (await snapshot()).state.kind === "update-available", "失败场景未就绪");
  372. await invoke("open");
  373. await (await updatePage()).getByRole("button", { name: "下载更新", exact: true }).click();
  374. await until(async () => (await snapshot()).downloads === 1, "失败下载未开始");
  375. await invoke("advance", 65536);
  376. await until(async () => (await invoke("bytes")) >= 65536, "失败场景首段未收到");
  377. await invoke("progress", 65536);
  378. await invoke("close");
  379. await until(async () => (await snapshot()).windowCount === 1, "失败场景窗口未关闭");
  380. await invoke("fail");
  381. await until(
  382. async () => (await snapshot()).state.kind === "update-available",
  383. "失败后未恢复可重试状态",
  384. );
  385. assert.equal((await snapshot()).windowCount, 1);
  386. await page.locator("main button").first().click();
  387. await (await updatePage()).getByRole("button", { name: "下载更新", exact: true }).waitFor();
  388. await invoke("close");
  389. await until(async () => (await snapshot()).windowCount === 1, "重试窗口未关闭");
  390. let version = 1;
  391. for (const locale of ["zh-CN", "en-US"])
  392. for (const theme of ["zai-light", "zai-dark"]) {
  393. const offered = "99.0." + version++;
  394. await app.evaluate(
  395. (_electron, { locale, theme }) => globalThis.control.setView(locale, theme),
  396. { locale, theme },
  397. );
  398. await invoke("offer", offered);
  399. await until(
  400. async () => (await snapshot()).state.kind === "update-available",
  401. "未出现可下载状态",
  402. );
  403. await page.locator("main button").first().click();
  404. await until(async () => (await snapshot()).windowId !== null, "更新窗口未打开");
  405. let id = (await snapshot()).windowId;
  406. let win = await updatePage();
  407. const starts = (await snapshot()).starts + 1;
  408. await win
  409. .getByRole("button", {
  410. name: locale === "zh-CN" ? "下载更新" : "Download update",
  411. exact: true,
  412. })
  413. .click();
  414. await until(async () => (await snapshot()).downloads === starts, "下载连接未到达");
  415. await invoke("advance", 65536);
  416. await until(async () => (await invoke("bytes")) >= 65536, "首段未写入");
  417. await invoke("progress", 65536);
  418. await until(
  419. async () => (await snapshot()).state.kind === "download-progress",
  420. "未进入下载状态",
  421. );
  422. await invoke("close");
  423. await until(async () => (await snapshot()).windowId === null, "下载中原生关闭被拦截");
  424. assert.equal((await snapshot()).listenerCount, 0);
  425. assert.equal((await snapshot()).tokenCancelled, false);
  426. await invoke("advance", 131072);
  427. await until(async () => (await invoke("bytes")) >= 131072, "窗口关闭后下载停止");
  428. await invoke("progress", 131072);
  429. assert.equal((await snapshot()).windowCount, 1);
  430. await invoke("holdSnapshot");
  431. await page.locator("main button").first().click();
  432. await until(async () => (await snapshot()).windowId !== null, "下载中入口无法重开");
  433. const reopened = await snapshot();
  434. assert.notEqual(reopened.windowId, id);
  435. assert.equal(reopened.starts, starts);
  436. assert.equal(reopened.state.transferredBytes, 131072);
  437. assert.equal(reopened.listenerCount, 1);
  438. win = await updatePage();
  439. await until(async () => await invoke("snapshotHeld"), "重开快照未进入受控等待");
  440. await invoke("advance", 196608);
  441. await until(async () => (await invoke("bytes")) >= 196608, "重开后字节未继续写入");
  442. await invoke("progress", 196608);
  443. await win.getByText("0.2MB / 0.3MB", { exact: true }).waitFor();
  444. await invoke("releaseSnapshot");
  445. await win.evaluate(() => new Promise((resolve) => requestAnimationFrame(resolve)));
  446. assert.equal(await win.getByText("0.2MB / 0.3MB", { exact: true }).count(), 1);
  447. await win
  448. .getByRole("button", {
  449. name: locale === "zh-CN" ? "后台下载" : "Download in background",
  450. exact: true,
  451. })
  452. .waitFor();
  453. await win.screenshot({ path: resolve(artifacts, locale + "-" + theme + ".png") });
  454. await win
  455. .getByRole("button", {
  456. name: locale === "zh-CN" ? "后台下载" : "Download in background",
  457. exact: true,
  458. })
  459. .click();
  460. await until(async () => (await snapshot()).windowId === null, "后台下载未关窗");
  461. for (let n = 0; n < 3; n++) {
  462. await invoke("open");
  463. await (await updatePage()).getByRole("dialog").waitFor();
  464. const closingId = (await snapshot()).windowId;
  465. const race = await invoke("closeAndReopen");
  466. assert.notEqual(race.id, closingId, JSON.stringify({ closingId, ...race }));
  467. assert.equal(race.parentId, race.mainId);
  468. await (await updatePage()).getByRole("dialog").waitFor();
  469. assert.equal((await snapshot()).listenerCount, 1, JSON.stringify(race));
  470. await invoke("close");
  471. await until(async () => (await snapshot()).listenerCount === 0, "关窗后监听未释放");
  472. }
  473. await invoke("finish");
  474. await until(
  475. async () => (await snapshot()).state.kind === "update-downloaded",
  476. "关闭后下载完成未发布",
  477. );
  478. assert.equal((await snapshot()).windowCount, 1);
  479. await page.locator("main button").first().click();
  480. await until(async () => (await snapshot()).windowId !== null, "完成后无法重开");
  481. await invoke("close");
  482. assert.equal((await snapshot()).installCalls, 0);
  483. results.push({
  484. locale,
  485. theme,
  486. starts,
  487. transferredWhileClosed: 131072,
  488. listenersAfterClose: 0,
  489. });
  490. }
  491. // 窗口已显示后关闭,再交付迟到的加载拒绝;不得复活窗口或影响 ready 状态。
  492. await invoke("holdLoad");
  493. await invoke("open");
  494. await (await updatePage()).getByRole("dialog").waitFor();
  495. await until(async () => await invoke("loadHeld"), "加载结果未进入受控等待");
  496. await invoke("close");
  497. await invoke("rejectLoad");
  498. await until(async () => (await snapshot()).windowCount === 1, "迟到加载结果重建了窗口");
  499. assert.equal((await snapshot()).state.kind, "update-downloaded");
  500. await invoke("open");
  501. await (
  502. await updatePage()
  503. )
  504. .getByRole("button", { name: "Restart to update", exact: true })
  505. .waitFor();
  506. assert.equal((await snapshot()).installCalls, 0);
  507. const exited = new Promise((resolve) => app.process().once("exit", (code) => resolve(code)));
  508. await invoke("quit").catch(() => {});
  509. assert.equal(await exited, 0);
  510. const quit = JSON.parse(await readFile(resolve(artifacts, "quit.json"), "utf8"));
  511. assert.equal(quit.installCalls, 0);
  512. assert.equal(quit.preparationCalls, 1);
  513. await writeFile(
  514. resolve(artifacts, "result.json"),
  515. JSON.stringify(
  516. { cases: results, failureRecovery: true, lateLoadIgnored: true, quit },
  517. null,
  518. 2,
  519. ),
  520. );
  521. console.log("update background E2E: PASS " + artifacts);
  522. } finally {
  523. await writeFile(resolve(artifacts, "electron.log"), logs.join(""));
  524. await app?.close().catch(() => {});
  525. await vite?.close();
  526. console.log("update background artifacts: " + artifacts);
  527. }
  528. });