autoUpdaterReadyState.test.ts 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364
  1. import { EventEmitter } from "node:events";
  2. import { PlatformChannels, desktopMenuMessageIds, formatDesktopMenuMessage } from "@zcode/shared";
  3. import { beforeEach, describe, expect, it, vi } from "vitest";
  4. const { loggerErrorMock, loggerInfoMock, loggerWarnMock, readFileMock, spawnMock } = vi.hoisted(
  5. () => {
  6. return {
  7. loggerErrorMock: vi.fn(),
  8. loggerInfoMock: vi.fn(),
  9. loggerWarnMock: vi.fn(),
  10. readFileMock: vi.fn(),
  11. spawnMock: vi.fn(),
  12. };
  13. },
  14. );
  15. const originalPlatform = process.platform;
  16. const ONE_HOUR_MS = 60 * 60 * 1000;
  17. const FIFTEEN_MINUTES_MS = 15 * 60 * 1000;
  18. const TWO_MINUTES_MS = 2 * 60 * 1000;
  19. const TEST_LOCALE = "en-US" as const;
  20. const menuItem = {
  21. label: "",
  22. enabled: true,
  23. };
  24. const browserWindows: Array<{
  25. isDestroyed: () => boolean;
  26. webContents: {
  27. id: number;
  28. send: ReturnType<typeof vi.fn>;
  29. };
  30. }> = [];
  31. const ipcMainOn = vi.fn();
  32. const ipcMainHandle = vi.fn();
  33. const dialogShowMessageBox = vi.fn(async () => ({ response: 1 }));
  34. const settingServiceMock = {
  35. get: vi.fn(async () => ({ recentProjects: [], locale: "en-US" as const })),
  36. update: vi.fn(async () => {}),
  37. };
  38. const appListeners = new Map<string, Array<(...args: unknown[]) => void>>();
  39. const appMock = {
  40. isPackaged: true,
  41. getVersion: vi.fn(() => "0.1.24"),
  42. getAppPath: vi.fn(() => "/tmp/zcode-app"),
  43. relaunch: vi.fn(),
  44. exit: vi.fn(),
  45. on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
  46. const listeners = appListeners.get(event) ?? [];
  47. listeners.push(listener);
  48. appListeners.set(event, listeners);
  49. }),
  50. };
  51. const autoUpdaterMock = new EventEmitter() as EventEmitter & {
  52. autoDownload: boolean;
  53. autoInstallOnAppQuit: boolean;
  54. logger: unknown;
  55. checkForUpdates: ReturnType<typeof vi.fn>;
  56. downloadUpdate: ReturnType<typeof vi.fn>;
  57. quitAndInstall: ReturnType<typeof vi.fn>;
  58. setFeedURL: ReturnType<typeof vi.fn>;
  59. forceDevUpdateConfig: boolean;
  60. currentVersion: { format(): string } | null;
  61. installerPath: string | null;
  62. autoRunAppAfterInstall: boolean;
  63. installDirectory: string | null;
  64. downloadedUpdateHelper: {
  65. downloadedFileInfo?: { isAdminRightsRequired?: boolean } | null;
  66. packageFile?: string | null;
  67. } | null;
  68. };
  69. autoUpdaterMock.autoDownload = false;
  70. autoUpdaterMock.autoInstallOnAppQuit = false;
  71. autoUpdaterMock.checkForUpdates = vi.fn(() => Promise.resolve());
  72. autoUpdaterMock.downloadUpdate = vi.fn(() => Promise.resolve([]));
  73. autoUpdaterMock.quitAndInstall = vi.fn();
  74. autoUpdaterMock.setFeedURL = vi.fn();
  75. autoUpdaterMock.forceDevUpdateConfig = false;
  76. autoUpdaterMock.currentVersion = null;
  77. autoUpdaterMock.installerPath =
  78. "C:\\Users\\demo\\AppData\\Local\\zcode-updater\\pending\\ZCode-0.1.25-win-x64.exe";
  79. autoUpdaterMock.autoRunAppAfterInstall = true;
  80. autoUpdaterMock.installDirectory = null;
  81. autoUpdaterMock.downloadedUpdateHelper = null;
  82. vi.mock("node:child_process", () => ({
  83. spawn: spawnMock,
  84. }));
  85. vi.mock("electron", () => ({
  86. app: appMock,
  87. BrowserWindow: {
  88. getAllWindows: vi.fn(() => browserWindows),
  89. },
  90. ipcMain: {
  91. on: ipcMainOn,
  92. handle: ipcMainHandle,
  93. },
  94. dialog: {
  95. showMessageBox: dialogShowMessageBox,
  96. },
  97. Menu: {
  98. getApplicationMenu: vi.fn(() => ({
  99. getMenuItemById: vi.fn(() => menuItem),
  100. })),
  101. },
  102. }));
  103. vi.mock("electron-updater", () => {
  104. class CancellationTokenMock {
  105. cancelled = false;
  106. private cancelListeners: Array<() => void> = [];
  107. cancel() {
  108. this.cancelled = true;
  109. const listeners = this.cancelListeners;
  110. this.cancelListeners = [];
  111. for (const listener of listeners) {
  112. listener();
  113. }
  114. }
  115. once(event: string, listener: () => void) {
  116. if (event === "cancel") {
  117. this.cancelListeners.push(listener);
  118. }
  119. return this;
  120. }
  121. dispose() {
  122. this.cancelListeners = [];
  123. }
  124. }
  125. class ProviderMock {
  126. constructor() {}
  127. get isUseMultipleRangeRequest() {
  128. return false;
  129. }
  130. setRequestHeaders() {}
  131. }
  132. return {
  133. CancellationToken: CancellationTokenMock,
  134. Provider: ProviderMock,
  135. default: {
  136. autoUpdater: autoUpdaterMock,
  137. },
  138. };
  139. });
  140. vi.mock("node:fs/promises", () => ({
  141. readFile: readFileMock,
  142. }));
  143. // Bugfix: 这里之前把模块路径写死成开发者本机绝对路径,换一台机器跑单测就会直接找不到模块。
  144. // 改成相对测试文件的可移植导入后,macOS / Linux / Windows 下都能按当前工作区正确解析。
  145. vi.mock("../src/main/logger.js", () => ({
  146. logger: {
  147. info: loggerInfoMock,
  148. warn: loggerWarnMock,
  149. error: loggerErrorMock,
  150. },
  151. }));
  152. async function importAutoUpdaterWithLocale() {
  153. const module = await import("../src/main/autoUpdater.js");
  154. module.setAutoUpdaterMenuLocale(TEST_LOCALE);
  155. return module;
  156. }
  157. function mockProcessPlatform(platform: NodeJS.Platform) {
  158. Object.defineProperty(process, "platform", {
  159. value: platform,
  160. configurable: true,
  161. });
  162. }
  163. function getExpectedDownloadingProgressLabel(progress: number) {
  164. return formatDesktopMenuMessage(
  165. TEST_LOCALE,
  166. desktopMenuMessageIds.helpDownloadingUpdateProgress,
  167. {
  168. progress,
  169. },
  170. );
  171. }
  172. describe("autoUpdater ready state sync", () => {
  173. beforeEach(() => {
  174. vi.resetModules();
  175. mockProcessPlatform(originalPlatform);
  176. browserWindows.length = 0;
  177. menuItem.label = "";
  178. menuItem.enabled = true;
  179. ipcMainOn.mockClear();
  180. ipcMainHandle.mockClear();
  181. spawnMock.mockClear();
  182. loggerInfoMock.mockClear();
  183. loggerWarnMock.mockClear();
  184. loggerErrorMock.mockClear();
  185. dialogShowMessageBox.mockClear();
  186. dialogShowMessageBox.mockResolvedValue({ response: 1 });
  187. appMock.getVersion.mockClear();
  188. appMock.relaunch.mockClear();
  189. appMock.exit.mockClear();
  190. autoUpdaterMock.removeAllListeners();
  191. autoUpdaterMock.autoDownload = false;
  192. autoUpdaterMock.autoInstallOnAppQuit = false;
  193. autoUpdaterMock.checkForUpdates.mockClear();
  194. autoUpdaterMock.downloadUpdate.mockClear();
  195. autoUpdaterMock.quitAndInstall.mockClear();
  196. autoUpdaterMock.setFeedURL.mockClear();
  197. autoUpdaterMock.forceDevUpdateConfig = false;
  198. autoUpdaterMock.currentVersion = null;
  199. autoUpdaterMock.installerPath =
  200. "C:\\Users\\demo\\AppData\\Local\\zcode-updater\\pending\\ZCode-0.1.25-win-x64.exe";
  201. autoUpdaterMock.autoRunAppAfterInstall = true;
  202. autoUpdaterMock.installDirectory = null;
  203. autoUpdaterMock.downloadedUpdateHelper = null;
  204. settingServiceMock.get.mockClear();
  205. settingServiceMock.get.mockResolvedValue({
  206. recentProjects: [],
  207. locale: "en-US",
  208. });
  209. settingServiceMock.update.mockClear();
  210. appListeners.clear();
  211. appMock.getVersion.mockImplementation(() => "0.1.24");
  212. appMock.getAppPath.mockClear();
  213. appMock.getAppPath.mockReturnValue("/tmp/zcode-app");
  214. appMock.isPackaged = true;
  215. Object.defineProperty(process, "resourcesPath", {
  216. value: "/tmp/zcode-resources",
  217. configurable: true,
  218. });
  219. delete process.env["TEST_UPDATER_ARCH"];
  220. delete process.env["ZCODE_UPDATE_FEED_URL"];
  221. delete process.env["ZCODE_AUTO_UPDATE_DEV"];
  222. delete process.env["ZCODE_AUTO_UPDATE_DEV_VERSION"];
  223. readFileMock.mockReset();
  224. readFileMock.mockRejectedValue(new Error("missing update config"));
  225. });
  226. it("Preview 禁用更新器时不注册 IPC、事件或启动检查", async () => {
  227. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  228. await initAutoUpdater({ enabled: false });
  229. expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled();
  230. expect(ipcMainOn).not.toHaveBeenCalled();
  231. expect(autoUpdaterMock.listenerCount("checking-for-update")).toBe(0);
  232. expect(loggerInfoMock).toHaveBeenCalledWith(
  233. "[auto-update] disabled for this desktop product flavor",
  234. );
  235. });
  236. it("Preview 禁用更新器后,漏改的手动检查入口也不能触碰未初始化的 updater", async () => {
  237. // Bugfix: 托盘/命令入口若仍按 ZCODE_ENV 放行,会对占位 feed 发真实 checkForUpdates;
  238. // 禁用语义必须在 autoUpdater 模块内 fail-closed,而不是依赖每个调用点各自判断。
  239. const win = {
  240. isDestroyed: () => false,
  241. webContents: {
  242. id: 9,
  243. send: vi.fn(),
  244. },
  245. };
  246. browserWindows.push(win);
  247. const { initAutoUpdater, checkForUpdateMenuClick } = await import("../src/main/autoUpdater.js");
  248. await initAutoUpdater({ enabled: false });
  249. checkForUpdateMenuClick(win as never);
  250. await Promise.resolve();
  251. expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled();
  252. expect(autoUpdaterMock.setFeedURL).not.toHaveBeenCalled();
  253. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  254. kind: "dev-skipped",
  255. });
  256. expect(loggerInfoMock).toHaveBeenCalledWith(
  257. "[auto-update] skip manual check: updater disabled for this product flavor",
  258. );
  259. });
  260. it("Linux arm64 主更新检查默认使用服务端 manifest provider", async () => {
  261. mockProcessPlatform("linux");
  262. process.env["TEST_UPDATER_ARCH"] = "arm64";
  263. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  264. initAutoUpdater();
  265. expect(autoUpdaterMock.setFeedURL).toHaveBeenCalledWith(
  266. expect.objectContaining({
  267. provider: "custom",
  268. releasePlatform: "linux-aarch64",
  269. }),
  270. );
  271. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  272. });
  273. it("开发态默认不初始化自动更新", async () => {
  274. appMock.isPackaged = false;
  275. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  276. await initAutoUpdater();
  277. expect(autoUpdaterMock.setFeedURL).not.toHaveBeenCalled();
  278. expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled();
  279. expect(autoUpdaterMock.forceDevUpdateConfig).toBe(false);
  280. });
  281. it("显式开启开发态自动更新时会覆盖本地版本并发起检查", async () => {
  282. appMock.isPackaged = false;
  283. appMock.getVersion.mockReturnValue("1.0.0");
  284. process.env["ZCODE_AUTO_UPDATE_DEV"] = "1";
  285. process.env["ZCODE_AUTO_UPDATE_DEV_VERSION"] = "3.3.1";
  286. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  287. await initAutoUpdater();
  288. expect(autoUpdaterMock.forceDevUpdateConfig).toBe(true);
  289. expect(autoUpdaterMock.currentVersion?.format()).toBe("3.3.1");
  290. expect(autoUpdaterMock.setFeedURL).toHaveBeenCalledWith(
  291. expect.objectContaining({
  292. provider: "custom",
  293. }),
  294. );
  295. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  296. expect(loggerInfoMock).toHaveBeenCalledWith("[auto-update] dev update enabled version=3.3.1");
  297. });
  298. it("服务端 manifest provider 会按设置选择 stable 或 preview 通道", async () => {
  299. settingServiceMock.get.mockResolvedValue({
  300. recentProjects: [],
  301. locale: "en-US",
  302. receivePreviewUpdates: true,
  303. });
  304. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  305. initAutoUpdater({
  306. settingService: settingServiceMock,
  307. deviceMid: "mid-1",
  308. resolveEndpointOrigin: () => "https://endpoint.example.test",
  309. });
  310. const options = autoUpdaterMock.setFeedURL.mock.calls[0]?.[0] as {
  311. deviceMid?: string;
  312. resolveEndpointOrigin?: () => string | Promise<string>;
  313. resolveReleaseChannel?: () => Promise<string>;
  314. };
  315. expect(options.deviceMid).toBe("mid-1");
  316. await expect(Promise.resolve(options.resolveEndpointOrigin?.())).resolves.toBe(
  317. "https://endpoint.example.test",
  318. );
  319. await expect(options.resolveReleaseChannel?.()).resolves.toBe("preview");
  320. });
  321. it("preview 冷启动检查不会把合法 preview 更新误判为 stale", async () => {
  322. settingServiceMock.get.mockResolvedValue({
  323. recentProjects: [],
  324. locale: "en-US",
  325. receivePreviewUpdates: true,
  326. });
  327. const { getAutoUpdaterState, initAutoUpdater } = await import("../src/main/autoUpdater.js");
  328. initAutoUpdater({
  329. settingService: settingServiceMock,
  330. deviceMid: "mid-preview",
  331. resolveEndpointOrigin: () => "https://endpoint.example.test",
  332. });
  333. await new Promise((resolve) => setTimeout(resolve, 0));
  334. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  335. autoUpdaterMock.emit("update-available", {
  336. version: "3.3.3",
  337. zcodeReleaseChannel: "preview",
  338. });
  339. await new Promise((resolve) => setTimeout(resolve, 0));
  340. // Bugfix: 冷启动时 provider 还没提前 resolveReleaseChannel,begin 阶段不能继续用默认 stable
  341. // 作为 expected channel,否则合法 preview manifest 会被 shouldIgnoreStaleAvailableUpdate 丢弃。
  342. expect(getAutoUpdaterState()).toMatchObject({
  343. kind: "update-available",
  344. version: "3.3.3",
  345. channel: "preview",
  346. });
  347. });
  348. it("关闭接收 preview 后会重新检查 stable manifest 并更新可用版本状态", async () => {
  349. const win = {
  350. isDestroyed: () => false,
  351. webContents: {
  352. id: 18,
  353. send: vi.fn(),
  354. },
  355. };
  356. browserWindows.push(win);
  357. settingServiceMock.get.mockResolvedValue({
  358. recentProjects: [],
  359. locale: "en-US",
  360. receivePreviewUpdates: true,
  361. });
  362. const { getAutoUpdaterState, initAutoUpdater, refreshAutoUpdaterReleaseChannel } =
  363. await import("../src/main/autoUpdater.js");
  364. initAutoUpdater({ settingService: settingServiceMock });
  365. const options = autoUpdaterMock.setFeedURL.mock.calls[0]?.[0] as {
  366. resolveReleaseChannel?: () => Promise<string>;
  367. };
  368. await expect(options.resolveReleaseChannel?.()).resolves.toBe("preview");
  369. await Promise.resolve();
  370. await Promise.resolve();
  371. autoUpdaterMock.emit("update-available", { version: "3.3.3" });
  372. await new Promise((resolve) => setTimeout(resolve, 0));
  373. expect(getAutoUpdaterState()).toMatchObject({
  374. kind: "update-available",
  375. version: "3.3.3",
  376. channel: "preview",
  377. });
  378. settingServiceMock.get.mockResolvedValue({
  379. recentProjects: [],
  380. locale: "en-US",
  381. receivePreviewUpdates: false,
  382. });
  383. refreshAutoUpdaterReleaseChannel(false, "test preview setting changed");
  384. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  385. expect(getAutoUpdaterState()).toMatchObject({
  386. kind: "checking",
  387. enabled: false,
  388. });
  389. await expect(options.resolveReleaseChannel?.()).resolves.toBe("stable");
  390. autoUpdaterMock.emit("update-available", { version: "3.3.2" });
  391. await new Promise((resolve) => setTimeout(resolve, 0));
  392. expect(getAutoUpdaterState()).toMatchObject({
  393. kind: "update-available",
  394. version: "3.3.2",
  395. channel: "stable",
  396. });
  397. expect(win.webContents.send).toHaveBeenCalledWith(
  398. PlatformChannels.UpdateStateChanged,
  399. expect.objectContaining({
  400. kind: "update-available",
  401. version: "3.3.2",
  402. channel: "stable",
  403. }),
  404. );
  405. });
  406. it("切换到 preview 后会忽略晚到的 stable manifest 结果", async () => {
  407. const win = {
  408. isDestroyed: () => false,
  409. webContents: {
  410. id: 19,
  411. send: vi.fn(),
  412. },
  413. };
  414. browserWindows.push(win);
  415. settingServiceMock.get.mockResolvedValue({
  416. recentProjects: [],
  417. locale: "en-US",
  418. receivePreviewUpdates: false,
  419. });
  420. const { getAutoUpdaterState, initAutoUpdater, refreshAutoUpdaterReleaseChannel } =
  421. await import("../src/main/autoUpdater.js");
  422. initAutoUpdater({ settingService: settingServiceMock });
  423. autoUpdaterMock.emit("checking-for-update");
  424. autoUpdaterMock.emit("update-available", {
  425. version: "3.3.4",
  426. zcodeReleaseChannel: "stable",
  427. });
  428. await new Promise((resolve) => setTimeout(resolve, 0));
  429. expect(getAutoUpdaterState()).toMatchObject({
  430. kind: "update-available",
  431. version: "3.3.4",
  432. channel: "stable",
  433. });
  434. settingServiceMock.get.mockResolvedValue({
  435. recentProjects: [],
  436. locale: "en-US",
  437. receivePreviewUpdates: true,
  438. });
  439. refreshAutoUpdaterReleaseChannel(true, "test preview setting changed");
  440. expect(getAutoUpdaterState()).toMatchObject({
  441. kind: "checking",
  442. enabled: false,
  443. });
  444. autoUpdaterMock.emit("update-available", {
  445. version: "3.3.4",
  446. zcodeReleaseChannel: "stable",
  447. });
  448. await new Promise((resolve) => setTimeout(resolve, 0));
  449. expect(getAutoUpdaterState()).toMatchObject({
  450. kind: "checking",
  451. enabled: false,
  452. });
  453. autoUpdaterMock.emit("update-available", {
  454. version: "3.3.5",
  455. zcodeReleaseChannel: "preview",
  456. });
  457. await new Promise((resolve) => setTimeout(resolve, 0));
  458. expect(getAutoUpdaterState()).toMatchObject({
  459. kind: "update-available",
  460. version: "3.3.5",
  461. channel: "preview",
  462. });
  463. expect(win.webContents.send).toHaveBeenCalledWith(
  464. PlatformChannels.UpdateStateChanged,
  465. expect.objectContaining({
  466. kind: "update-available",
  467. version: "3.3.5",
  468. channel: "preview",
  469. }),
  470. );
  471. });
  472. it("update-available 异步处理完成前切换通道会延后到当前 generation 收口", async () => {
  473. let resolveSettings:
  474. | ((settings: Awaited<ReturnType<typeof settingServiceMock.get>>) => void)
  475. | undefined;
  476. const pendingSettings = new Promise<Awaited<ReturnType<typeof settingServiceMock.get>>>(
  477. (resolve) => {
  478. resolveSettings = resolve;
  479. },
  480. );
  481. settingServiceMock.get.mockReturnValue(pendingSettings);
  482. const { getAutoUpdaterState, initAutoUpdater, refreshAutoUpdaterReleaseChannel } =
  483. await import("../src/main/autoUpdater.js");
  484. initAutoUpdater({ settingService: settingServiceMock });
  485. autoUpdaterMock.emit("checking-for-update");
  486. autoUpdaterMock.emit("update-available", {
  487. version: "3.3.4",
  488. zcodeReleaseChannel: "stable",
  489. });
  490. await Promise.resolve();
  491. await Promise.resolve();
  492. refreshAutoUpdaterReleaseChannel(true, "test preview setting changed");
  493. // Bugfix: 有 settingService 时,启动检查会先预热 channel 再真正请求 provider。
  494. // pending settings 阶段仍处于 in-flight,通道切换必须被延后,但请求尚未发出。
  495. expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled();
  496. expect(getAutoUpdaterState()).toMatchObject({
  497. kind: "checking",
  498. enabled: false,
  499. });
  500. resolveSettings?.({
  501. recentProjects: [],
  502. locale: "en-US",
  503. receivePreviewUpdates: false,
  504. });
  505. await new Promise((resolve) => setTimeout(resolve, 0));
  506. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  507. expect(getAutoUpdaterState()).toMatchObject({
  508. kind: "checking",
  509. enabled: false,
  510. });
  511. });
  512. it("冷启动恢复待安装说明后同版本 manifest 仍会重新下载以重建 macOS staging", async () => {
  513. mockProcessPlatform("darwin");
  514. appMock.getVersion.mockReturnValue("3.5.0");
  515. const pendingReleaseNotes = {
  516. version: "3.6.4",
  517. title: "Release v3.6.4",
  518. markdown: "## Fixes",
  519. releaseDate: "2026-07-30T16:56:00.356Z",
  520. };
  521. settingServiceMock.get.mockResolvedValue({
  522. recentProjects: [],
  523. locale: "en-US",
  524. autoDownloadAndInstallUpdates: true,
  525. pendingPostUpdateReleaseNotes: pendingReleaseNotes,
  526. });
  527. const { getAutoUpdaterState, hydratePendingPostUpdateReleaseNotes, initAutoUpdater } =
  528. await import("../src/main/autoUpdater.js");
  529. await hydratePendingPostUpdateReleaseNotes(settingServiceMock);
  530. await initAutoUpdater({ settingService: settingServiceMock });
  531. await Promise.resolve();
  532. autoUpdaterMock.emit("update-available", {
  533. version: "3.6.4",
  534. zcodeReleaseChannel: "stable",
  535. releaseName: "Release v3.6.4",
  536. releaseNotes: "## Fixes",
  537. });
  538. await new Promise((resolve) => setTimeout(resolve, 0));
  539. // Bugfix: pendingPostUpdateReleaseNotes 只能恢复展示文案,不能证明当前进程的
  540. // electron-updater / Squirrel.Mac 已经重建 native staging。遇到同版本 manifest
  541. // 时仍要重新走 downloadUpdate,让缓存命中或重新下载后的 update-downloaded
  542. // 事件把真实可安装状态带回来。
  543. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  544. expect(getAutoUpdaterState()).toMatchObject({
  545. kind: "update-available",
  546. version: "3.6.4",
  547. channel: "stable",
  548. });
  549. });
  550. it("冷启动恢复的待安装状态被点击时不会执行退出准备而是重新 staging", async () => {
  551. mockProcessPlatform("darwin");
  552. appMock.getVersion.mockReturnValue("3.5.0");
  553. const onBeforeQuitAndInstall = vi.fn();
  554. settingServiceMock.get.mockResolvedValue({
  555. recentProjects: [],
  556. locale: "en-US",
  557. autoDownloadAndInstallUpdates: true,
  558. pendingPostUpdateReleaseNotes: {
  559. version: "3.6.4",
  560. title: "Release v3.6.4",
  561. markdown: "## Fixes",
  562. },
  563. });
  564. const { getAutoUpdaterState, hydratePendingPostUpdateReleaseNotes, initAutoUpdater } =
  565. await import("../src/main/autoUpdater.js");
  566. await hydratePendingPostUpdateReleaseNotes(settingServiceMock);
  567. await initAutoUpdater({
  568. settingService: settingServiceMock,
  569. onBeforeQuitAndInstall,
  570. });
  571. const quitAndInstallHandler = ipcMainHandle.mock.calls.find(
  572. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  573. )?.[1] as (() => Promise<void>) | undefined;
  574. await quitAndInstallHandler?.();
  575. // Bugfix: 从 pending release notes 恢复出的 ready 没有当前进程内的
  576. // Squirrel.Mac staging 上下文,不能执行退出准备。用户点击时应先恢复为
  577. // 可下载更新并重新 downloadUpdate,等真实 update-downloaded 后再允许安装。
  578. expect(onBeforeQuitAndInstall).not.toHaveBeenCalled();
  579. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  580. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  581. expect(getAutoUpdaterState()).toMatchObject({
  582. kind: "update-available",
  583. version: "3.6.4",
  584. channel: "stable",
  585. });
  586. });
  587. it("晚到的旧通道结果不会结束当前通道的检查 generation", async () => {
  588. const { getAutoUpdaterState, initAutoUpdater, refreshAutoUpdaterReleaseChannel } =
  589. await import("../src/main/autoUpdater.js");
  590. initAutoUpdater({ settingService: settingServiceMock });
  591. autoUpdaterMock.emit("update-not-available", { version: "0.1.24" });
  592. await new Promise((resolve) => setTimeout(resolve, 0));
  593. const previewCheckPromise = new Promise<void>(() => {});
  594. autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => previewCheckPromise);
  595. refreshAutoUpdaterReleaseChannel(true, "test preview setting changed");
  596. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  597. expect(getAutoUpdaterState()).toMatchObject({
  598. kind: "checking",
  599. enabled: false,
  600. });
  601. autoUpdaterMock.emit("update-available", {
  602. version: "3.3.4",
  603. zcodeReleaseChannel: "stable",
  604. });
  605. await new Promise((resolve) => setTimeout(resolve, 0));
  606. refreshAutoUpdaterReleaseChannel(false, "test stable setting changed");
  607. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  608. expect(getAutoUpdaterState()).toMatchObject({
  609. kind: "checking",
  610. enabled: false,
  611. });
  612. autoUpdaterMock.emit("update-available", {
  613. version: "3.3.5",
  614. zcodeReleaseChannel: "preview",
  615. });
  616. await new Promise((resolve) => setTimeout(resolve, 0));
  617. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(3);
  618. expect(getAutoUpdaterState()).toMatchObject({
  619. kind: "checking",
  620. enabled: false,
  621. });
  622. });
  623. it("启动参数中的 update feed URL 优先于环境变量", async () => {
  624. const { resolveUpdateFeedSourceFromStartupConfig } = await import("../src/main/autoUpdater.js");
  625. expect(
  626. resolveUpdateFeedSourceFromStartupConfig({
  627. argv: [
  628. "ZCode",
  629. "--zcode-update-feed-url",
  630. "https://arg.example.test/api/v1/releases/electron/manifest",
  631. ],
  632. env: {
  633. ZCODE_UPDATE_FEED_URL: "https://env.example.test/api/v1/releases/electron/manifest",
  634. },
  635. }),
  636. ).toEqual({
  637. url: "https://arg.example.test/api/v1/releases/electron/manifest",
  638. });
  639. expect(
  640. resolveUpdateFeedSourceFromStartupConfig({
  641. argv: [
  642. "ZCode",
  643. "--zcode-update-feed-url=https://equals.example.test/api/v1/releases/electron/manifest",
  644. ],
  645. env: {},
  646. }),
  647. ).toEqual({
  648. url: "https://equals.example.test/api/v1/releases/electron/manifest",
  649. });
  650. expect(
  651. resolveUpdateFeedSourceFromStartupConfig({
  652. argv: ["ZCode"],
  653. env: {
  654. ZCODE_UPDATE_FEED_URL: "https://env.example.test/api/v1/releases/electron/manifest",
  655. },
  656. }),
  657. ).toEqual({
  658. url: "https://env.example.test/api/v1/releases/electron/manifest",
  659. });
  660. });
  661. it("启动时可覆盖服务端 manifest 接口 URL", async () => {
  662. mockProcessPlatform("darwin");
  663. process.env["TEST_UPDATER_ARCH"] = "arm64";
  664. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  665. initAutoUpdater({
  666. updateFeedSource: {
  667. url: "https://zcode.z.ai/api/v1/releases/electron/manifest?platform=old&channel=1",
  668. },
  669. });
  670. expect(autoUpdaterMock.setFeedURL).toHaveBeenCalledWith(
  671. expect.objectContaining({
  672. provider: "custom",
  673. manifestUrl:
  674. "https://zcode.z.ai/api/v1/releases/electron/manifest?platform=old&channel=1",
  675. releasePlatform: "darwin-aarch64",
  676. }),
  677. );
  678. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  679. });
  680. it("manifest URL 覆盖不会切换到 generic feed", async () => {
  681. mockProcessPlatform("darwin");
  682. process.env["TEST_UPDATER_ARCH"] = "arm64";
  683. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  684. initAutoUpdater({
  685. updateFeedSource: {
  686. url: "https://runtime.example.test/api/v1/releases/electron/manifest",
  687. },
  688. });
  689. expect(autoUpdaterMock.setFeedURL).toHaveBeenCalledWith(
  690. expect.objectContaining({
  691. provider: "custom",
  692. manifestUrl: "https://runtime.example.test/api/v1/releases/electron/manifest",
  693. }),
  694. );
  695. expect(autoUpdaterMock.setFeedURL).not.toHaveBeenCalledWith(
  696. expect.objectContaining({ provider: "generic" }),
  697. );
  698. });
  699. it("下载完成后会缓存版本,并补发给后续窗口", async () => {
  700. const firstWindow = {
  701. isDestroyed: () => false,
  702. webContents: {
  703. id: 1,
  704. send: vi.fn(),
  705. },
  706. };
  707. browserWindows.push(firstWindow);
  708. const { initAutoUpdater, syncReadyUpdateToWindow } = await import("../src/main/autoUpdater.js");
  709. initAutoUpdater();
  710. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  711. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  712. expect(firstWindow.webContents.send).toHaveBeenCalledWith(
  713. PlatformChannels.UpdateReady,
  714. "0.1.25",
  715. );
  716. const laterWindow = {
  717. isDestroyed: () => false,
  718. webContents: {
  719. id: 2,
  720. send: vi.fn(),
  721. },
  722. };
  723. syncReadyUpdateToWindow(laterWindow);
  724. expect(laterWindow.webContents.send).toHaveBeenCalledWith(
  725. PlatformChannels.UpdateReady,
  726. "0.1.25",
  727. );
  728. });
  729. it("下载完成后 updater 报错会清理 ready 状态", async () => {
  730. const win = {
  731. isDestroyed: () => false,
  732. webContents: {
  733. id: 5,
  734. send: vi.fn(),
  735. },
  736. };
  737. browserWindows.push(win);
  738. const { initAutoUpdater, syncReadyUpdateToWindow } = await importAutoUpdaterWithLocale();
  739. initAutoUpdater();
  740. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  741. expect(menuItem.label).toBe(
  742. formatDesktopMenuMessage(TEST_LOCALE, desktopMenuMessageIds.helpRestartToUpdate, {
  743. version: "0.1.25",
  744. }),
  745. );
  746. win.webContents.send.mockClear();
  747. autoUpdaterMock.emit(
  748. "error",
  749. new Error("Could not locate update bundle for com.github.Electron"),
  750. );
  751. await Promise.resolve();
  752. // Bugfix: Squirrel.Mac 可能在 update-downloaded 后才发现 zip 不能 stage。
  753. // 此时不能继续补发 ready 或保留“重启以更新”,否则用户再次点击仍然没有安装器接管。
  754. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  755. kind: "idle",
  756. enabled: true,
  757. });
  758. expect(menuItem.label).toBe(
  759. formatDesktopMenuMessage(TEST_LOCALE, desktopMenuMessageIds.helpCheckForUpdates),
  760. );
  761. const laterWindow = {
  762. isDestroyed: () => false,
  763. webContents: {
  764. id: 6,
  765. send: vi.fn(),
  766. },
  767. };
  768. syncReadyUpdateToWindow(laterWindow);
  769. expect(laterWindow.webContents.send).not.toHaveBeenCalledWith(
  770. PlatformChannels.UpdateReady,
  771. "0.1.25",
  772. );
  773. });
  774. it("开发态缓存包 ready 后的 Squirrel 迟到错误不会关闭待安装状态", async () => {
  775. mockProcessPlatform("darwin");
  776. appMock.isPackaged = false;
  777. process.env["ZCODE_AUTO_UPDATE_DEV"] = "1";
  778. const win = {
  779. isDestroyed: () => false,
  780. webContents: {
  781. id: 7,
  782. send: vi.fn(),
  783. },
  784. };
  785. browserWindows.push(win);
  786. const { initAutoUpdater, syncReadyUpdateToWindow } = await importAutoUpdaterWithLocale();
  787. initAutoUpdater();
  788. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  789. expect(menuItem.label).toBe(
  790. formatDesktopMenuMessage(TEST_LOCALE, desktopMenuMessageIds.helpRestartToUpdate, {
  791. version: "0.1.25",
  792. }),
  793. );
  794. win.webContents.send.mockClear();
  795. autoUpdaterMock.emit("error", {
  796. code: 2,
  797. message: "Could not locate update bundle for com.github.Electron",
  798. domain: "SQRLUpdaterErrorDomain",
  799. });
  800. await Promise.resolve();
  801. // 修复原因:开发态验证真实测试环境 manifest 时,Squirrel.Mac 仍可能在
  802. // update-downloaded 后补一个 code=2。生产 staging error 仍要清 ready,
  803. // 但开发态不能因此让弹窗自动关闭。
  804. expect(win.webContents.send).not.toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  805. kind: "idle",
  806. enabled: true,
  807. });
  808. expect(menuItem.label).toBe(
  809. formatDesktopMenuMessage(TEST_LOCALE, desktopMenuMessageIds.helpRestartToUpdate, {
  810. version: "0.1.25",
  811. }),
  812. );
  813. expect(loggerWarnMock).toHaveBeenCalledWith(
  814. expect.stringContaining("[auto-update] ignore dev Squirrel ready error"),
  815. );
  816. const laterWindow = {
  817. isDestroyed: () => false,
  818. webContents: {
  819. id: 8,
  820. send: vi.fn(),
  821. },
  822. };
  823. syncReadyUpdateToWindow(laterWindow);
  824. expect(laterWindow.webContents.send).toHaveBeenCalledWith(
  825. PlatformChannels.UpdateReady,
  826. "0.1.25",
  827. );
  828. });
  829. it("在没有已下载更新时不会误发 update-ready", async () => {
  830. const { syncReadyUpdateToWindow } = await import("../src/main/autoUpdater.js");
  831. const win = {
  832. isDestroyed: () => false,
  833. webContents: {
  834. id: 3,
  835. send: vi.fn(),
  836. },
  837. };
  838. syncReadyUpdateToWindow(win);
  839. expect(win.webContents.send).not.toHaveBeenCalled();
  840. });
  841. it("下载过程中不会提前向 renderer 宣告 update-ready", async () => {
  842. const releaseNotes = {
  843. version: "0.1.25",
  844. releaseName: "Release v0.1.25",
  845. releaseNotes: "# Release v0.1.25\n\n- downloading notes",
  846. releaseDate: "2026-06-23T13:48:54.438Z",
  847. };
  848. const expectedReleaseNotes = {
  849. version: "0.1.25",
  850. title: "Release v0.1.25",
  851. markdown: "# Release v0.1.25\n\n- downloading notes",
  852. releaseDate: "2026-06-23T13:48:54.438Z",
  853. };
  854. const win = {
  855. isDestroyed: () => false,
  856. webContents: {
  857. id: 4,
  858. send: vi.fn(),
  859. },
  860. };
  861. browserWindows.push(win);
  862. const { downloadAvailableUpdate, initAutoUpdater } = await importAutoUpdaterWithLocale();
  863. // Bugfix: autoUpdater 菜单文案已经改成跟随当前 locale。
  864. // 这个单测之前直接断言英文常量,实际却没有像 main 进程那样先同步应用语言,
  865. // 于是模块会落回 DEFAULT_LOCALE,导致“下载中”文案在测试环境里变成中文。
  866. // 这里显式设成 en-US,让断言验证的是“下载进度状态”本身,而不是隐式依赖默认语言。
  867. initAutoUpdater();
  868. // 回归保护:按钮显示完全依赖 renderer 收到 PlatformChannels.UpdateReady。
  869. // 如果这里在 update-available / download-progress 阶段就提前发事件,
  870. // UI 会误以为“更新已可安装”,用户看到的就是下载尚未完成却已经出现重启更新按钮。
  871. autoUpdaterMock.emit("update-available", releaseNotes);
  872. await new Promise((resolve) => setTimeout(resolve, 0));
  873. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  874. downloadAvailableUpdate("test");
  875. autoUpdaterMock.emit("download-progress", {
  876. percent: 42,
  877. bytesPerSecond: 1024,
  878. transferred: 1024,
  879. total: 2048,
  880. });
  881. expect(win.webContents.send).not.toHaveBeenCalledWith(
  882. PlatformChannels.UpdateReady,
  883. expect.anything(),
  884. );
  885. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  886. kind: "update-available",
  887. enabled: true,
  888. version: "0.1.25",
  889. channel: "stable",
  890. releaseNotes: expectedReleaseNotes,
  891. });
  892. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  893. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  894. kind: "download-progress",
  895. enabled: false,
  896. progress: "42",
  897. version: "0.1.25",
  898. channel: "stable",
  899. releaseNotes: expectedReleaseNotes,
  900. transferredBytes: 1024,
  901. totalBytes: 2048,
  902. });
  903. expect(menuItem.label).toBe(getExpectedDownloadingProgressLabel(42));
  904. expect(menuItem.enabled).toBe(false);
  905. });
  906. it("收到真实下载进度时会通知状态监听器", async () => {
  907. const { downloadAvailableUpdate, initAutoUpdater, onAutoUpdaterStateChanged } =
  908. await importAutoUpdaterWithLocale();
  909. initAutoUpdater();
  910. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  911. await new Promise((resolve) => setTimeout(resolve, 0));
  912. const listener = vi.fn();
  913. const dispose = onAutoUpdaterStateChanged(listener);
  914. downloadAvailableUpdate("test");
  915. autoUpdaterMock.emit("download-progress", {
  916. percent: 7,
  917. bytesPerSecond: 1024,
  918. transferred: 1024,
  919. total: 2048,
  920. });
  921. dispose();
  922. expect(listener).toHaveBeenCalledWith(
  923. expect.objectContaining({
  924. kind: "download-progress",
  925. enabled: false,
  926. progress: "7",
  927. version: "0.1.25",
  928. }),
  929. );
  930. });
  931. it("命中已下载缓存时不会先广播 0% 下载态,会直接进入已下载状态", async () => {
  932. const win = {
  933. isDestroyed: () => false,
  934. webContents: {
  935. id: 42,
  936. send: vi.fn(),
  937. },
  938. };
  939. browserWindows.push(win);
  940. const { downloadAvailableUpdate, getAutoUpdaterState, initAutoUpdater } =
  941. await importAutoUpdaterWithLocale();
  942. initAutoUpdater();
  943. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  944. await new Promise((resolve) => setTimeout(resolve, 0));
  945. downloadAvailableUpdate("test");
  946. expect(getAutoUpdaterState()).toMatchObject({
  947. kind: "update-available",
  948. version: "0.1.25",
  949. });
  950. expect(win.webContents.send).not.toHaveBeenCalledWith(
  951. PlatformChannels.UpdateStateChanged,
  952. expect.objectContaining({
  953. kind: "download-progress",
  954. progress: "0",
  955. }),
  956. );
  957. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  958. expect(getAutoUpdaterState()).toMatchObject({
  959. kind: "update-downloaded",
  960. version: "0.1.25",
  961. });
  962. expect(win.webContents.send).toHaveBeenCalledWith(
  963. PlatformChannels.UpdateStateChanged,
  964. expect.objectContaining({
  965. kind: "update-downloaded",
  966. version: "0.1.25",
  967. }),
  968. );
  969. });
  970. it("开启自动下载并安装偏好后发现更新会自动开始下载", async () => {
  971. settingServiceMock.get.mockResolvedValue({
  972. recentProjects: [],
  973. locale: "en-US",
  974. autoDownloadAndInstallUpdates: true,
  975. });
  976. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  977. initAutoUpdater({ settingService: settingServiceMock });
  978. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  979. await new Promise((resolve) => setTimeout(resolve, 0));
  980. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  981. expect(getAutoUpdaterState()).toMatchObject({
  982. kind: "update-available",
  983. version: "0.1.25",
  984. });
  985. });
  986. it("发现更新后只有 renderer 请求才会开始下载", async () => {
  987. const { initAutoUpdater } = await importAutoUpdaterWithLocale();
  988. initAutoUpdater();
  989. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  990. await new Promise((resolve) => setTimeout(resolve, 0));
  991. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  992. const downloadHandler = ipcMainHandle.mock.calls.find(
  993. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  994. )?.[1] as (() => void) | undefined;
  995. expect(downloadHandler).toBeTypeOf("function");
  996. downloadHandler?.();
  997. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  998. });
  999. it("取消下载会中断 token 并回到当前可更新版本", async () => {
  1000. const releaseNotes = {
  1001. version: "0.1.25",
  1002. releaseName: "Release v0.1.25",
  1003. releaseNotes: "# Release v0.1.25\n\n- cancellable notes",
  1004. releaseDate: "2026-06-23T13:48:54.438Z",
  1005. };
  1006. const expectedReleaseNotes = {
  1007. version: "0.1.25",
  1008. title: "Release v0.1.25",
  1009. markdown: "# Release v0.1.25\n\n- cancellable notes",
  1010. releaseDate: "2026-06-23T13:48:54.438Z",
  1011. };
  1012. const win = {
  1013. isDestroyed: () => false,
  1014. webContents: {
  1015. id: 6,
  1016. send: vi.fn(),
  1017. },
  1018. };
  1019. browserWindows.push(win);
  1020. autoUpdaterMock.downloadUpdate.mockImplementationOnce(
  1021. (token: EventEmitter) =>
  1022. new Promise((_resolve, reject) => {
  1023. token.once("cancel", () => reject(new Error("cancelled")));
  1024. }),
  1025. );
  1026. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1027. initAutoUpdater();
  1028. autoUpdaterMock.emit("update-available", releaseNotes);
  1029. await new Promise((resolve) => setTimeout(resolve, 0));
  1030. const downloadHandler = ipcMainHandle.mock.calls.find(
  1031. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  1032. )?.[1] as (() => void) | undefined;
  1033. const cancelHandler = ipcMainHandle.mock.calls.find(
  1034. ([channel]: [string, unknown]) => channel === PlatformChannels.CancelUpdateDownload,
  1035. )?.[1] as (() => void) | undefined;
  1036. expect(downloadHandler).toBeTypeOf("function");
  1037. expect(cancelHandler).toBeTypeOf("function");
  1038. downloadHandler?.();
  1039. const cancellationToken = autoUpdaterMock.downloadUpdate.mock.calls[0]?.[0] as
  1040. | { cancelled?: boolean }
  1041. | undefined;
  1042. expect(cancellationToken?.cancelled).toBe(false);
  1043. autoUpdaterMock.emit("download-progress", {
  1044. percent: 1,
  1045. bytesPerSecond: 1024,
  1046. transferred: 1,
  1047. total: 100,
  1048. });
  1049. expect(getAutoUpdaterState()).toEqual({
  1050. kind: "download-progress",
  1051. enabled: false,
  1052. progress: "1",
  1053. version: "0.1.25",
  1054. channel: "stable",
  1055. releaseNotes: expectedReleaseNotes,
  1056. transferredBytes: 1,
  1057. totalBytes: 100,
  1058. });
  1059. cancelHandler?.();
  1060. await Promise.resolve();
  1061. await Promise.resolve();
  1062. expect(cancellationToken?.cancelled).toBe(true);
  1063. expect(loggerErrorMock).not.toHaveBeenCalled();
  1064. expect(getAutoUpdaterState()).toEqual({
  1065. kind: "update-available",
  1066. enabled: true,
  1067. version: "0.1.25",
  1068. channel: "stable",
  1069. releaseNotes: expectedReleaseNotes,
  1070. });
  1071. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1072. kind: "update-available",
  1073. enabled: true,
  1074. version: "0.1.25",
  1075. channel: "stable",
  1076. releaseNotes: expectedReleaseNotes,
  1077. });
  1078. expect(menuItem.enabled).toBe(true);
  1079. win.webContents.send.mockClear();
  1080. autoUpdaterMock.emit("download-progress", {
  1081. percent: 63,
  1082. bytesPerSecond: 1024,
  1083. transferred: 1024,
  1084. total: 2048,
  1085. });
  1086. expect(getAutoUpdaterState()).toEqual({
  1087. kind: "update-available",
  1088. enabled: true,
  1089. version: "0.1.25",
  1090. channel: "stable",
  1091. releaseNotes: expectedReleaseNotes,
  1092. });
  1093. expect(win.webContents.send).not.toHaveBeenCalledWith(
  1094. PlatformChannels.UpdateStateChanged,
  1095. expect.objectContaining({
  1096. kind: "download-progress",
  1097. }),
  1098. );
  1099. autoUpdaterMock.emit("error", new Error("cancelled"));
  1100. expect(loggerErrorMock).not.toHaveBeenCalled();
  1101. expect(getAutoUpdaterState()).toEqual({
  1102. kind: "update-available",
  1103. enabled: true,
  1104. version: "0.1.25",
  1105. channel: "stable",
  1106. releaseNotes: expectedReleaseNotes,
  1107. });
  1108. });
  1109. it("下载启动失败后保留当前可更新版本供用户重试", async () => {
  1110. const releaseNotes = {
  1111. version: "0.1.25",
  1112. releaseName: "Release v0.1.25",
  1113. releaseNotes: "# Release v0.1.25\n\n- retryable notes",
  1114. releaseDate: "2026-06-23T13:48:54.438Z",
  1115. };
  1116. const expectedReleaseNotes = {
  1117. version: "0.1.25",
  1118. title: "Release v0.1.25",
  1119. markdown: "# Release v0.1.25\n\n- retryable notes",
  1120. releaseDate: "2026-06-23T13:48:54.438Z",
  1121. };
  1122. const win = {
  1123. isDestroyed: () => false,
  1124. webContents: {
  1125. id: 10,
  1126. send: vi.fn(),
  1127. },
  1128. };
  1129. browserWindows.push(win);
  1130. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1131. initAutoUpdater();
  1132. autoUpdaterMock.emit("update-available", releaseNotes);
  1133. await new Promise((resolve) => setTimeout(resolve, 0));
  1134. const downloadHandler = ipcMainHandle.mock.calls.find(
  1135. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  1136. )?.[1] as (() => void) | undefined;
  1137. downloadHandler?.();
  1138. expect(getAutoUpdaterState()).toMatchObject({
  1139. kind: "update-available",
  1140. version: "0.1.25",
  1141. });
  1142. autoUpdaterMock.emit("error", new Error("download failed before progress"));
  1143. await Promise.resolve();
  1144. // Bugfix: 下载失败不是跳过版本。不能广播 idle 让主入口和弹窗一起消失,
  1145. // 应退回可更新状态,保留同一版本供用户重试。
  1146. expect(getAutoUpdaterState()).toEqual({
  1147. kind: "update-available",
  1148. enabled: true,
  1149. version: "0.1.25",
  1150. channel: "stable",
  1151. releaseNotes: expectedReleaseNotes,
  1152. });
  1153. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1154. kind: "update-available",
  1155. enabled: true,
  1156. version: "0.1.25",
  1157. channel: "stable",
  1158. releaseNotes: expectedReleaseNotes,
  1159. });
  1160. expect(menuItem.enabled).toBe(true);
  1161. await Promise.resolve();
  1162. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1163. });
  1164. it("下载失败发生在检查收口前时,收口后再查一次", async () => {
  1165. let releaseCheck: (() => void) | undefined;
  1166. autoUpdaterMock.checkForUpdates.mockImplementationOnce(
  1167. () =>
  1168. new Promise((resolve) => {
  1169. releaseCheck = () => resolve(undefined);
  1170. }),
  1171. );
  1172. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1173. initAutoUpdater();
  1174. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1175. await Promise.resolve();
  1176. const downloadHandler = ipcMainHandle.mock.calls.find(
  1177. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  1178. )?.[1] as (() => void) | undefined;
  1179. autoUpdaterMock.downloadUpdate.mockRejectedValueOnce(new Error("network down"));
  1180. downloadHandler?.();
  1181. await Promise.resolve();
  1182. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  1183. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  1184. releaseCheck?.();
  1185. await Promise.resolve();
  1186. await Promise.resolve();
  1187. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1188. });
  1189. it("跳过当前版本会按 stable 通道持久化并清空 available 状态", async () => {
  1190. const win = {
  1191. isDestroyed: () => false,
  1192. webContents: {
  1193. id: 7,
  1194. send: vi.fn(),
  1195. },
  1196. };
  1197. browserWindows.push(win);
  1198. const { initAutoUpdater } = await importAutoUpdaterWithLocale();
  1199. initAutoUpdater({ settingService: settingServiceMock });
  1200. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1201. await new Promise((resolve) => setTimeout(resolve, 0));
  1202. const skipHandler = ipcMainHandle.mock.calls.find(
  1203. ([channel]: [string, unknown]) => channel === PlatformChannels.SkipUpdateVersion,
  1204. )?.[1] as ((event: unknown, version: string) => Promise<void>) | undefined;
  1205. expect(skipHandler).toBeTypeOf("function");
  1206. await skipHandler?.({}, "0.1.25");
  1207. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1208. skippedElectronUpdateVersions: {
  1209. stable: "0.1.25",
  1210. },
  1211. });
  1212. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1213. kind: "idle",
  1214. enabled: true,
  1215. });
  1216. });
  1217. it("下载中跳过当前版本会取消下载并持久化 skipped 状态", async () => {
  1218. const win = {
  1219. isDestroyed: () => false,
  1220. webContents: {
  1221. id: 8,
  1222. send: vi.fn(),
  1223. },
  1224. };
  1225. browserWindows.push(win);
  1226. autoUpdaterMock.downloadUpdate.mockImplementationOnce(
  1227. (token: EventEmitter) =>
  1228. new Promise((_resolve, reject) => {
  1229. token.once("cancel", () => reject(new Error("cancelled")));
  1230. }),
  1231. );
  1232. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1233. initAutoUpdater({ settingService: settingServiceMock });
  1234. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1235. await new Promise((resolve) => setTimeout(resolve, 0));
  1236. const downloadHandler = ipcMainHandle.mock.calls.find(
  1237. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  1238. )?.[1] as (() => void) | undefined;
  1239. const skipHandler = ipcMainHandle.mock.calls.find(
  1240. ([channel]: [string, unknown]) => channel === PlatformChannels.SkipUpdateVersion,
  1241. )?.[1] as ((event: unknown, version: string) => Promise<void>) | undefined;
  1242. downloadHandler?.();
  1243. const cancellationToken = autoUpdaterMock.downloadUpdate.mock.calls[0]?.[0] as
  1244. | { cancelled?: boolean }
  1245. | undefined;
  1246. await skipHandler?.({}, "0.1.25");
  1247. await Promise.resolve();
  1248. await Promise.resolve();
  1249. expect(cancellationToken?.cancelled).toBe(true);
  1250. expect(loggerErrorMock).not.toHaveBeenCalled();
  1251. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1252. skippedElectronUpdateVersions: {
  1253. stable: "0.1.25",
  1254. },
  1255. });
  1256. expect(getAutoUpdaterState()).toEqual({ kind: "idle", enabled: true });
  1257. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1258. kind: "idle",
  1259. enabled: true,
  1260. });
  1261. });
  1262. it("手动检查更新会清除当前通道的 skipped 缓存并重新显示该版本", async () => {
  1263. const win = {
  1264. isDestroyed: () => false,
  1265. webContents: {
  1266. id: 9,
  1267. send: vi.fn(),
  1268. },
  1269. };
  1270. browserWindows.push(win);
  1271. let settingsState = {
  1272. recentProjects: [],
  1273. locale: "en-US" as const,
  1274. skippedElectronUpdateVersions: {
  1275. preview: "0.2.0",
  1276. },
  1277. };
  1278. settingServiceMock.get.mockImplementation(async () => settingsState);
  1279. settingServiceMock.update.mockImplementation(async (patch) => {
  1280. settingsState = { ...settingsState, ...patch };
  1281. });
  1282. const { checkForUpdateMenuClick, getAutoUpdaterState, initAutoUpdater } =
  1283. await importAutoUpdaterWithLocale();
  1284. initAutoUpdater({ settingService: settingServiceMock });
  1285. await Promise.resolve();
  1286. await Promise.resolve();
  1287. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1288. await new Promise((resolve) => setTimeout(resolve, 0));
  1289. const skipHandler = ipcMainHandle.mock.calls.find(
  1290. ([channel]: [string, unknown]) => channel === PlatformChannels.SkipUpdateVersion,
  1291. )?.[1] as ((event: unknown, version: string) => Promise<void>) | undefined;
  1292. await skipHandler?.({}, "0.1.25");
  1293. expect(getAutoUpdaterState()).toEqual({ kind: "idle", enabled: true });
  1294. expect(settingsState.skippedElectronUpdateVersions).toEqual({
  1295. preview: "0.2.0",
  1296. stable: "0.1.25",
  1297. });
  1298. win.webContents.send.mockClear();
  1299. checkForUpdateMenuClick(win as never);
  1300. await new Promise((resolve) => setTimeout(resolve, 0));
  1301. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1302. expect(settingsState.skippedElectronUpdateVersions).toEqual({
  1303. preview: "0.2.0",
  1304. });
  1305. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1306. await new Promise((resolve) => setTimeout(resolve, 0));
  1307. // Bugfix: 手动检查代表用户重新关注被跳过版本。
  1308. // 只清当前 stable 通道的缓存,避免误删 preview 跳过记录,同时要让同版本更新重新展示。
  1309. expect(getAutoUpdaterState()).toEqual({
  1310. kind: "update-available",
  1311. enabled: true,
  1312. version: "0.1.25",
  1313. channel: "stable",
  1314. });
  1315. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  1316. kind: "available",
  1317. version: "0.1.25",
  1318. channel: "stable",
  1319. });
  1320. });
  1321. it("下载完成后会持久化版本说明,并且启动后只同步给一个窗口", async () => {
  1322. const firstWindow = {
  1323. isDestroyed: () => false,
  1324. webContents: {
  1325. id: 11,
  1326. send: vi.fn(),
  1327. },
  1328. };
  1329. const secondWindow = {
  1330. isDestroyed: () => false,
  1331. webContents: {
  1332. id: 12,
  1333. send: vi.fn(),
  1334. },
  1335. };
  1336. browserWindows.push(firstWindow, secondWindow);
  1337. const { initAutoUpdater, syncPostUpdateReleaseNotesToWindow } =
  1338. await import("../src/main/autoUpdater.js");
  1339. initAutoUpdater({ settingService: settingServiceMock });
  1340. autoUpdaterMock.emit("update-downloaded", {
  1341. version: "0.1.25",
  1342. releaseName: "Release v0.1.25",
  1343. releaseNotes: "# Release v0.1.25\n\n- add popup",
  1344. releaseDate: new Date("2026-06-23T13:48:54.438Z"),
  1345. releaseNotesByLocale: {
  1346. "zh-CN": {
  1347. title: "ZCode v0.1.25",
  1348. markdown: "# ZCode v0.1.25\n\n- 中文说明",
  1349. },
  1350. "en-US": {
  1351. title: "ZCode v0.1.25",
  1352. markdown: "# ZCode v0.1.25\n\n- English notes",
  1353. },
  1354. },
  1355. });
  1356. await Promise.resolve();
  1357. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1358. pendingPostUpdateReleaseNotes: {
  1359. version: "0.1.25",
  1360. title: "Release v0.1.25",
  1361. markdown: "# Release v0.1.25\n\n- add popup",
  1362. releaseDate: "2026-06-23T13:48:54.438Z",
  1363. releaseNotesByLocale: {
  1364. "zh-CN": {
  1365. title: "ZCode v0.1.25",
  1366. markdown: "# ZCode v0.1.25\n\n- 中文说明",
  1367. },
  1368. "en-US": {
  1369. title: "ZCode v0.1.25",
  1370. markdown: "# ZCode v0.1.25\n\n- English notes",
  1371. },
  1372. },
  1373. },
  1374. });
  1375. expect(firstWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1376. kind: "update-downloaded",
  1377. enabled: true,
  1378. version: "0.1.25",
  1379. channel: "stable",
  1380. releaseNotes: {
  1381. version: "0.1.25",
  1382. title: "Release v0.1.25",
  1383. markdown: "# Release v0.1.25\n\n- add popup",
  1384. releaseDate: "2026-06-23T13:48:54.438Z",
  1385. releaseNotesByLocale: {
  1386. "zh-CN": {
  1387. title: "ZCode v0.1.25",
  1388. markdown: "# ZCode v0.1.25\n\n- 中文说明",
  1389. },
  1390. "en-US": {
  1391. title: "ZCode v0.1.25",
  1392. markdown: "# ZCode v0.1.25\n\n- English notes",
  1393. },
  1394. },
  1395. },
  1396. });
  1397. // 安装后再次启动时,当前 app 版本才等于 pending 版本;这时 pending payload
  1398. // 才应作为 post-update release notes 同步给 renderer。
  1399. appMock.getVersion.mockImplementation(() => "0.1.25");
  1400. syncPostUpdateReleaseNotesToWindow(firstWindow as never);
  1401. syncPostUpdateReleaseNotesToWindow(secondWindow as never);
  1402. expect(firstWindow.webContents.send).toHaveBeenCalledWith(
  1403. PlatformChannels.PostUpdateReleaseNotes,
  1404. {
  1405. version: "0.1.25",
  1406. title: "Release v0.1.25",
  1407. markdown: "# Release v0.1.25\n\n- add popup",
  1408. releaseDate: "2026-06-23T13:48:54.438Z",
  1409. releaseNotesByLocale: {
  1410. "zh-CN": {
  1411. title: "ZCode v0.1.25",
  1412. markdown: "# ZCode v0.1.25\n\n- 中文说明",
  1413. },
  1414. "en-US": {
  1415. title: "ZCode v0.1.25",
  1416. markdown: "# ZCode v0.1.25\n\n- English notes",
  1417. },
  1418. },
  1419. },
  1420. );
  1421. expect(secondWindow.webContents.send).not.toHaveBeenCalledWith(
  1422. PlatformChannels.PostUpdateReleaseNotes,
  1423. expect.anything(),
  1424. );
  1425. });
  1426. it("没有 releaseNotes 时不会写入待展示说明", async () => {
  1427. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1428. initAutoUpdater({ settingService: settingServiceMock });
  1429. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1430. await Promise.resolve();
  1431. expect(settingServiceMock.update).not.toHaveBeenCalledWith(
  1432. expect.objectContaining({
  1433. pendingPostUpdateReleaseNotes: expect.anything(),
  1434. }),
  1435. );
  1436. });
  1437. it("renderer ack 后会清空待展示说明,不再重复补发", async () => {
  1438. appMock.getVersion.mockImplementation(() => "0.1.25");
  1439. const firstWindow = {
  1440. isDestroyed: () => false,
  1441. webContents: {
  1442. id: 21,
  1443. send: vi.fn(),
  1444. },
  1445. };
  1446. const laterWindow = {
  1447. isDestroyed: () => false,
  1448. webContents: {
  1449. id: 22,
  1450. send: vi.fn(),
  1451. },
  1452. };
  1453. browserWindows.push(firstWindow, laterWindow);
  1454. settingServiceMock.get.mockResolvedValue({
  1455. recentProjects: [],
  1456. locale: "en-US",
  1457. pendingPostUpdateReleaseNotes: {
  1458. version: "0.1.25",
  1459. title: "Release v0.1.25",
  1460. markdown: "# Release v0.1.25\n\n- add popup",
  1461. },
  1462. });
  1463. const {
  1464. acknowledgePostUpdateReleaseNotes,
  1465. hydratePendingPostUpdateReleaseNotes,
  1466. syncPostUpdateReleaseNotesToWindow,
  1467. } = await import("../src/main/autoUpdater.js");
  1468. await hydratePendingPostUpdateReleaseNotes(settingServiceMock);
  1469. syncPostUpdateReleaseNotesToWindow(firstWindow as never);
  1470. expect(firstWindow.webContents.send).toHaveBeenCalledWith(
  1471. PlatformChannels.PostUpdateReleaseNotes,
  1472. {
  1473. version: "0.1.25",
  1474. title: "Release v0.1.25",
  1475. markdown: "# Release v0.1.25\n\n- add popup",
  1476. },
  1477. );
  1478. await acknowledgePostUpdateReleaseNotes("0.1.25", settingServiceMock);
  1479. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1480. pendingPostUpdateReleaseNotes: undefined,
  1481. });
  1482. syncPostUpdateReleaseNotesToWindow(laterWindow as never);
  1483. expect(laterWindow.webContents.send).not.toHaveBeenCalledWith(
  1484. PlatformChannels.PostUpdateReleaseNotes,
  1485. expect.anything(),
  1486. );
  1487. });
  1488. it("hydrate 时若待展示版本低于已安装应用版本则丢弃,避免手动跳级安装后弹出旧版说明", async () => {
  1489. appMock.getVersion.mockImplementation(() => "0.1.26");
  1490. settingServiceMock.get.mockResolvedValue({
  1491. recentProjects: [],
  1492. locale: "en-US",
  1493. pendingPostUpdateReleaseNotes: {
  1494. version: "0.1.25",
  1495. title: "Release v0.1.25",
  1496. markdown: "# Release v0.1.25\n\n- old",
  1497. },
  1498. });
  1499. const { hydratePendingPostUpdateReleaseNotes, syncPostUpdateReleaseNotesToWindow } =
  1500. await import("../src/main/autoUpdater.js");
  1501. await hydratePendingPostUpdateReleaseNotes(settingServiceMock);
  1502. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1503. pendingPostUpdateReleaseNotes: undefined,
  1504. });
  1505. const win = {
  1506. isDestroyed: () => false,
  1507. webContents: {
  1508. id: 99,
  1509. send: vi.fn(),
  1510. },
  1511. };
  1512. syncPostUpdateReleaseNotesToWindow(win as never);
  1513. expect(win.webContents.send).not.toHaveBeenCalledWith(
  1514. PlatformChannels.PostUpdateReleaseNotes,
  1515. expect.anything(),
  1516. );
  1517. });
  1518. it("hydrate 时若待展示版本高于当前应用版本则恢复为待安装更新", async () => {
  1519. appMock.getVersion.mockImplementation(() => "0.1.24");
  1520. settingServiceMock.get.mockResolvedValue({
  1521. recentProjects: [],
  1522. locale: "en-US",
  1523. pendingPostUpdateReleaseNotes: {
  1524. version: "0.1.25",
  1525. title: "Release v0.1.25",
  1526. markdown: "# Release v0.1.25\n\n- cached",
  1527. },
  1528. });
  1529. const {
  1530. getAutoUpdaterState,
  1531. hydratePendingPostUpdateReleaseNotes,
  1532. syncPostUpdateReleaseNotesToWindow,
  1533. syncReadyUpdateToWindow,
  1534. } = await importAutoUpdaterWithLocale();
  1535. await hydratePendingPostUpdateReleaseNotes(settingServiceMock);
  1536. // Bugfix: 已下载但未安装时重启,pending release notes 的版本仍高于当前 app。
  1537. // 此时应恢复“重启以更新”,不能重新提示下载同一个已缓存版本。
  1538. expect(getAutoUpdaterState()).toEqual({
  1539. kind: "update-downloaded",
  1540. enabled: true,
  1541. version: "0.1.25",
  1542. releaseNotes: {
  1543. version: "0.1.25",
  1544. title: "Release v0.1.25",
  1545. markdown: "# Release v0.1.25\n\n- cached",
  1546. },
  1547. });
  1548. const readyWindow = {
  1549. isDestroyed: () => false,
  1550. webContents: {
  1551. id: 101,
  1552. send: vi.fn(),
  1553. },
  1554. };
  1555. syncReadyUpdateToWindow(readyWindow as never);
  1556. expect(readyWindow.webContents.send).toHaveBeenCalledWith(
  1557. PlatformChannels.UpdateReady,
  1558. "0.1.25",
  1559. );
  1560. const notesWindow = {
  1561. isDestroyed: () => false,
  1562. webContents: {
  1563. id: 102,
  1564. send: vi.fn(),
  1565. },
  1566. };
  1567. syncPostUpdateReleaseNotesToWindow(notesWindow as never);
  1568. expect(notesWindow.webContents.send).not.toHaveBeenCalledWith(
  1569. PlatformChannels.PostUpdateReleaseNotes,
  1570. expect.anything(),
  1571. );
  1572. });
  1573. it("用户确认安装更新前会先执行退出准备钩子", async () => {
  1574. mockProcessPlatform("darwin");
  1575. let resolveQuitPreparation: (() => void) | null = null;
  1576. const onBeforeQuitAndInstall = vi.fn(
  1577. () =>
  1578. new Promise<void>((resolve) => {
  1579. resolveQuitPreparation = resolve;
  1580. }),
  1581. );
  1582. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1583. initAutoUpdater({ onBeforeQuitAndInstall });
  1584. const quitHandler = ipcMainOn.mock.calls.find(
  1585. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1586. )?.[1] as (() => void) | undefined;
  1587. expect(quitHandler).toBeTypeOf("function");
  1588. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1589. await Promise.resolve();
  1590. quitHandler?.();
  1591. expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1);
  1592. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(0);
  1593. resolveQuitPreparation?.();
  1594. await Promise.resolve();
  1595. await Promise.resolve();
  1596. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1);
  1597. });
  1598. it("安装前退出准备失败时不会继续启动安装器或开发态重启", async () => {
  1599. mockProcessPlatform("win32");
  1600. const prepareError = new Error("host process still locked resources");
  1601. const onBeforeQuitAndInstall = vi.fn(async () => {
  1602. throw prepareError;
  1603. });
  1604. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1605. initAutoUpdater({ onBeforeQuitAndInstall });
  1606. const quitHandler = ipcMainHandle.mock.calls.find(
  1607. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1608. )?.[1] as (() => Promise<void>) | undefined;
  1609. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1610. await Promise.resolve();
  1611. expect(quitHandler).toBeTypeOf("function");
  1612. await expect(quitHandler!()).rejects.toBe(prepareError);
  1613. // Bugfix: 安装前准备负责释放 Windows resources/glm 等随包资源锁。
  1614. // 如果准备失败还继续启动安装器,会再次形成 bundled runtime 半更新。
  1615. expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1);
  1616. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  1617. expect(appMock.relaunch).not.toHaveBeenCalled();
  1618. expect(appMock.exit).not.toHaveBeenCalled();
  1619. expect(loggerErrorMock).toHaveBeenCalledWith(
  1620. "[auto-update] prepare quit and install failed:",
  1621. prepareError,
  1622. );
  1623. });
  1624. it("没有已下载更新时安装请求不会执行退出准备", async () => {
  1625. mockProcessPlatform("darwin");
  1626. const onBeforeQuitAndInstall = vi.fn();
  1627. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1628. initAutoUpdater({ onBeforeQuitAndInstall });
  1629. const quitHandler = ipcMainHandle.mock.calls.find(
  1630. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1631. )?.[1] as (() => Promise<void>) | undefined;
  1632. expect(quitHandler).toBeTypeOf("function");
  1633. await expect(quitHandler!()).rejects.toThrow("Update is not ready to install: state=idle");
  1634. // Bugfix: renderer 的旧 ready 缓存可能残留,但 main 已经因为 staging error
  1635. // 回到 idle。此时不能清理 host 或调用 quitAndInstall,否则按钮表现为无响应。
  1636. expect(onBeforeQuitAndInstall).not.toHaveBeenCalled();
  1637. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  1638. expect(loggerWarnMock).toHaveBeenCalledWith(
  1639. "[auto-update] ignore quitAndInstall request: state=idle",
  1640. );
  1641. });
  1642. it("Windows 安装更新恢复 electron-updater 原生入口,不再启动 PowerShell launcher", async () => {
  1643. mockProcessPlatform("win32");
  1644. const onBeforeQuitAndInstall = vi.fn();
  1645. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1646. initAutoUpdater({ onBeforeQuitAndInstall });
  1647. const quitHandler = ipcMainOn.mock.calls.find(
  1648. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1649. )?.[1] as (() => void) | undefined;
  1650. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1651. await Promise.resolve();
  1652. quitHandler?.();
  1653. await Promise.resolve();
  1654. await Promise.resolve();
  1655. expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1);
  1656. // Bugfix: 3.3.0 的 detached hidden PowerShell launcher 只证明 powershell.exe
  1657. // 创建成功,不能证明安装器脚本实际执行。Windows 也必须回到 electron-updater 原生入口。
  1658. expect(spawnMock).not.toHaveBeenCalled();
  1659. expect(appMock.exit).not.toHaveBeenCalled();
  1660. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1);
  1661. });
  1662. it("更新已下载后点击菜单会直接重启安装", async () => {
  1663. mockProcessPlatform("darwin");
  1664. const onBeforeQuitAndInstall = vi.fn();
  1665. const win = {
  1666. isDestroyed: () => false,
  1667. webContents: {
  1668. id: 21,
  1669. send: vi.fn(),
  1670. },
  1671. };
  1672. browserWindows.push(win);
  1673. const { initAutoUpdater, checkForUpdateMenuClick } = await import("../src/main/autoUpdater.js");
  1674. initAutoUpdater({ onBeforeQuitAndInstall });
  1675. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1676. win.webContents.send.mockClear();
  1677. checkForUpdateMenuClick(win as never);
  1678. await Promise.resolve();
  1679. await Promise.resolve();
  1680. // Bugfix: 菜单文案是“重启以更新”时,点击应和更新按钮一样真的安装;
  1681. // 旧逻辑只给 renderer 发 ready toast,用户看到的是“重启”但实际没有重启。
  1682. expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1);
  1683. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1);
  1684. expect(win.webContents.send).not.toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  1685. kind: "ready",
  1686. version: "0.1.25",
  1687. });
  1688. });
  1689. it("Windows 初始化时会关闭 quit 自动安装,避免关应用后立即关机打断更新", async () => {
  1690. mockProcessPlatform("win32");
  1691. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1692. initAutoUpdater();
  1693. expect(autoUpdaterMock.autoDownload).toBe(false);
  1694. expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false);
  1695. });
  1696. it("非 Windows 初始化时保持 quit 自动安装,避免影响既有升级行为", async () => {
  1697. mockProcessPlatform("darwin");
  1698. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1699. initAutoUpdater();
  1700. // 非 Windows 也不再让 electron-updater 在退出时直接装 staged 包。
  1701. // ready 包仍等于当前目标时,由 before-quit 主动安装;目标已经更高则跳过。
  1702. expect(autoUpdaterMock.autoDownload).toBe(false);
  1703. expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false);
  1704. });
  1705. it("Windows 启动时不阻塞主界面,后台检查更新", async () => {
  1706. mockProcessPlatform("win32");
  1707. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1708. // initAutoUpdater 现在立即返回,不等待更新检查完成
  1709. await expect(initAutoUpdater()).resolves.toBeUndefined();
  1710. // 更新检查应该在后台触发
  1711. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  1712. });
  1713. it("启动后会注册 15 分钟轮询,并在空闲时再次检查更新", async () => {
  1714. vi.useFakeTimers();
  1715. try {
  1716. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1717. initAutoUpdater();
  1718. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  1719. await vi.advanceTimersByTimeAsync(FIFTEEN_MINUTES_MS);
  1720. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1721. } finally {
  1722. vi.useRealTimers();
  1723. }
  1724. });
  1725. it("已发现更新后 2 分钟轮询会换成更高版本,且入口不进入 checking", async () => {
  1726. vi.useFakeTimers();
  1727. try {
  1728. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1729. initAutoUpdater();
  1730. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1731. await Promise.resolve();
  1732. await vi.advanceTimersByTimeAsync(TWO_MINUTES_MS);
  1733. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1734. autoUpdaterMock.emit("update-available", { version: "0.1.27" });
  1735. await Promise.resolve();
  1736. expect(getAutoUpdaterState()).toMatchObject({
  1737. kind: "update-available",
  1738. version: "0.1.27",
  1739. });
  1740. } finally {
  1741. vi.useRealTimers();
  1742. }
  1743. });
  1744. it("已发现更新后手动检查会重新请求并替换版本", async () => {
  1745. const win = {
  1746. isDestroyed: () => false,
  1747. webContents: { id: 51, send: vi.fn() },
  1748. };
  1749. browserWindows.push(win);
  1750. const { checkForUpdateMenuClick, getAutoUpdaterState, initAutoUpdater } =
  1751. await import("../src/main/autoUpdater.js");
  1752. initAutoUpdater();
  1753. await Promise.resolve();
  1754. await Promise.resolve();
  1755. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1756. await Promise.resolve();
  1757. checkForUpdateMenuClick(win as never);
  1758. await Promise.resolve();
  1759. autoUpdaterMock.emit("update-available", { version: "0.1.27" });
  1760. await Promise.resolve();
  1761. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1762. expect(getAutoUpdaterState()).toMatchObject({
  1763. kind: "update-available",
  1764. version: "0.1.27",
  1765. });
  1766. });
  1767. it("自动下载完成后立刻复查,更高版本会替换并重新下载", async () => {
  1768. settingServiceMock.get.mockResolvedValue({
  1769. recentProjects: [],
  1770. locale: "en-US",
  1771. autoDownloadAndInstallUpdates: true,
  1772. });
  1773. const { getAutoUpdaterState, initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1774. initAutoUpdater({ settingService: settingServiceMock });
  1775. await new Promise((resolve) => setTimeout(resolve, 0));
  1776. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1777. await new Promise((resolve) => setTimeout(resolve, 0));
  1778. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  1779. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1780. await new Promise((resolve) => setTimeout(resolve, 0));
  1781. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1782. autoUpdaterMock.emit("update-available", { version: "0.1.27" });
  1783. await new Promise((resolve) => setTimeout(resolve, 0));
  1784. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(2);
  1785. expect(getAutoUpdaterState()).toMatchObject({
  1786. kind: "update-available",
  1787. version: "0.1.27",
  1788. });
  1789. });
  1790. it("macOS 上旧 ready 包不再等于目标时退出不安装", async () => {
  1791. mockProcessPlatform("darwin");
  1792. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1793. initAutoUpdater();
  1794. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1795. autoUpdaterMock.emit("update-available", { version: "0.1.27" });
  1796. await Promise.resolve();
  1797. const event = { preventDefault: vi.fn() };
  1798. for (const listener of appListeners.get("before-quit") ?? []) {
  1799. listener(event);
  1800. }
  1801. expect(event.preventDefault).not.toHaveBeenCalled();
  1802. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  1803. });
  1804. it("下载中轮询不会并发触发新的检查", async () => {
  1805. vi.useFakeTimers();
  1806. try {
  1807. const { downloadAvailableUpdate, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1808. initAutoUpdater();
  1809. await Promise.resolve();
  1810. await Promise.resolve();
  1811. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1812. await Promise.resolve();
  1813. downloadAvailableUpdate("test");
  1814. autoUpdaterMock.emit("download-progress", {
  1815. percent: 10,
  1816. bytesPerSecond: 1024,
  1817. transferred: 1024,
  1818. total: 10240,
  1819. });
  1820. await vi.advanceTimersByTimeAsync(FIFTEEN_MINUTES_MS);
  1821. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  1822. } finally {
  1823. vi.useRealTimers();
  1824. }
  1825. });
  1826. it("已下载更新后轮询发现更高版本时先提示,用户确认后替换 ready 版本", async () => {
  1827. vi.useFakeTimers();
  1828. try {
  1829. const win = {
  1830. isDestroyed: () => false,
  1831. webContents: {
  1832. id: 41,
  1833. send: vi.fn(),
  1834. },
  1835. };
  1836. browserWindows.push(win);
  1837. const { downloadAvailableUpdate, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1838. initAutoUpdater();
  1839. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1840. autoUpdaterMock.downloadUpdate.mockClear();
  1841. win.webContents.send.mockClear();
  1842. await vi.advanceTimersByTimeAsync(TWO_MINUTES_MS);
  1843. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1844. autoUpdaterMock.emit("update-available", { version: "0.1.26" });
  1845. await Promise.resolve();
  1846. await Promise.resolve();
  1847. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  1848. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1849. kind: "update-available",
  1850. enabled: true,
  1851. version: "0.1.26",
  1852. channel: "stable",
  1853. });
  1854. downloadAvailableUpdate("test");
  1855. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  1856. autoUpdaterMock.emit("update-downloaded", { version: "0.1.26" });
  1857. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateReady, "0.1.26");
  1858. expect(menuItem.label).toBe(
  1859. formatDesktopMenuMessage(TEST_LOCALE, desktopMenuMessageIds.helpRestartToUpdate, {
  1860. version: "0.1.26",
  1861. }),
  1862. );
  1863. } finally {
  1864. vi.useRealTimers();
  1865. }
  1866. });
  1867. it("已下载更新后轮询发现同版本时不会重复下载", async () => {
  1868. vi.useFakeTimers();
  1869. try {
  1870. const { initAutoUpdater } = await importAutoUpdaterWithLocale();
  1871. initAutoUpdater();
  1872. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1873. autoUpdaterMock.downloadUpdate.mockClear();
  1874. await vi.advanceTimersByTimeAsync(TWO_MINUTES_MS);
  1875. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1876. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1877. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  1878. expect(menuItem.label).toBe(
  1879. formatDesktopMenuMessage(TEST_LOCALE, desktopMenuMessageIds.helpRestartToUpdate, {
  1880. version: "0.1.25",
  1881. }),
  1882. );
  1883. } finally {
  1884. vi.useRealTimers();
  1885. }
  1886. });
  1887. it("重复手动检查时不会丢失第一次检查的结果", async () => {
  1888. const firstWindow = {
  1889. isDestroyed: () => false,
  1890. webContents: {
  1891. id: 31,
  1892. send: vi.fn(),
  1893. },
  1894. };
  1895. const secondWindow = {
  1896. isDestroyed: () => false,
  1897. webContents: {
  1898. id: 32,
  1899. send: vi.fn(),
  1900. },
  1901. };
  1902. const { initAutoUpdater, checkForUpdateMenuClick } = await import("../src/main/autoUpdater.js");
  1903. browserWindows.push(firstWindow, secondWindow);
  1904. initAutoUpdater();
  1905. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  1906. await Promise.resolve();
  1907. await Promise.resolve();
  1908. checkForUpdateMenuClick(firstWindow as never);
  1909. checkForUpdateMenuClick(secondWindow as never);
  1910. expect(secondWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  1911. kind: "error",
  1912. message: "Update check already in progress.",
  1913. });
  1914. autoUpdaterMock.emit("update-not-available", { version: "0.1.24" });
  1915. // Bugfix: 第二次手动点击只应该收到“正在检查中”的即时反馈,
  1916. // 不能把第一次手动检查真正的完成结果抢走;否则第一次点击的用户会一直等不到结论。
  1917. expect(firstWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  1918. kind: "up-to-date",
  1919. currentVersion: "0.1.24",
  1920. });
  1921. });
  1922. it("强制升级自动更新会直接安装已下载版本,不再用最低版本二次拦截", async () => {
  1923. mockProcessPlatform("darwin");
  1924. const { initAutoUpdater, requestForceAutoUpdate } = await import("../src/main/autoUpdater.js");
  1925. const onStateChange = vi.fn();
  1926. initAutoUpdater();
  1927. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1928. await Promise.resolve();
  1929. await Promise.resolve();
  1930. autoUpdaterMock.checkForUpdates.mockClear();
  1931. autoUpdaterMock.quitAndInstall.mockClear();
  1932. requestForceAutoUpdate(onStateChange, "force-update", "0.1.26");
  1933. await Promise.resolve();
  1934. expect(onStateChange).toHaveBeenCalledWith({ kind: "checking" });
  1935. expect(onStateChange).toHaveBeenCalledWith({ kind: "installing" });
  1936. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce();
  1937. expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled();
  1938. });
  1939. it("开发态自动更新安装请求会重启当前 dev app", async () => {
  1940. mockProcessPlatform("darwin");
  1941. appMock.isPackaged = false;
  1942. process.env["ZCODE_AUTO_UPDATE_DEV"] = "1";
  1943. const onBeforeQuitAndInstall = vi.fn();
  1944. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1945. initAutoUpdater({ onBeforeQuitAndInstall });
  1946. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1947. await Promise.resolve();
  1948. await Promise.resolve();
  1949. autoUpdaterMock.quitAndInstall.mockClear();
  1950. appMock.relaunch.mockClear();
  1951. appMock.exit.mockClear();
  1952. const quitAndInstallHandler = ipcMainHandle.mock.calls.find(
  1953. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1954. )?.[1] as (() => Promise<void>) | undefined;
  1955. await quitAndInstallHandler?.();
  1956. // 修复原因:开发态没有真实发布包安装上下文可接管,不能继续依赖
  1957. // electron-updater.quitAndInstall();否则按钮会执行退出准备但应用不重启。
  1958. expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1);
  1959. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  1960. expect(appMock.relaunch).toHaveBeenCalledTimes(1);
  1961. expect(appMock.exit).toHaveBeenCalledWith(0);
  1962. expect(loggerInfoMock).toHaveBeenCalledWith(
  1963. "[auto-update] dev update install fallback: relaunch app",
  1964. );
  1965. });
  1966. it("强制升级下载失败时会恢复菜单并反馈弹窗错误", async () => {
  1967. const downloadError = new Error("network down");
  1968. autoUpdaterMock.downloadUpdate.mockRejectedValueOnce(downloadError);
  1969. const win = {
  1970. isDestroyed: () => false,
  1971. webContents: {
  1972. id: 41,
  1973. send: vi.fn(),
  1974. },
  1975. };
  1976. browserWindows.push(win);
  1977. const { initAutoUpdater, requestForceAutoUpdate } = await import("../src/main/autoUpdater.js");
  1978. const onStateChange = vi.fn();
  1979. initAutoUpdater();
  1980. requestForceAutoUpdate(onStateChange);
  1981. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1982. await new Promise((resolve) => setTimeout(resolve, 0));
  1983. expect(onStateChange).toHaveBeenCalledWith({ kind: "checking" });
  1984. expect(onStateChange).toHaveBeenCalledWith(
  1985. expect.objectContaining({
  1986. kind: "downloading",
  1987. version: "0.1.25",
  1988. }),
  1989. );
  1990. expect(onStateChange).toHaveBeenCalledWith({
  1991. kind: "error",
  1992. message: "network down",
  1993. });
  1994. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1995. kind: "idle",
  1996. enabled: true,
  1997. });
  1998. });
  1999. it("强制升级自动更新复用检查时,无可用更新会反馈错误状态", async () => {
  2000. const { initAutoUpdater, requestForceAutoUpdate } = await import("../src/main/autoUpdater.js");
  2001. const onStateChange = vi.fn();
  2002. initAutoUpdater();
  2003. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  2004. requestForceAutoUpdate(onStateChange);
  2005. expect(onStateChange).toHaveBeenCalledWith({ kind: "checking" });
  2006. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  2007. autoUpdaterMock.emit("update-not-available", { version: "0.1.24" });
  2008. // Bugfix: 启动期检查被强更弹窗复用后,无更新也必须通知弹窗,避免一直停留在 checking。
  2009. expect(onStateChange).toHaveBeenCalledWith({
  2010. kind: "error",
  2011. message: "未找到可安装更新,请使用手动升级。",
  2012. });
  2013. });
  2014. it("强制升级自动更新复用检查失败时,会反馈弹窗错误状态", async () => {
  2015. const checkError = new Error("feed offline");
  2016. autoUpdaterMock.checkForUpdates.mockRejectedValueOnce(checkError);
  2017. const { getAutoUpdaterState, initAutoUpdater, requestForceAutoUpdate } =
  2018. await import("../src/main/autoUpdater.js");
  2019. const onStateChange = vi.fn();
  2020. initAutoUpdater();
  2021. requestForceAutoUpdate(onStateChange);
  2022. await Promise.resolve();
  2023. await Promise.resolve();
  2024. // Bugfix: 强更弹窗复用启动期后台检查时,checkForUpdates 直接 reject 也必须反馈给弹窗,
  2025. // 否则用户会一直看到 checking,无法判断自动升级已经失败。
  2026. expect(onStateChange).toHaveBeenCalledWith({ kind: "checking" });
  2027. expect(onStateChange).toHaveBeenCalledWith({
  2028. kind: "error",
  2029. message: "feed offline",
  2030. });
  2031. expect(getAutoUpdaterState()).toEqual({ kind: "idle", enabled: true });
  2032. });
  2033. it("强制升级自动更新无可用更新时按英文 locale 反馈错误文案", async () => {
  2034. const { initAutoUpdater, requestForceAutoUpdate } = await importAutoUpdaterWithLocale();
  2035. const onStateChange = vi.fn();
  2036. initAutoUpdater();
  2037. requestForceAutoUpdate(onStateChange);
  2038. autoUpdaterMock.emit("update-not-available", { version: "0.1.24" });
  2039. expect(onStateChange).toHaveBeenCalledWith({
  2040. kind: "error",
  2041. message: "No installable update was found. Use manual update instead.",
  2042. });
  2043. });
  2044. });