auto-update-install-reentry-smoke.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
  3. import { createRequire } from "node:module";
  4. import { resolve } from "node:path";
  5. import { build } from "esbuild";
  6. import { _electron } from "playwright-core";
  7. // 真实 macOS 退出时序回归:只替换原生安装器,不接触用户应用、更新缓存或 ShipIt。
  8. if (process.platform !== "darwin") {
  9. console.log("auto-update install reentry smoke: macOS only (skipped)");
  10. process.exit(0);
  11. }
  12. const desktopDir = resolve(import.meta.dirname, "..");
  13. const repoRoot = resolve(desktopDir, "../..");
  14. const require = createRequire(resolve(desktopDir, "package.json"));
  15. const preparingDownloadFailure = process.argv.includes("--preparing-download-failure");
  16. const pendingCheck = process.argv.includes("--pending-check");
  17. const nativeInstallError = process.argv.includes("--native-install-error");
  18. await mkdir(resolve(desktopDir, ".e2e-artifacts"), { recursive: true });
  19. const artifactDir = await mkdtemp(resolve(desktopDir, ".e2e-artifacts/update-install-reentry-"));
  20. await mkdir(resolve(artifactDir, "user-data"));
  21. const entryPath = resolve(artifactDir, "main.cjs");
  22. await build({
  23. stdin: {
  24. resolveDir: desktopDir,
  25. sourcefile: "auto-update-install-reentry-fixture.mjs",
  26. contents: `
  27. import { app, BrowserWindow, ipcMain } from "electron";
  28. import pkg from "electron-updater";
  29. import { PlatformChannels } from "@zcode/shared";
  30. import { initAutoUpdater, downloadAvailableUpdate } from "./src/main/autoUpdater.ts";
  31. (async () => {
  32. const { autoUpdater } = pkg;
  33. const nativeUpdater = autoUpdater.nativeUpdater;
  34. const order = [];
  35. let installCalls = 0;
  36. let prepareCalls = 0;
  37. let nativeInstallCalls = 0;
  38. let relaunchCalls = 0;
  39. const preparingDownloadFailure = ${JSON.stringify(preparingDownloadFailure)};
  40. const pendingCheck = ${JSON.stringify(pendingCheck)};
  41. const nativeInstallError = ${JSON.stringify(nativeInstallError)};
  42. let finishPreparation;
  43. const preparation = new Promise((resolve) => { finishPreparation = resolve; });
  44. app.setPath("userData", ${JSON.stringify(resolve(artifactDir, "user-data"))});
  45. Object.defineProperty(app, "isPackaged", { value: true });
  46. autoUpdater.checkForUpdates = () => pendingCheck ? new Promise(() => {}) : Promise.resolve(null);
  47. app.relaunch = () => { relaunchCalls++; order.push("relaunch"); };
  48. const originalExit = app.exit.bind(app);
  49. app.exit = (code) => {
  50. if (nativeInstallError) {
  51. order.push("recovery-exit");
  52. console.log("UPDATE_INSTALL_RESULT=" + JSON.stringify({ installCalls, prepareCalls, nativeInstallCalls, relaunchCalls, prevented: false, order }));
  53. }
  54. originalExit(code);
  55. };
  56. autoUpdater.squirrelDownloadedUpdate = false;
  57. const originalInstall = autoUpdater.quitAndInstall.bind(autoUpdater);
  58. autoUpdater.quitAndInstall = () => {
  59. installCalls++;
  60. order.push("install-entry");
  61. originalInstall();
  62. };
  63. nativeUpdater.checkForUpdates = () => {
  64. // 根因发生在原生 staging 回调晚于安装入口返回时,不用超时猜测状态。
  65. setImmediate(() => {
  66. if (nativeInstallError) {
  67. order.push("native-error");
  68. nativeUpdater.emit("error", new Error("native staging failed"));
  69. } else {
  70. order.push("native-staged");
  71. nativeUpdater.emit("update-downloaded");
  72. }
  73. });
  74. };
  75. nativeUpdater.quitAndInstall = () => {
  76. if (nativeInstallCalls > 0) return;
  77. nativeInstallCalls++;
  78. order.push("native-install");
  79. setImmediate(() => app.quit());
  80. };
  81. await app.whenReady();
  82. await initAutoUpdater({
  83. onBeforeQuitAndInstall: async () => {
  84. prepareCalls++;
  85. order.push("prepare");
  86. if (preparingDownloadFailure) await preparation;
  87. },
  88. });
  89. ipcMain.handle("smoke-background-download-failure", () => {
  90. autoUpdater.downloadUpdate = async () => { throw new Error("background download must not start"); };
  91. autoUpdater.emit("update-available", { version: "99.0.1" });
  92. autoUpdater.emit("update-downloaded", { version: "99.0.1" });
  93. downloadAvailableUpdate("smoke-background");
  94. order.push("background-target-locked");
  95. });
  96. ipcMain.handle("smoke-finish-preparation", () => { finishPreparation(); });
  97. const win = new BrowserWindow({
  98. width: 420, height: 200,
  99. webPreferences: { nodeIntegration: true, contextIsolation: false },
  100. });
  101. await win.loadURL("data:text/html," + encodeURIComponent(
  102. '<button id="install">Restart to update</button><script>' +
  103. 'document.getElementById("install").onclick = () => ' +
  104. 'require("electron").ipcRenderer.invoke(' + JSON.stringify(PlatformChannels.QuitAndInstallUpdate) + ');' +
  105. '</script>'
  106. ));
  107. autoUpdater.emit("update-downloaded", { version: "99.0.0" });
  108. app.on("before-quit", (event) => {
  109. order.push("before-quit");
  110. console.log("UPDATE_INSTALL_RESULT=" + JSON.stringify({
  111. installCalls, prepareCalls, nativeInstallCalls, relaunchCalls,
  112. prevented: event.defaultPrevented, order,
  113. }));
  114. // 旧实现会拦截退出并重入;立即结束隔离夹具,避免无限循环。
  115. if (event.defaultPrevented) app.exit(2);
  116. });
  117. })().catch((error) => { console.error(error); app.exit(1); });
  118. `,
  119. },
  120. outfile: entryPath,
  121. bundle: true,
  122. platform: "node",
  123. format: "cjs",
  124. external: ["electron", "electron-updater", "semver"],
  125. alias: { "@zcode/shared": resolve(repoRoot, "packages/shared/src/index.ts") },
  126. plugins: [
  127. {
  128. name: "isolated-smoke-logger",
  129. setup(buildApi) {
  130. buildApi.onResolve({ filter: /^\.\/logger\.js$/ }, (args) => {
  131. if (args.importer.endsWith("/src/main/autoUpdater.ts")) {
  132. return { path: "logger", namespace: "smoke" };
  133. }
  134. });
  135. buildApi.onLoad({ filter: /.*/, namespace: "smoke" }, () => ({
  136. contents:
  137. "export const logger = { info: console.log, warn: console.warn, error: console.error };",
  138. }));
  139. },
  140. },
  141. ],
  142. });
  143. const env = { ...process.env };
  144. delete env.ELECTRON_RUN_AS_NODE;
  145. let electronApp;
  146. let output = "";
  147. try {
  148. electronApp = await _electron.launch({
  149. executablePath: require("electron"),
  150. args: [entryPath],
  151. env,
  152. });
  153. const child = electronApp.process();
  154. for (const stream of [child.stdout, child.stderr]) {
  155. stream?.on("data", (chunk) => {
  156. output += chunk.toString();
  157. });
  158. }
  159. const exited = new Promise((resolveExit, rejectExit) => {
  160. child.once("exit", (code, signal) => resolveExit({ code, signal }));
  161. child.once("error", rejectExit);
  162. });
  163. const page = await electronApp.firstWindow();
  164. await page.locator("#install").click();
  165. if (preparingDownloadFailure) {
  166. await page.evaluate(() =>
  167. require("electron").ipcRenderer.invoke("smoke-background-download-failure"),
  168. );
  169. await page.locator("#install").click();
  170. await page.evaluate(() => require("electron").ipcRenderer.invoke("smoke-finish-preparation"));
  171. }
  172. const timeout = AbortSignal.timeout(15_000);
  173. const result = await Promise.race([
  174. exited,
  175. new Promise((_, reject) =>
  176. timeout.addEventListener(
  177. "abort",
  178. () => reject(new Error("Electron did not exit after install")),
  179. { once: true },
  180. ),
  181. ),
  182. ]);
  183. assert.equal(result.code, 0, output);
  184. const reportLine = output.split("\n").find((line) => line.startsWith("UPDATE_INSTALL_RESULT="));
  185. assert.ok(reportLine, output);
  186. const report = JSON.parse(reportLine.slice("UPDATE_INSTALL_RESULT=".length));
  187. assert.deepEqual(report, {
  188. installCalls: 1,
  189. prepareCalls: 1,
  190. nativeInstallCalls: nativeInstallError ? 0 : 1,
  191. relaunchCalls: nativeInstallError ? 1 : 0,
  192. prevented: false,
  193. order: [
  194. "prepare",
  195. ...(preparingDownloadFailure ? ["background-target-locked"] : []),
  196. "install-entry",
  197. ...(nativeInstallError
  198. ? ["native-error", "relaunch", "recovery-exit"]
  199. : ["native-staged", "native-install", "before-quit"]),
  200. ],
  201. });
  202. await writeFile(
  203. resolve(artifactDir, "result.json"),
  204. JSON.stringify({ ...result, ...report }, null, 2),
  205. );
  206. console.log("auto-update install reentry smoke: PASS", artifactDir);
  207. } finally {
  208. await writeFile(resolve(artifactDir, "electron.log"), output);
  209. await electronApp?.close().catch(() => {});
  210. }