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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. // 真实 Electron 退出时序回归:替换安装器 IO,不接触用户应用、更新缓存或 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. const ordinaryQuit = process.argv.includes("--ordinary-quit");
  19. const linuxDeb = process.argv.includes("--linux-deb");
  20. await mkdir(resolve(desktopDir, ".e2e-artifacts"), { recursive: true });
  21. const artifactDir = await mkdtemp(resolve(desktopDir, ".e2e-artifacts/update-install-reentry-"));
  22. await mkdir(resolve(artifactDir, "user-data"));
  23. const entryPath = resolve(artifactDir, "main.cjs");
  24. await build({
  25. stdin: {
  26. resolveDir: desktopDir,
  27. sourcefile: "auto-update-install-reentry-fixture.mjs",
  28. contents: `
  29. import { app, BrowserWindow, ipcMain } from "electron";
  30. import { PlatformChannels } from "@zcode/shared";
  31. import { initAutoUpdater, downloadAvailableUpdate } from "./src/main/autoUpdater.ts";
  32. (async () => {
  33. const autoUpdater = globalThis.__smokeUpdater;
  34. const nativeUpdater = autoUpdater.nativeUpdater;
  35. const order = [];
  36. let installCalls = 0;
  37. let prepareCalls = 0;
  38. let nativeInstallCalls = 0;
  39. let relaunchCalls = 0;
  40. const preparingDownloadFailure = ${JSON.stringify(preparingDownloadFailure)};
  41. const pendingCheck = ${JSON.stringify(pendingCheck)};
  42. const nativeInstallError = ${JSON.stringify(nativeInstallError)};
  43. const ordinaryQuit = ${JSON.stringify(ordinaryQuit)};
  44. const linuxDeb = ${JSON.stringify(linuxDeb)};
  45. let finishPreparation;
  46. const preparation = new Promise((resolve) => { finishPreparation = resolve; });
  47. app.setPath("userData", ${JSON.stringify(resolve(artifactDir, "user-data"))});
  48. Object.defineProperty(app, "isPackaged", { value: true });
  49. autoUpdater.checkForUpdates = () => pendingCheck ? new Promise(() => {}) : Promise.resolve(null);
  50. app.relaunch = () => { relaunchCalls++; order.push("relaunch"); };
  51. const originalExit = app.exit.bind(app);
  52. app.exit = (code) => {
  53. if (nativeInstallError) {
  54. order.push("recovery-exit");
  55. console.log("UPDATE_INSTALL_RESULT=" + JSON.stringify({ installCalls, prepareCalls, nativeInstallCalls, relaunchCalls, prevented: false, order }));
  56. }
  57. originalExit(code);
  58. };
  59. autoUpdater.squirrelDownloadedUpdate = false;
  60. const originalInstall = autoUpdater.quitAndInstall.bind(autoUpdater);
  61. autoUpdater.quitAndInstall = () => {
  62. installCalls++;
  63. order.push("install-entry");
  64. originalInstall();
  65. };
  66. if (linuxDeb) {
  67. autoUpdater.downloadedUpdateHelper = {
  68. file: "/tmp/zcode smoke/update.deb", downloadedFileInfo: { isAdminRightsRequired: false },
  69. };
  70. autoUpdater.hasCommand = (command) => ["dpkg", "pkexec"].includes(command);
  71. autoUpdater.spawnSyncLog = (command, args) => {
  72. order.push("command:" + command);
  73. if (command !== "pkexec" || args[0] !== "--disable-internal-agent" || !args.join(" ").includes("/bin/bash")) {
  74. throw new Error("expected Linux privilege escalation");
  75. }
  76. if (nativeInstallError) throw new Error("authorization cancelled");
  77. nativeInstallCalls++;
  78. return "";
  79. };
  80. } else {
  81. nativeUpdater.checkForUpdates = () => {
  82. // 根因发生在原生 staging 回调晚于安装入口返回时,不用超时猜测状态。
  83. setImmediate(() => {
  84. if (nativeInstallError) {
  85. order.push("native-error");
  86. nativeUpdater.emit("error", new Error("native staging failed"));
  87. } else {
  88. order.push("native-staged");
  89. nativeUpdater.emit("update-downloaded");
  90. }
  91. });
  92. };
  93. nativeUpdater.quitAndInstall = () => {
  94. if (nativeInstallCalls > 0) return;
  95. nativeInstallCalls++;
  96. order.push("native-install");
  97. setImmediate(() => app.quit());
  98. };
  99. }
  100. await app.whenReady();
  101. await initAutoUpdater({
  102. onBeforeQuitAndInstall: async () => {
  103. prepareCalls++;
  104. order.push("prepare");
  105. if (preparingDownloadFailure) await preparation;
  106. },
  107. });
  108. ipcMain.handle("smoke-background-download-failure", () => {
  109. autoUpdater.downloadUpdate = async () => { throw new Error("background download must not start"); };
  110. autoUpdater.emit("update-available", { version: "99.0.1" });
  111. autoUpdater.emit("update-downloaded", { version: "99.0.1" });
  112. downloadAvailableUpdate("smoke-background");
  113. order.push("background-target-locked");
  114. });
  115. ipcMain.handle("smoke-finish-preparation", () => { finishPreparation(); });
  116. const win = new BrowserWindow({
  117. width: 420, height: 200,
  118. webPreferences: { nodeIntegration: true, contextIsolation: false },
  119. });
  120. await win.loadURL("data:text/html," + encodeURIComponent(
  121. '<button id="install">Restart to update</button><script>' +
  122. 'document.getElementById("install").onclick = () => ' +
  123. 'require("electron").ipcRenderer.invoke(' + JSON.stringify(ordinaryQuit ? "smoke-ordinary-quit" : PlatformChannels.QuitAndInstallUpdate) + ');' +
  124. '</script>'
  125. ));
  126. ipcMain.handle("smoke-ordinary-quit", () => { app.quit(); });
  127. autoUpdater.emit("update-downloaded", { version: "99.0.0" });
  128. app.on("before-quit", (event) => {
  129. order.push("before-quit");
  130. console.log("UPDATE_INSTALL_RESULT=" + JSON.stringify({
  131. installCalls, prepareCalls, nativeInstallCalls, relaunchCalls,
  132. prevented: event.defaultPrevented, order,
  133. }));
  134. // 旧实现会拦截退出并重入;立即结束隔离夹具,避免无限循环。
  135. if (event.defaultPrevented) app.exit(2);
  136. });
  137. })().catch((error) => { console.error(error); app.exit(1); });
  138. `,
  139. },
  140. outfile: entryPath,
  141. bundle: true,
  142. platform: "node",
  143. format: "cjs",
  144. // 在 macOS 的真实 Electron 中执行 DebUpdater;只替换平台判断和系统命令边界。
  145. // 这验证 Linux 安装器调用顺序,不代表 Linux 实机文件替换验收。
  146. ...(linuxDeb ? { define: { "process.platform": '"linux"' } } : {}),
  147. banner: {
  148. js: `globalThis.__smokeUpdater = ${linuxDeb ? 'new (require("electron-updater").DebUpdater)()' : 'require("electron-updater").autoUpdater'};`,
  149. },
  150. external: ["electron", "electron-updater", "semver"],
  151. alias: { "@zcode/shared": resolve(repoRoot, "packages/shared/src/index.ts") },
  152. plugins: [
  153. {
  154. name: "isolated-smoke-updater",
  155. setup(buildApi) {
  156. buildApi.onResolve({ filter: /^electron-updater$/ }, (args) => {
  157. if (args.importer.endsWith("/src/main/autoUpdater.ts")) {
  158. return { path: "updater", namespace: "smoke-updater" };
  159. }
  160. });
  161. buildApi.onLoad({ filter: /.*/, namespace: "smoke-updater" }, () => ({
  162. contents:
  163. 'export { CancellationToken } from "electron-updater"; export default { autoUpdater: globalThis.__smokeUpdater };',
  164. resolveDir: desktopDir,
  165. }));
  166. },
  167. },
  168. {
  169. name: "isolated-smoke-logger",
  170. setup(buildApi) {
  171. buildApi.onResolve({ filter: /^\.\/logger\.js$/ }, (args) => {
  172. if (args.importer.endsWith("/src/main/autoUpdater.ts")) {
  173. return { path: "logger", namespace: "smoke" };
  174. }
  175. });
  176. buildApi.onLoad({ filter: /.*/, namespace: "smoke" }, () => ({
  177. contents:
  178. "export const logger = { info: console.log, warn: console.warn, error: console.error };",
  179. }));
  180. },
  181. },
  182. ],
  183. });
  184. const env = { ...process.env };
  185. delete env.ELECTRON_RUN_AS_NODE;
  186. let electronApp;
  187. let output = "";
  188. try {
  189. electronApp = await _electron.launch({
  190. executablePath: require("electron"),
  191. args: [entryPath],
  192. env,
  193. });
  194. const child = electronApp.process();
  195. for (const stream of [child.stdout, child.stderr]) {
  196. stream?.on("data", (chunk) => {
  197. output += chunk.toString();
  198. });
  199. }
  200. const exited = new Promise((resolveExit, rejectExit) => {
  201. child.once("exit", (code, signal) => resolveExit({ code, signal }));
  202. child.once("error", rejectExit);
  203. });
  204. const page = await electronApp.firstWindow();
  205. await page.locator("#install").click();
  206. if (preparingDownloadFailure) {
  207. await page.evaluate(() =>
  208. require("electron").ipcRenderer.invoke("smoke-background-download-failure"),
  209. );
  210. await page.locator("#install").click();
  211. await page.evaluate(() => require("electron").ipcRenderer.invoke("smoke-finish-preparation"));
  212. }
  213. const timeout = AbortSignal.timeout(15_000);
  214. const result = await Promise.race([
  215. exited,
  216. new Promise((_, reject) =>
  217. timeout.addEventListener(
  218. "abort",
  219. () => reject(new Error("Electron did not exit after install")),
  220. { once: true },
  221. ),
  222. ),
  223. ]);
  224. assert.equal(result.code, 0, output);
  225. const reportLine = output.split("\n").find((line) => line.startsWith("UPDATE_INSTALL_RESULT="));
  226. assert.ok(reportLine, output);
  227. const report = JSON.parse(reportLine.slice("UPDATE_INSTALL_RESULT=".length));
  228. assert.deepEqual(report, {
  229. installCalls: ordinaryQuit ? 0 : 1,
  230. prepareCalls: ordinaryQuit ? 0 : 1,
  231. nativeInstallCalls: ordinaryQuit || nativeInstallError ? 0 : 1,
  232. relaunchCalls: ordinaryQuit ? 0 : nativeInstallError || linuxDeb ? 1 : 0,
  233. prevented: false,
  234. order: ordinaryQuit
  235. ? ["before-quit"]
  236. : [
  237. "prepare",
  238. ...(preparingDownloadFailure ? ["background-target-locked"] : []),
  239. "install-entry",
  240. ...(linuxDeb
  241. ? nativeInstallError
  242. ? ["command:pkexec", "command:pkexec", "relaunch", "recovery-exit"]
  243. : ["command:pkexec", "relaunch", "before-quit"]
  244. : nativeInstallError
  245. ? ["native-error", "relaunch", "recovery-exit"]
  246. : ["native-staged", "native-install", "before-quit"]),
  247. ],
  248. });
  249. await writeFile(
  250. resolve(artifactDir, "result.json"),
  251. JSON.stringify({ ...result, ...report }, null, 2),
  252. );
  253. console.log("auto-update install reentry smoke: PASS", artifactDir);
  254. } finally {
  255. await writeFile(resolve(artifactDir, "electron.log"), output);
  256. await electronApp?.close().catch(() => {});
  257. }