autoUpdaterReadyState.test.ts 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715
  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. await vi.waitFor(() =>
  959. expect(getAutoUpdaterState()).toMatchObject({ kind: "update-downloaded", version: "0.1.25" }),
  960. );
  961. expect(win.webContents.send).toHaveBeenCalledWith(
  962. PlatformChannels.UpdateStateChanged,
  963. expect.objectContaining({
  964. kind: "update-downloaded",
  965. version: "0.1.25",
  966. }),
  967. );
  968. });
  969. it("开启自动下载并安装偏好后发现更新会自动开始下载", async () => {
  970. settingServiceMock.get.mockResolvedValue({
  971. recentProjects: [],
  972. locale: "en-US",
  973. autoDownloadAndInstallUpdates: true,
  974. });
  975. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  976. initAutoUpdater({ settingService: settingServiceMock });
  977. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  978. await new Promise((resolve) => setTimeout(resolve, 0));
  979. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  980. expect(getAutoUpdaterState()).toMatchObject({
  981. kind: "update-available",
  982. version: "0.1.25",
  983. });
  984. });
  985. it("发现更新后只有 renderer 请求才会开始下载", async () => {
  986. const { initAutoUpdater } = await importAutoUpdaterWithLocale();
  987. initAutoUpdater();
  988. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  989. await new Promise((resolve) => setTimeout(resolve, 0));
  990. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  991. const downloadHandler = ipcMainHandle.mock.calls.find(
  992. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  993. )?.[1] as (() => void) | undefined;
  994. expect(downloadHandler).toBeTypeOf("function");
  995. downloadHandler?.();
  996. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  997. });
  998. it("取消下载会中断 token 并回到当前可更新版本", async () => {
  999. const releaseNotes = {
  1000. version: "0.1.25",
  1001. releaseName: "Release v0.1.25",
  1002. releaseNotes: "# Release v0.1.25\n\n- cancellable notes",
  1003. releaseDate: "2026-06-23T13:48:54.438Z",
  1004. };
  1005. const expectedReleaseNotes = {
  1006. version: "0.1.25",
  1007. title: "Release v0.1.25",
  1008. markdown: "# Release v0.1.25\n\n- cancellable notes",
  1009. releaseDate: "2026-06-23T13:48:54.438Z",
  1010. };
  1011. const win = {
  1012. isDestroyed: () => false,
  1013. webContents: {
  1014. id: 6,
  1015. send: vi.fn(),
  1016. },
  1017. };
  1018. browserWindows.push(win);
  1019. autoUpdaterMock.downloadUpdate.mockImplementationOnce(
  1020. (token: EventEmitter) =>
  1021. new Promise((_resolve, reject) => {
  1022. token.once("cancel", () => reject(new Error("cancelled")));
  1023. }),
  1024. );
  1025. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1026. initAutoUpdater();
  1027. autoUpdaterMock.emit("update-available", releaseNotes);
  1028. await new Promise((resolve) => setTimeout(resolve, 0));
  1029. const downloadHandler = ipcMainHandle.mock.calls.find(
  1030. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  1031. )?.[1] as (() => void) | undefined;
  1032. const cancelHandler = ipcMainHandle.mock.calls.find(
  1033. ([channel]: [string, unknown]) => channel === PlatformChannels.CancelUpdateDownload,
  1034. )?.[1] as (() => void) | undefined;
  1035. expect(downloadHandler).toBeTypeOf("function");
  1036. expect(cancelHandler).toBeTypeOf("function");
  1037. downloadHandler?.();
  1038. const cancellationToken = autoUpdaterMock.downloadUpdate.mock.calls[0]?.[0] as
  1039. | { cancelled?: boolean }
  1040. | undefined;
  1041. expect(cancellationToken?.cancelled).toBe(false);
  1042. autoUpdaterMock.emit("download-progress", {
  1043. percent: 1,
  1044. bytesPerSecond: 1024,
  1045. transferred: 1,
  1046. total: 100,
  1047. });
  1048. expect(getAutoUpdaterState()).toEqual({
  1049. kind: "download-progress",
  1050. enabled: false,
  1051. progress: "1",
  1052. version: "0.1.25",
  1053. channel: "stable",
  1054. releaseNotes: expectedReleaseNotes,
  1055. transferredBytes: 1,
  1056. totalBytes: 100,
  1057. });
  1058. cancelHandler?.();
  1059. await Promise.resolve();
  1060. await Promise.resolve();
  1061. expect(cancellationToken?.cancelled).toBe(true);
  1062. expect(loggerErrorMock).not.toHaveBeenCalled();
  1063. expect(getAutoUpdaterState()).toEqual({
  1064. kind: "update-available",
  1065. enabled: true,
  1066. version: "0.1.25",
  1067. channel: "stable",
  1068. releaseNotes: expectedReleaseNotes,
  1069. });
  1070. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1071. kind: "update-available",
  1072. enabled: true,
  1073. version: "0.1.25",
  1074. channel: "stable",
  1075. releaseNotes: expectedReleaseNotes,
  1076. });
  1077. expect(menuItem.enabled).toBe(true);
  1078. win.webContents.send.mockClear();
  1079. autoUpdaterMock.emit("download-progress", {
  1080. percent: 63,
  1081. bytesPerSecond: 1024,
  1082. transferred: 1024,
  1083. total: 2048,
  1084. });
  1085. expect(getAutoUpdaterState()).toEqual({
  1086. kind: "update-available",
  1087. enabled: true,
  1088. version: "0.1.25",
  1089. channel: "stable",
  1090. releaseNotes: expectedReleaseNotes,
  1091. });
  1092. expect(win.webContents.send).not.toHaveBeenCalledWith(
  1093. PlatformChannels.UpdateStateChanged,
  1094. expect.objectContaining({
  1095. kind: "download-progress",
  1096. }),
  1097. );
  1098. autoUpdaterMock.emit("error", new Error("cancelled"));
  1099. expect(loggerErrorMock).not.toHaveBeenCalled();
  1100. expect(getAutoUpdaterState()).toEqual({
  1101. kind: "update-available",
  1102. enabled: true,
  1103. version: "0.1.25",
  1104. channel: "stable",
  1105. releaseNotes: expectedReleaseNotes,
  1106. });
  1107. });
  1108. it("下载启动失败后保留当前可更新版本供用户重试", async () => {
  1109. const releaseNotes = {
  1110. version: "0.1.25",
  1111. releaseName: "Release v0.1.25",
  1112. releaseNotes: "# Release v0.1.25\n\n- retryable notes",
  1113. releaseDate: "2026-06-23T13:48:54.438Z",
  1114. };
  1115. const expectedReleaseNotes = {
  1116. version: "0.1.25",
  1117. title: "Release v0.1.25",
  1118. markdown: "# Release v0.1.25\n\n- retryable notes",
  1119. releaseDate: "2026-06-23T13:48:54.438Z",
  1120. };
  1121. const win = {
  1122. isDestroyed: () => false,
  1123. webContents: {
  1124. id: 10,
  1125. send: vi.fn(),
  1126. },
  1127. };
  1128. browserWindows.push(win);
  1129. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1130. initAutoUpdater();
  1131. autoUpdaterMock.emit("update-available", releaseNotes);
  1132. await new Promise((resolve) => setTimeout(resolve, 0));
  1133. const downloadHandler = ipcMainHandle.mock.calls.find(
  1134. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  1135. )?.[1] as (() => void) | undefined;
  1136. downloadHandler?.();
  1137. expect(getAutoUpdaterState()).toMatchObject({
  1138. kind: "update-available",
  1139. version: "0.1.25",
  1140. });
  1141. autoUpdaterMock.emit("error", new Error("download failed before progress"));
  1142. await Promise.resolve();
  1143. // Bugfix: 下载失败不是跳过版本。不能广播 idle 让主入口和弹窗一起消失,
  1144. // 应退回可更新状态,保留同一版本供用户重试。
  1145. expect(getAutoUpdaterState()).toEqual({
  1146. kind: "update-available",
  1147. enabled: true,
  1148. version: "0.1.25",
  1149. channel: "stable",
  1150. releaseNotes: expectedReleaseNotes,
  1151. });
  1152. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1153. kind: "update-available",
  1154. enabled: true,
  1155. version: "0.1.25",
  1156. channel: "stable",
  1157. releaseNotes: expectedReleaseNotes,
  1158. });
  1159. expect(menuItem.enabled).toBe(true);
  1160. await Promise.resolve();
  1161. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1162. });
  1163. it("下载失败发生在检查收口前时,收口后再查一次", async () => {
  1164. let releaseCheck: (() => void) | undefined;
  1165. autoUpdaterMock.checkForUpdates.mockImplementationOnce(
  1166. () =>
  1167. new Promise((resolve) => {
  1168. releaseCheck = () => resolve(undefined);
  1169. }),
  1170. );
  1171. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1172. initAutoUpdater();
  1173. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1174. await Promise.resolve();
  1175. const downloadHandler = ipcMainHandle.mock.calls.find(
  1176. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  1177. )?.[1] as (() => void) | undefined;
  1178. autoUpdaterMock.downloadUpdate.mockRejectedValueOnce(new Error("network down"));
  1179. downloadHandler?.();
  1180. await Promise.resolve();
  1181. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  1182. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  1183. releaseCheck?.();
  1184. await Promise.resolve();
  1185. await Promise.resolve();
  1186. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1187. });
  1188. it("跳过当前版本会按 stable 通道持久化并清空 available 状态", async () => {
  1189. const win = {
  1190. isDestroyed: () => false,
  1191. webContents: {
  1192. id: 7,
  1193. send: vi.fn(),
  1194. },
  1195. };
  1196. browserWindows.push(win);
  1197. const { initAutoUpdater } = await importAutoUpdaterWithLocale();
  1198. initAutoUpdater({ settingService: settingServiceMock });
  1199. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1200. await new Promise((resolve) => setTimeout(resolve, 0));
  1201. const skipHandler = ipcMainHandle.mock.calls.find(
  1202. ([channel]: [string, unknown]) => channel === PlatformChannels.SkipUpdateVersion,
  1203. )?.[1] as ((event: unknown, version: string) => Promise<void>) | undefined;
  1204. expect(skipHandler).toBeTypeOf("function");
  1205. await skipHandler?.({}, "0.1.25");
  1206. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1207. skippedElectronUpdateVersions: {
  1208. stable: "0.1.25",
  1209. },
  1210. });
  1211. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1212. kind: "idle",
  1213. enabled: true,
  1214. });
  1215. });
  1216. it("下载中跳过当前版本会取消下载并持久化 skipped 状态", async () => {
  1217. const win = {
  1218. isDestroyed: () => false,
  1219. webContents: {
  1220. id: 8,
  1221. send: vi.fn(),
  1222. },
  1223. };
  1224. browserWindows.push(win);
  1225. autoUpdaterMock.downloadUpdate.mockImplementationOnce(
  1226. (token: EventEmitter) =>
  1227. new Promise((_resolve, reject) => {
  1228. token.once("cancel", () => reject(new Error("cancelled")));
  1229. }),
  1230. );
  1231. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  1232. initAutoUpdater({ settingService: settingServiceMock });
  1233. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1234. await new Promise((resolve) => setTimeout(resolve, 0));
  1235. const downloadHandler = ipcMainHandle.mock.calls.find(
  1236. ([channel]: [string, unknown]) => channel === PlatformChannels.DownloadUpdate,
  1237. )?.[1] as (() => void) | undefined;
  1238. const skipHandler = ipcMainHandle.mock.calls.find(
  1239. ([channel]: [string, unknown]) => channel === PlatformChannels.SkipUpdateVersion,
  1240. )?.[1] as ((event: unknown, version: string) => Promise<void>) | undefined;
  1241. downloadHandler?.();
  1242. const cancellationToken = autoUpdaterMock.downloadUpdate.mock.calls[0]?.[0] as
  1243. | { cancelled?: boolean }
  1244. | undefined;
  1245. await skipHandler?.({}, "0.1.25");
  1246. await Promise.resolve();
  1247. await Promise.resolve();
  1248. expect(cancellationToken?.cancelled).toBe(true);
  1249. expect(loggerErrorMock).not.toHaveBeenCalled();
  1250. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1251. skippedElectronUpdateVersions: {
  1252. stable: "0.1.25",
  1253. },
  1254. });
  1255. expect(getAutoUpdaterState()).toEqual({ kind: "idle", enabled: true });
  1256. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1257. kind: "idle",
  1258. enabled: true,
  1259. });
  1260. });
  1261. it("手动检查更新会清除当前通道的 skipped 缓存并重新显示该版本", async () => {
  1262. const win = {
  1263. isDestroyed: () => false,
  1264. webContents: {
  1265. id: 9,
  1266. send: vi.fn(),
  1267. },
  1268. };
  1269. browserWindows.push(win);
  1270. let settingsState = {
  1271. recentProjects: [],
  1272. locale: "en-US" as const,
  1273. skippedElectronUpdateVersions: {
  1274. preview: "0.2.0",
  1275. },
  1276. };
  1277. settingServiceMock.get.mockImplementation(async () => settingsState);
  1278. settingServiceMock.update.mockImplementation(async (patch) => {
  1279. settingsState = { ...settingsState, ...patch };
  1280. });
  1281. const { checkForUpdateMenuClick, getAutoUpdaterState, initAutoUpdater } =
  1282. await importAutoUpdaterWithLocale();
  1283. initAutoUpdater({ settingService: settingServiceMock });
  1284. await Promise.resolve();
  1285. await Promise.resolve();
  1286. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1287. await new Promise((resolve) => setTimeout(resolve, 0));
  1288. const skipHandler = ipcMainHandle.mock.calls.find(
  1289. ([channel]: [string, unknown]) => channel === PlatformChannels.SkipUpdateVersion,
  1290. )?.[1] as ((event: unknown, version: string) => Promise<void>) | undefined;
  1291. await skipHandler?.({}, "0.1.25");
  1292. expect(getAutoUpdaterState()).toEqual({ kind: "idle", enabled: true });
  1293. expect(settingsState.skippedElectronUpdateVersions).toEqual({
  1294. preview: "0.2.0",
  1295. stable: "0.1.25",
  1296. });
  1297. win.webContents.send.mockClear();
  1298. checkForUpdateMenuClick(win as never);
  1299. await new Promise((resolve) => setTimeout(resolve, 0));
  1300. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  1301. expect(settingsState.skippedElectronUpdateVersions).toEqual({
  1302. preview: "0.2.0",
  1303. });
  1304. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1305. await new Promise((resolve) => setTimeout(resolve, 0));
  1306. // Bugfix: 手动检查代表用户重新关注被跳过版本。
  1307. // 只清当前 stable 通道的缓存,避免误删 preview 跳过记录,同时要让同版本更新重新展示。
  1308. expect(getAutoUpdaterState()).toEqual({
  1309. kind: "update-available",
  1310. enabled: true,
  1311. version: "0.1.25",
  1312. channel: "stable",
  1313. });
  1314. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  1315. kind: "available",
  1316. version: "0.1.25",
  1317. channel: "stable",
  1318. });
  1319. });
  1320. it("下载完成后会持久化版本说明,并且启动后只同步给一个窗口", async () => {
  1321. const firstWindow = {
  1322. isDestroyed: () => false,
  1323. webContents: {
  1324. id: 11,
  1325. send: vi.fn(),
  1326. },
  1327. };
  1328. const secondWindow = {
  1329. isDestroyed: () => false,
  1330. webContents: {
  1331. id: 12,
  1332. send: vi.fn(),
  1333. },
  1334. };
  1335. browserWindows.push(firstWindow, secondWindow);
  1336. const { initAutoUpdater, syncPostUpdateReleaseNotesToWindow } =
  1337. await import("../src/main/autoUpdater.js");
  1338. initAutoUpdater({ settingService: settingServiceMock });
  1339. autoUpdaterMock.emit("update-downloaded", {
  1340. version: "0.1.25",
  1341. releaseName: "Release v0.1.25",
  1342. releaseNotes: "# Release v0.1.25\n\n- add popup",
  1343. releaseDate: new Date("2026-06-23T13:48:54.438Z"),
  1344. releaseNotesByLocale: {
  1345. "zh-CN": {
  1346. title: "ZCode v0.1.25",
  1347. markdown: "# ZCode v0.1.25\n\n- 中文说明",
  1348. },
  1349. "en-US": {
  1350. title: "ZCode v0.1.25",
  1351. markdown: "# ZCode v0.1.25\n\n- English notes",
  1352. },
  1353. },
  1354. });
  1355. await Promise.resolve();
  1356. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1357. pendingPostUpdateReleaseNotes: {
  1358. version: "0.1.25",
  1359. title: "Release v0.1.25",
  1360. markdown: "# Release v0.1.25\n\n- add popup",
  1361. releaseDate: "2026-06-23T13:48:54.438Z",
  1362. releaseNotesByLocale: {
  1363. "zh-CN": {
  1364. title: "ZCode v0.1.25",
  1365. markdown: "# ZCode v0.1.25\n\n- 中文说明",
  1366. },
  1367. "en-US": {
  1368. title: "ZCode v0.1.25",
  1369. markdown: "# ZCode v0.1.25\n\n- English notes",
  1370. },
  1371. },
  1372. },
  1373. });
  1374. expect(firstWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  1375. kind: "update-downloaded",
  1376. enabled: true,
  1377. version: "0.1.25",
  1378. channel: "stable",
  1379. releaseNotes: {
  1380. version: "0.1.25",
  1381. title: "Release v0.1.25",
  1382. markdown: "# Release v0.1.25\n\n- add popup",
  1383. releaseDate: "2026-06-23T13:48:54.438Z",
  1384. releaseNotesByLocale: {
  1385. "zh-CN": {
  1386. title: "ZCode v0.1.25",
  1387. markdown: "# ZCode v0.1.25\n\n- 中文说明",
  1388. },
  1389. "en-US": {
  1390. title: "ZCode v0.1.25",
  1391. markdown: "# ZCode v0.1.25\n\n- English notes",
  1392. },
  1393. },
  1394. },
  1395. });
  1396. // 安装后再次启动时,当前 app 版本才等于 pending 版本;这时 pending payload
  1397. // 才应作为 post-update release notes 同步给 renderer。
  1398. appMock.getVersion.mockImplementation(() => "0.1.25");
  1399. syncPostUpdateReleaseNotesToWindow(firstWindow as never);
  1400. syncPostUpdateReleaseNotesToWindow(secondWindow as never);
  1401. expect(firstWindow.webContents.send).toHaveBeenCalledWith(
  1402. PlatformChannels.PostUpdateReleaseNotes,
  1403. {
  1404. version: "0.1.25",
  1405. title: "Release v0.1.25",
  1406. markdown: "# Release v0.1.25\n\n- add popup",
  1407. releaseDate: "2026-06-23T13:48:54.438Z",
  1408. releaseNotesByLocale: {
  1409. "zh-CN": {
  1410. title: "ZCode v0.1.25",
  1411. markdown: "# ZCode v0.1.25\n\n- 中文说明",
  1412. },
  1413. "en-US": {
  1414. title: "ZCode v0.1.25",
  1415. markdown: "# ZCode v0.1.25\n\n- English notes",
  1416. },
  1417. },
  1418. },
  1419. );
  1420. expect(secondWindow.webContents.send).not.toHaveBeenCalledWith(
  1421. PlatformChannels.PostUpdateReleaseNotes,
  1422. expect.anything(),
  1423. );
  1424. });
  1425. it("没有 releaseNotes 时不会写入待展示说明", async () => {
  1426. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1427. initAutoUpdater({ settingService: settingServiceMock });
  1428. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1429. await Promise.resolve();
  1430. expect(settingServiceMock.update).not.toHaveBeenCalledWith(
  1431. expect.objectContaining({
  1432. pendingPostUpdateReleaseNotes: expect.anything(),
  1433. }),
  1434. );
  1435. });
  1436. it("renderer ack 后会清空待展示说明,不再重复补发", async () => {
  1437. appMock.getVersion.mockImplementation(() => "0.1.25");
  1438. const firstWindow = {
  1439. isDestroyed: () => false,
  1440. webContents: {
  1441. id: 21,
  1442. send: vi.fn(),
  1443. },
  1444. };
  1445. const laterWindow = {
  1446. isDestroyed: () => false,
  1447. webContents: {
  1448. id: 22,
  1449. send: vi.fn(),
  1450. },
  1451. };
  1452. browserWindows.push(firstWindow, laterWindow);
  1453. settingServiceMock.get.mockResolvedValue({
  1454. recentProjects: [],
  1455. locale: "en-US",
  1456. pendingPostUpdateReleaseNotes: {
  1457. version: "0.1.25",
  1458. title: "Release v0.1.25",
  1459. markdown: "# Release v0.1.25\n\n- add popup",
  1460. },
  1461. });
  1462. const {
  1463. acknowledgePostUpdateReleaseNotes,
  1464. hydratePendingPostUpdateReleaseNotes,
  1465. syncPostUpdateReleaseNotesToWindow,
  1466. } = await import("../src/main/autoUpdater.js");
  1467. await hydratePendingPostUpdateReleaseNotes(settingServiceMock);
  1468. syncPostUpdateReleaseNotesToWindow(firstWindow as never);
  1469. expect(firstWindow.webContents.send).toHaveBeenCalledWith(
  1470. PlatformChannels.PostUpdateReleaseNotes,
  1471. {
  1472. version: "0.1.25",
  1473. title: "Release v0.1.25",
  1474. markdown: "# Release v0.1.25\n\n- add popup",
  1475. },
  1476. );
  1477. await acknowledgePostUpdateReleaseNotes("0.1.25", settingServiceMock);
  1478. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1479. pendingPostUpdateReleaseNotes: undefined,
  1480. });
  1481. syncPostUpdateReleaseNotesToWindow(laterWindow as never);
  1482. expect(laterWindow.webContents.send).not.toHaveBeenCalledWith(
  1483. PlatformChannels.PostUpdateReleaseNotes,
  1484. expect.anything(),
  1485. );
  1486. });
  1487. it("hydrate 时若待展示版本低于已安装应用版本则丢弃,避免手动跳级安装后弹出旧版说明", async () => {
  1488. appMock.getVersion.mockImplementation(() => "0.1.26");
  1489. settingServiceMock.get.mockResolvedValue({
  1490. recentProjects: [],
  1491. locale: "en-US",
  1492. pendingPostUpdateReleaseNotes: {
  1493. version: "0.1.25",
  1494. title: "Release v0.1.25",
  1495. markdown: "# Release v0.1.25\n\n- old",
  1496. },
  1497. });
  1498. const { hydratePendingPostUpdateReleaseNotes, syncPostUpdateReleaseNotesToWindow } =
  1499. await import("../src/main/autoUpdater.js");
  1500. await hydratePendingPostUpdateReleaseNotes(settingServiceMock);
  1501. expect(settingServiceMock.update).toHaveBeenCalledWith({
  1502. pendingPostUpdateReleaseNotes: undefined,
  1503. });
  1504. const win = {
  1505. isDestroyed: () => false,
  1506. webContents: {
  1507. id: 99,
  1508. send: vi.fn(),
  1509. },
  1510. };
  1511. syncPostUpdateReleaseNotesToWindow(win as never);
  1512. expect(win.webContents.send).not.toHaveBeenCalledWith(
  1513. PlatformChannels.PostUpdateReleaseNotes,
  1514. expect.anything(),
  1515. );
  1516. });
  1517. it("hydrate 时若待展示版本高于当前应用版本则恢复为待安装更新", async () => {
  1518. appMock.getVersion.mockImplementation(() => "0.1.24");
  1519. settingServiceMock.get.mockResolvedValue({
  1520. recentProjects: [],
  1521. locale: "en-US",
  1522. pendingPostUpdateReleaseNotes: {
  1523. version: "0.1.25",
  1524. title: "Release v0.1.25",
  1525. markdown: "# Release v0.1.25\n\n- cached",
  1526. },
  1527. });
  1528. const {
  1529. getAutoUpdaterState,
  1530. hydratePendingPostUpdateReleaseNotes,
  1531. syncPostUpdateReleaseNotesToWindow,
  1532. syncReadyUpdateToWindow,
  1533. } = await importAutoUpdaterWithLocale();
  1534. await hydratePendingPostUpdateReleaseNotes(settingServiceMock);
  1535. // Bugfix: 已下载但未安装时重启,pending release notes 的版本仍高于当前 app。
  1536. // 此时应恢复“重启以更新”,不能重新提示下载同一个已缓存版本。
  1537. expect(getAutoUpdaterState()).toEqual({
  1538. kind: "update-downloaded",
  1539. enabled: true,
  1540. version: "0.1.25",
  1541. releaseNotes: {
  1542. version: "0.1.25",
  1543. title: "Release v0.1.25",
  1544. markdown: "# Release v0.1.25\n\n- cached",
  1545. },
  1546. });
  1547. const readyWindow = {
  1548. isDestroyed: () => false,
  1549. webContents: {
  1550. id: 101,
  1551. send: vi.fn(),
  1552. },
  1553. };
  1554. syncReadyUpdateToWindow(readyWindow as never);
  1555. expect(readyWindow.webContents.send).toHaveBeenCalledWith(
  1556. PlatformChannels.UpdateReady,
  1557. "0.1.25",
  1558. );
  1559. const notesWindow = {
  1560. isDestroyed: () => false,
  1561. webContents: {
  1562. id: 102,
  1563. send: vi.fn(),
  1564. },
  1565. };
  1566. syncPostUpdateReleaseNotesToWindow(notesWindow as never);
  1567. expect(notesWindow.webContents.send).not.toHaveBeenCalledWith(
  1568. PlatformChannels.PostUpdateReleaseNotes,
  1569. expect.anything(),
  1570. );
  1571. });
  1572. it("用户确认安装更新前会先执行退出准备钩子", async () => {
  1573. mockProcessPlatform("darwin");
  1574. let resolveQuitPreparation: (() => void) | null = null;
  1575. const onBeforeQuitAndInstall = vi.fn(
  1576. () =>
  1577. new Promise<void>((resolve) => {
  1578. resolveQuitPreparation = resolve;
  1579. }),
  1580. );
  1581. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1582. initAutoUpdater({ onBeforeQuitAndInstall });
  1583. const quitHandler = ipcMainOn.mock.calls.find(
  1584. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1585. )?.[1] as (() => void) | undefined;
  1586. expect(quitHandler).toBeTypeOf("function");
  1587. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1588. await Promise.resolve();
  1589. quitHandler?.();
  1590. await vi.waitFor(() => expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1));
  1591. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(0);
  1592. resolveQuitPreparation?.();
  1593. await Promise.resolve();
  1594. await Promise.resolve();
  1595. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1);
  1596. });
  1597. it("安装前退出准备失败时不启动安装器,受控重启恢复服务", async () => {
  1598. mockProcessPlatform("win32");
  1599. const prepareError = new Error("host process still locked resources");
  1600. const onBeforeQuitAndInstall = vi.fn(async () => {
  1601. throw prepareError;
  1602. });
  1603. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1604. initAutoUpdater({ onBeforeQuitAndInstall });
  1605. const quitHandler = ipcMainHandle.mock.calls.find(
  1606. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1607. )?.[1] as (() => Promise<void>) | undefined;
  1608. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1609. await Promise.resolve();
  1610. expect(quitHandler).toBeTypeOf("function");
  1611. await expect(quitHandler!()).rejects.toBe(prepareError);
  1612. // Bugfix: 安装前准备负责释放 Windows resources/glm 等随包资源锁。
  1613. // 如果准备失败还继续启动安装器,会再次形成 bundled runtime 半更新。
  1614. expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1);
  1615. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  1616. expect(appMock.relaunch).toHaveBeenCalledOnce();
  1617. expect(appMock.exit).toHaveBeenCalledWith(0);
  1618. expect(loggerErrorMock).toHaveBeenCalledWith(
  1619. "[auto-update] prepare quit and install failed:",
  1620. prepareError,
  1621. );
  1622. });
  1623. it.each(["darwin", "linux"] as const)(
  1624. "%s 安装调用返回后原生退出直接放行,重复安装命令不重入",
  1625. async (platform) => {
  1626. mockProcessPlatform(platform);
  1627. const onBeforeQuitAndInstall = vi.fn(async () => {});
  1628. const { initAutoUpdater } = await importAutoUpdaterWithLocale();
  1629. await initAutoUpdater({ onBeforeQuitAndInstall });
  1630. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1631. const install = ipcMainHandle.mock.calls.find(
  1632. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1633. )![1] as () => Promise<void>;
  1634. await install();
  1635. // 原生 staging 在安装入口返回后才触发退出,不能被当作新的安装请求。
  1636. const event = { preventDefault: vi.fn() };
  1637. for (const listener of appListeners.get("before-quit") ?? []) {
  1638. listener(event);
  1639. }
  1640. await install();
  1641. expect(event.preventDefault).not.toHaveBeenCalled();
  1642. expect(onBeforeQuitAndInstall).toHaveBeenCalledOnce();
  1643. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce();
  1644. },
  1645. );
  1646. it.each(["同步抛错", "异步错误事件"] as const)(
  1647. "安装%s后受控重启,新进程重新就绪可重试",
  1648. async (failureKind) => {
  1649. mockProcessPlatform("darwin");
  1650. const services = { hostAlive: true, remoteAlive: true };
  1651. const onBeforeQuitAndInstall = vi.fn(() => {
  1652. services.hostAlive = false;
  1653. services.remoteAlive = false;
  1654. });
  1655. const module = await importAutoUpdaterWithLocale();
  1656. await module.initAutoUpdater({ onBeforeQuitAndInstall });
  1657. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1658. const install = ipcMainHandle.mock.calls.find(
  1659. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1660. )![1] as () => Promise<void>;
  1661. const error = new Error("native installer failed");
  1662. if (failureKind === "同步抛错") {
  1663. autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
  1664. throw error;
  1665. });
  1666. await expect(install()).rejects.toBe(error);
  1667. } else {
  1668. await install();
  1669. autoUpdaterMock.emit("error", error);
  1670. }
  1671. expect(services).toEqual({ hostAlive: false, remoteAlive: false });
  1672. expect(appMock.relaunch).toHaveBeenCalledOnce();
  1673. expect(appMock.exit).toHaveBeenCalledWith(0);
  1674. autoUpdaterMock.emit("error", error);
  1675. expect(appMock.relaunch).toHaveBeenCalledOnce();
  1676. // 模拟退出后新 main 进程重新装配,旧进程的 recovering 不接收重试。
  1677. vi.resetModules();
  1678. autoUpdaterMock.removeAllListeners();
  1679. ipcMainHandle.mockClear();
  1680. const restarted = await importAutoUpdaterWithLocale();
  1681. await restarted.initAutoUpdater();
  1682. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1683. await (
  1684. ipcMainHandle.mock.calls.find(
  1685. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1686. )![1] as () => Promise<void>
  1687. )();
  1688. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(2);
  1689. },
  1690. );
  1691. it.each(["darwin", "linux", "win32"] as const)(
  1692. "%s 服务清理后锁定目标,迟到新版本事件与重复入口不会放弃或重入安装",
  1693. async (platform) => {
  1694. mockProcessPlatform(platform);
  1695. let finishPreparation!: () => void;
  1696. const preparation = new Promise<void>((resolve) => {
  1697. finishPreparation = resolve;
  1698. });
  1699. const services = { hostAlive: true, remoteAlive: true };
  1700. const onBeforeQuitAndInstall = vi.fn(() => {
  1701. services.hostAlive = false;
  1702. services.remoteAlive = false;
  1703. return preparation;
  1704. });
  1705. const module = await importAutoUpdaterWithLocale();
  1706. await module.initAutoUpdater({ onBeforeQuitAndInstall });
  1707. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1708. const install = ipcMainHandle.mock.calls.find(
  1709. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1710. )![1] as () => Promise<void>;
  1711. const firstInstall = install();
  1712. await vi.waitFor(() => expect(onBeforeQuitAndInstall).toHaveBeenCalledOnce());
  1713. expect(services).toEqual({ hostAlive: false, remoteAlive: false });
  1714. const checkCalls = autoUpdaterMock.checkForUpdates.mock.calls.length;
  1715. autoUpdaterMock.emit("update-available", { version: "0.1.26" });
  1716. autoUpdaterMock.emit("update-downloaded", { version: "0.1.26" });
  1717. module.downloadAvailableUpdate();
  1718. module.refreshAutoUpdaterReleaseChannel(true);
  1719. module.requestAutoUpdateCheckWithoutWindow();
  1720. const event = { preventDefault: vi.fn() };
  1721. for (const listener of appListeners.get("before-quit") ?? []) listener(event);
  1722. await install();
  1723. finishPreparation();
  1724. await firstInstall;
  1725. expect(module.getAutoUpdaterState()).toMatchObject({
  1726. kind: "update-downloaded",
  1727. version: "0.1.25",
  1728. });
  1729. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  1730. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(checkCalls);
  1731. expect(event.preventDefault).not.toHaveBeenCalled();
  1732. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce();
  1733. },
  1734. );
  1735. it.each(["darwin", "linux", "win32"] as const)(
  1736. "%s 后台检查永不完成也不阻塞已有 ready,迟到结果不替换安装目标",
  1737. async (platform) => {
  1738. mockProcessPlatform(platform);
  1739. let finishCheck!: () => void;
  1740. autoUpdaterMock.checkForUpdates.mockReturnValueOnce(
  1741. new Promise<void>((resolve) => {
  1742. finishCheck = resolve;
  1743. }),
  1744. );
  1745. const onBeforeQuitAndInstall = vi.fn();
  1746. const module = await importAutoUpdaterWithLocale();
  1747. await module.initAutoUpdater({ onBeforeQuitAndInstall });
  1748. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1749. const install = ipcMainHandle.mock.calls.find(
  1750. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1751. )![1] as () => Promise<void>;
  1752. let completed = false;
  1753. const installation = install().then(() => {
  1754. completed = true;
  1755. });
  1756. await vi.waitFor(() => expect(completed).toBe(true));
  1757. expect(onBeforeQuitAndInstall).toHaveBeenCalledOnce();
  1758. autoUpdaterMock.emit("update-available", { version: "0.1.26" });
  1759. finishCheck();
  1760. await installation;
  1761. expect(module.getAutoUpdaterState()).toMatchObject({
  1762. kind: "update-downloaded",
  1763. version: "0.1.25",
  1764. });
  1765. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce();
  1766. },
  1767. );
  1768. it("检查结果已进入异步设置读取,确认安装后也不能改写锁定包", async () => {
  1769. let finishSettings!: (value: { recentProjects: never[]; locale: "en-US" }) => void;
  1770. const settings = new Promise<{ recentProjects: never[]; locale: "en-US" }>((resolve) => {
  1771. finishSettings = resolve;
  1772. });
  1773. const module = await importAutoUpdaterWithLocale();
  1774. await module.initAutoUpdater({ settingService: settingServiceMock });
  1775. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1776. settingServiceMock.get.mockReturnValueOnce(settings);
  1777. autoUpdaterMock.emit("update-available", { version: "0.1.26" });
  1778. const install = ipcMainHandle.mock.calls.find(
  1779. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1780. )![1] as () => Promise<void>;
  1781. await install();
  1782. finishSettings({ recentProjects: [], locale: "en-US" });
  1783. await Promise.resolve();
  1784. await Promise.resolve();
  1785. expect(module.getAutoUpdaterState()).toMatchObject({
  1786. kind: "update-downloaded",
  1787. version: "0.1.25",
  1788. });
  1789. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  1790. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce();
  1791. });
  1792. it("下载 ready 事件先于下载 Promise 返回时,不提前发布可安装状态", async () => {
  1793. let finishDownload!: () => void;
  1794. autoUpdaterMock.downloadUpdate.mockReturnValueOnce(
  1795. new Promise<string[]>((resolve) => {
  1796. finishDownload = () => resolve([]);
  1797. }),
  1798. );
  1799. const onBeforeQuitAndInstall = vi.fn();
  1800. const module = await importAutoUpdaterWithLocale();
  1801. await module.initAutoUpdater({ onBeforeQuitAndInstall });
  1802. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1803. await vi.waitFor(() => expect(module.getAutoUpdaterState().kind).toBe("update-available"));
  1804. module.downloadAvailableUpdate();
  1805. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1806. const install = ipcMainHandle.mock.calls.find(
  1807. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1808. )![1] as () => Promise<void>;
  1809. await expect(install()).rejects.toThrow("Update is not ready to install");
  1810. expect(onBeforeQuitAndInstall).not.toHaveBeenCalled();
  1811. finishDownload();
  1812. await vi.waitFor(() => expect(module.getAutoUpdaterState().kind).toBe("update-downloaded"));
  1813. await install();
  1814. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce();
  1815. });
  1816. it.each(["失败", "取消"] as const)("下载%s后不发布提前到达的 ready", async (kind) => {
  1817. let rejectDownload!: (error: Error) => void;
  1818. autoUpdaterMock.downloadUpdate.mockReturnValueOnce(
  1819. new Promise<string[]>((_resolve, reject) => {
  1820. rejectDownload = reject;
  1821. }),
  1822. );
  1823. const onBeforeQuitAndInstall = vi.fn();
  1824. const module = await importAutoUpdaterWithLocale();
  1825. await module.initAutoUpdater({ onBeforeQuitAndInstall });
  1826. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1827. await vi.waitFor(() => expect(module.getAutoUpdaterState().kind).toBe("update-available"));
  1828. module.downloadAvailableUpdate("test");
  1829. autoUpdaterMock.emit("download-progress", {
  1830. percent: 50,
  1831. bytesPerSecond: 1,
  1832. transferred: 1,
  1833. total: 2,
  1834. });
  1835. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1836. if (kind === "取消") module.cancelDownloadingUpdate("test");
  1837. const error = new Error(kind === "取消" ? "cancelled" : "download failed after ready event");
  1838. rejectDownload(error);
  1839. await vi.waitFor(() => {
  1840. if (kind === "取消")
  1841. expect(loggerInfoMock).toHaveBeenCalledWith("[auto-update] test download cancelled");
  1842. else
  1843. expect(loggerErrorMock).toHaveBeenCalledWith(
  1844. "[auto-update] download update failed:",
  1845. error,
  1846. );
  1847. });
  1848. await Promise.resolve();
  1849. expect(module.getAutoUpdaterState().kind).not.toBe("update-downloaded");
  1850. expect(onBeforeQuitAndInstall).not.toHaveBeenCalled();
  1851. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  1852. });
  1853. it("挂起检查的迟到错误不触发安装恢复,真实原生错误仍受控重启", async () => {
  1854. let failCheck!: (error: Error) => void;
  1855. autoUpdaterMock.checkForUpdates.mockReturnValueOnce(
  1856. new Promise<void>((_resolve, reject) => {
  1857. failCheck = reject;
  1858. }),
  1859. );
  1860. const module = await importAutoUpdaterWithLocale();
  1861. await module.initAutoUpdater();
  1862. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1863. const install = ipcMainHandle.mock.calls.find(
  1864. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1865. )![1] as () => Promise<void>;
  1866. await install();
  1867. const checkError = new Error("background check failed");
  1868. autoUpdaterMock.emit("error", checkError, "Cannot check for updates: background check failed");
  1869. failCheck(checkError);
  1870. await Promise.resolve();
  1871. await Promise.resolve();
  1872. expect(module.getAutoUpdaterState()).toMatchObject({
  1873. kind: "update-downloaded",
  1874. version: "0.1.25",
  1875. });
  1876. expect(appMock.relaunch).not.toHaveBeenCalled();
  1877. autoUpdaterMock.emit("error", new Error("native staging failed"));
  1878. expect(appMock.relaunch).toHaveBeenCalledOnce();
  1879. expect(appMock.exit).toHaveBeenCalledWith(0);
  1880. });
  1881. it.each(["先可用后失败", "先失败后可用", "重复错误"] as const)(
  1882. "交接后%s的原生错误受控重启一次,不能留下服务已清理的旧窗口",
  1883. async (order) => {
  1884. const services = { hostAlive: true, remoteAlive: true };
  1885. const onBeforeQuitAndInstall = vi.fn(() => {
  1886. services.hostAlive = false;
  1887. services.remoteAlive = false;
  1888. });
  1889. const module = await importAutoUpdaterWithLocale();
  1890. await module.initAutoUpdater({ onBeforeQuitAndInstall });
  1891. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1892. const install = ipcMainHandle.mock.calls.find(
  1893. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1894. )![1] as () => Promise<void>;
  1895. await install();
  1896. const newer = () => {
  1897. autoUpdaterMock.emit("update-available", { version: "0.1.26" });
  1898. module.downloadAvailableUpdate();
  1899. };
  1900. const fail = () => autoUpdaterMock.emit("error", new Error("native installer failed"));
  1901. if (order === "先可用后失败") {
  1902. newer();
  1903. fail();
  1904. } else {
  1905. fail();
  1906. if (order === "重复错误") fail();
  1907. else newer();
  1908. }
  1909. expect(services).toEqual({ hostAlive: false, remoteAlive: false });
  1910. expect(appMock.relaunch).toHaveBeenCalledOnce();
  1911. expect(appMock.exit).toHaveBeenCalledWith(0);
  1912. autoUpdaterMock.emit("update-downloaded", { version: "0.1.26" });
  1913. await install();
  1914. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce();
  1915. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  1916. },
  1917. );
  1918. it("强更缓存同步 ready 仍等待下载 Promise 收口后才清理服务", async () => {
  1919. let finishDownload!: () => void;
  1920. const download = new Promise<string[]>((resolve) => {
  1921. finishDownload = () => resolve([]);
  1922. });
  1923. autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => {
  1924. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1925. return download;
  1926. });
  1927. const onBeforeQuitAndInstall = vi.fn();
  1928. const module = await importAutoUpdaterWithLocale();
  1929. await module.initAutoUpdater({ onBeforeQuitAndInstall });
  1930. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  1931. await vi.waitFor(() => expect(module.getAutoUpdaterState().kind).toBe("update-available"));
  1932. module.requestForceAutoUpdate(vi.fn());
  1933. await Promise.resolve();
  1934. expect(onBeforeQuitAndInstall).not.toHaveBeenCalled();
  1935. finishDownload();
  1936. await vi.waitFor(() => expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce());
  1937. expect(onBeforeQuitAndInstall).toHaveBeenCalledOnce();
  1938. });
  1939. it("准备期间原生 staging 失败,清理完成后重启恢复服务而不留下失效窗口", async () => {
  1940. let finishPreparation!: () => void;
  1941. const preparation = new Promise<void>((resolve) => {
  1942. finishPreparation = resolve;
  1943. });
  1944. const onBeforeQuitAndInstall = vi.fn(() => preparation);
  1945. const module = await importAutoUpdaterWithLocale();
  1946. await module.initAutoUpdater({ onBeforeQuitAndInstall });
  1947. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1948. const install = ipcMainHandle.mock.calls.find(
  1949. ([channel]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1950. )![1] as () => Promise<void>;
  1951. const firstInstall = install();
  1952. await vi.waitFor(() => expect(onBeforeQuitAndInstall).toHaveBeenCalledOnce());
  1953. autoUpdaterMock.emit("error", new Error("native staging failed"));
  1954. finishPreparation();
  1955. await firstInstall;
  1956. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  1957. expect(appMock.relaunch).toHaveBeenCalledOnce();
  1958. expect(appMock.exit).toHaveBeenCalledWith(0);
  1959. });
  1960. it("没有已下载更新时安装请求不会执行退出准备", async () => {
  1961. mockProcessPlatform("darwin");
  1962. const onBeforeQuitAndInstall = vi.fn();
  1963. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1964. initAutoUpdater({ onBeforeQuitAndInstall });
  1965. const quitHandler = ipcMainHandle.mock.calls.find(
  1966. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1967. )?.[1] as (() => Promise<void>) | undefined;
  1968. expect(quitHandler).toBeTypeOf("function");
  1969. await expect(quitHandler!()).rejects.toThrow("Update is not ready to install: state=idle");
  1970. // Bugfix: renderer 的旧 ready 缓存可能残留,但 main 已经因为 staging error
  1971. // 回到 idle。此时不能清理 host 或调用 quitAndInstall,否则按钮表现为无响应。
  1972. expect(onBeforeQuitAndInstall).not.toHaveBeenCalled();
  1973. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  1974. expect(loggerWarnMock).toHaveBeenCalledWith(
  1975. "[auto-update] ignore quitAndInstall request: state=idle",
  1976. );
  1977. });
  1978. it("Windows 安装更新恢复 electron-updater 原生入口,不再启动 PowerShell launcher", async () => {
  1979. mockProcessPlatform("win32");
  1980. const onBeforeQuitAndInstall = vi.fn();
  1981. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  1982. initAutoUpdater({ onBeforeQuitAndInstall });
  1983. const quitHandler = ipcMainOn.mock.calls.find(
  1984. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  1985. )?.[1] as (() => void) | undefined;
  1986. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  1987. await Promise.resolve();
  1988. quitHandler?.();
  1989. await Promise.resolve();
  1990. await Promise.resolve();
  1991. await vi.waitFor(() => expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1));
  1992. // Bugfix: 3.3.0 的 detached hidden PowerShell launcher 只证明 powershell.exe
  1993. // 创建成功,不能证明安装器脚本实际执行。Windows 也必须回到 electron-updater 原生入口。
  1994. expect(spawnMock).not.toHaveBeenCalled();
  1995. expect(appMock.exit).not.toHaveBeenCalled();
  1996. await vi.waitFor(() => expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1));
  1997. });
  1998. it("更新已下载后点击菜单会直接重启安装", async () => {
  1999. mockProcessPlatform("darwin");
  2000. const onBeforeQuitAndInstall = vi.fn();
  2001. const win = {
  2002. isDestroyed: () => false,
  2003. webContents: {
  2004. id: 21,
  2005. send: vi.fn(),
  2006. },
  2007. };
  2008. browserWindows.push(win);
  2009. const { initAutoUpdater, checkForUpdateMenuClick } = await import("../src/main/autoUpdater.js");
  2010. initAutoUpdater({ onBeforeQuitAndInstall });
  2011. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  2012. win.webContents.send.mockClear();
  2013. checkForUpdateMenuClick(win as never);
  2014. await Promise.resolve();
  2015. await Promise.resolve();
  2016. // Bugfix: 菜单文案是“重启以更新”时,点击应和更新按钮一样真的安装;
  2017. // 旧逻辑只给 renderer 发 ready toast,用户看到的是“重启”但实际没有重启。
  2018. await vi.waitFor(() => expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1));
  2019. expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1);
  2020. expect(win.webContents.send).not.toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  2021. kind: "ready",
  2022. version: "0.1.25",
  2023. });
  2024. });
  2025. it("Windows 初始化时会关闭 quit 自动安装,避免关应用后立即关机打断更新", async () => {
  2026. mockProcessPlatform("win32");
  2027. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  2028. initAutoUpdater();
  2029. expect(autoUpdaterMock.autoDownload).toBe(false);
  2030. expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false);
  2031. });
  2032. it("非 Windows 初始化时保持 quit 自动安装,避免影响既有升级行为", async () => {
  2033. mockProcessPlatform("darwin");
  2034. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  2035. initAutoUpdater();
  2036. // 非 Windows 也不再让 electron-updater 在退出时直接装 staged 包。
  2037. // ready 包仍等于当前目标时,由 before-quit 主动安装;目标已经更高则跳过。
  2038. expect(autoUpdaterMock.autoDownload).toBe(false);
  2039. expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false);
  2040. });
  2041. it("Windows 启动时不阻塞主界面,后台检查更新", async () => {
  2042. mockProcessPlatform("win32");
  2043. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  2044. // initAutoUpdater 现在立即返回,不等待更新检查完成
  2045. await expect(initAutoUpdater()).resolves.toBeUndefined();
  2046. // 更新检查应该在后台触发
  2047. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  2048. });
  2049. it("启动后会注册 15 分钟轮询,并在空闲时再次检查更新", async () => {
  2050. vi.useFakeTimers();
  2051. try {
  2052. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  2053. initAutoUpdater();
  2054. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  2055. await vi.advanceTimersByTimeAsync(FIFTEEN_MINUTES_MS);
  2056. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  2057. } finally {
  2058. vi.useRealTimers();
  2059. }
  2060. });
  2061. it("已发现更新后 2 分钟轮询会换成更高版本,且入口不进入 checking", async () => {
  2062. vi.useFakeTimers();
  2063. try {
  2064. const { getAutoUpdaterState, initAutoUpdater } = await importAutoUpdaterWithLocale();
  2065. initAutoUpdater();
  2066. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  2067. await Promise.resolve();
  2068. await vi.advanceTimersByTimeAsync(TWO_MINUTES_MS);
  2069. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  2070. autoUpdaterMock.emit("update-available", { version: "0.1.27" });
  2071. await Promise.resolve();
  2072. expect(getAutoUpdaterState()).toMatchObject({
  2073. kind: "update-available",
  2074. version: "0.1.27",
  2075. });
  2076. } finally {
  2077. vi.useRealTimers();
  2078. }
  2079. });
  2080. it("已发现更新后手动检查会重新请求并替换版本", async () => {
  2081. const win = {
  2082. isDestroyed: () => false,
  2083. webContents: { id: 51, send: vi.fn() },
  2084. };
  2085. browserWindows.push(win);
  2086. const { checkForUpdateMenuClick, getAutoUpdaterState, initAutoUpdater } =
  2087. await import("../src/main/autoUpdater.js");
  2088. initAutoUpdater();
  2089. await Promise.resolve();
  2090. await Promise.resolve();
  2091. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  2092. await Promise.resolve();
  2093. checkForUpdateMenuClick(win as never);
  2094. await Promise.resolve();
  2095. autoUpdaterMock.emit("update-available", { version: "0.1.27" });
  2096. await Promise.resolve();
  2097. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  2098. expect(getAutoUpdaterState()).toMatchObject({
  2099. kind: "update-available",
  2100. version: "0.1.27",
  2101. });
  2102. });
  2103. it("自动下载完成后立刻复查,更高版本会替换并重新下载", async () => {
  2104. settingServiceMock.get.mockResolvedValue({
  2105. recentProjects: [],
  2106. locale: "en-US",
  2107. autoDownloadAndInstallUpdates: true,
  2108. });
  2109. const { getAutoUpdaterState, initAutoUpdater } = await import("../src/main/autoUpdater.js");
  2110. initAutoUpdater({ settingService: settingServiceMock });
  2111. await new Promise((resolve) => setTimeout(resolve, 0));
  2112. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  2113. await new Promise((resolve) => setTimeout(resolve, 0));
  2114. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  2115. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  2116. await new Promise((resolve) => setTimeout(resolve, 0));
  2117. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  2118. autoUpdaterMock.emit("update-available", { version: "0.1.27" });
  2119. await new Promise((resolve) => setTimeout(resolve, 0));
  2120. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(2);
  2121. expect(getAutoUpdaterState()).toMatchObject({
  2122. kind: "update-available",
  2123. version: "0.1.27",
  2124. });
  2125. });
  2126. it("macOS 上旧 ready 包不再等于目标时退出不安装", async () => {
  2127. mockProcessPlatform("darwin");
  2128. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  2129. initAutoUpdater();
  2130. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  2131. autoUpdaterMock.emit("update-available", { version: "0.1.27" });
  2132. await Promise.resolve();
  2133. const event = { preventDefault: vi.fn() };
  2134. for (const listener of appListeners.get("before-quit") ?? []) {
  2135. listener(event);
  2136. }
  2137. expect(event.preventDefault).not.toHaveBeenCalled();
  2138. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  2139. });
  2140. it("下载中轮询不会并发触发新的检查", async () => {
  2141. vi.useFakeTimers();
  2142. try {
  2143. const { downloadAvailableUpdate, initAutoUpdater } = await importAutoUpdaterWithLocale();
  2144. initAutoUpdater();
  2145. await Promise.resolve();
  2146. await Promise.resolve();
  2147. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  2148. await Promise.resolve();
  2149. downloadAvailableUpdate("test");
  2150. autoUpdaterMock.emit("download-progress", {
  2151. percent: 10,
  2152. bytesPerSecond: 1024,
  2153. transferred: 1024,
  2154. total: 10240,
  2155. });
  2156. await vi.advanceTimersByTimeAsync(FIFTEEN_MINUTES_MS);
  2157. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  2158. } finally {
  2159. vi.useRealTimers();
  2160. }
  2161. });
  2162. it("已下载更新后轮询发现更高版本时先提示,用户确认后替换 ready 版本", async () => {
  2163. vi.useFakeTimers();
  2164. try {
  2165. const win = {
  2166. isDestroyed: () => false,
  2167. webContents: {
  2168. id: 41,
  2169. send: vi.fn(),
  2170. },
  2171. };
  2172. browserWindows.push(win);
  2173. const { downloadAvailableUpdate, initAutoUpdater } = await importAutoUpdaterWithLocale();
  2174. initAutoUpdater();
  2175. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  2176. autoUpdaterMock.downloadUpdate.mockClear();
  2177. win.webContents.send.mockClear();
  2178. await vi.advanceTimersByTimeAsync(TWO_MINUTES_MS);
  2179. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  2180. autoUpdaterMock.emit("update-available", { version: "0.1.26" });
  2181. await Promise.resolve();
  2182. await Promise.resolve();
  2183. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  2184. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  2185. kind: "update-available",
  2186. enabled: true,
  2187. version: "0.1.26",
  2188. channel: "stable",
  2189. });
  2190. downloadAvailableUpdate("test");
  2191. expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1);
  2192. autoUpdaterMock.emit("update-downloaded", { version: "0.1.26" });
  2193. await vi.waitFor(() =>
  2194. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateReady, "0.1.26"),
  2195. );
  2196. expect(menuItem.label).toBe(
  2197. formatDesktopMenuMessage(TEST_LOCALE, desktopMenuMessageIds.helpRestartToUpdate, {
  2198. version: "0.1.26",
  2199. }),
  2200. );
  2201. } finally {
  2202. vi.useRealTimers();
  2203. }
  2204. });
  2205. it("已下载更新后轮询发现同版本时不会重复下载", async () => {
  2206. vi.useFakeTimers();
  2207. try {
  2208. const { initAutoUpdater } = await importAutoUpdaterWithLocale();
  2209. initAutoUpdater();
  2210. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  2211. autoUpdaterMock.downloadUpdate.mockClear();
  2212. await vi.advanceTimersByTimeAsync(TWO_MINUTES_MS);
  2213. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  2214. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2);
  2215. expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled();
  2216. expect(menuItem.label).toBe(
  2217. formatDesktopMenuMessage(TEST_LOCALE, desktopMenuMessageIds.helpRestartToUpdate, {
  2218. version: "0.1.25",
  2219. }),
  2220. );
  2221. } finally {
  2222. vi.useRealTimers();
  2223. }
  2224. });
  2225. it("重复手动检查时不会丢失第一次检查的结果", async () => {
  2226. const firstWindow = {
  2227. isDestroyed: () => false,
  2228. webContents: {
  2229. id: 31,
  2230. send: vi.fn(),
  2231. },
  2232. };
  2233. const secondWindow = {
  2234. isDestroyed: () => false,
  2235. webContents: {
  2236. id: 32,
  2237. send: vi.fn(),
  2238. },
  2239. };
  2240. const { initAutoUpdater, checkForUpdateMenuClick } = await import("../src/main/autoUpdater.js");
  2241. browserWindows.push(firstWindow, secondWindow);
  2242. initAutoUpdater();
  2243. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  2244. await Promise.resolve();
  2245. await Promise.resolve();
  2246. checkForUpdateMenuClick(firstWindow as never);
  2247. checkForUpdateMenuClick(secondWindow as never);
  2248. expect(secondWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  2249. kind: "error",
  2250. message: "Update check already in progress.",
  2251. });
  2252. autoUpdaterMock.emit("update-not-available", { version: "0.1.24" });
  2253. // Bugfix: 第二次手动点击只应该收到“正在检查中”的即时反馈,
  2254. // 不能把第一次手动检查真正的完成结果抢走;否则第一次点击的用户会一直等不到结论。
  2255. expect(firstWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateCheckResult, {
  2256. kind: "up-to-date",
  2257. currentVersion: "0.1.24",
  2258. });
  2259. });
  2260. it("强制升级自动更新会直接安装已下载版本,不再用最低版本二次拦截", async () => {
  2261. mockProcessPlatform("darwin");
  2262. const { initAutoUpdater, requestForceAutoUpdate } = await import("../src/main/autoUpdater.js");
  2263. const onStateChange = vi.fn();
  2264. initAutoUpdater();
  2265. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  2266. await Promise.resolve();
  2267. await Promise.resolve();
  2268. autoUpdaterMock.checkForUpdates.mockClear();
  2269. autoUpdaterMock.quitAndInstall.mockClear();
  2270. requestForceAutoUpdate(onStateChange, "force-update", "0.1.26");
  2271. await Promise.resolve();
  2272. expect(onStateChange).toHaveBeenCalledWith({ kind: "checking" });
  2273. expect(onStateChange).toHaveBeenCalledWith({ kind: "installing" });
  2274. await vi.waitFor(() => expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce());
  2275. expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled();
  2276. });
  2277. it("开发态自动更新安装请求会重启当前 dev app", async () => {
  2278. mockProcessPlatform("darwin");
  2279. appMock.isPackaged = false;
  2280. process.env["ZCODE_AUTO_UPDATE_DEV"] = "1";
  2281. const onBeforeQuitAndInstall = vi.fn();
  2282. const { initAutoUpdater } = await import("../src/main/autoUpdater.js");
  2283. initAutoUpdater({ onBeforeQuitAndInstall });
  2284. autoUpdaterMock.emit("update-downloaded", { version: "0.1.25" });
  2285. await Promise.resolve();
  2286. await Promise.resolve();
  2287. autoUpdaterMock.quitAndInstall.mockClear();
  2288. appMock.relaunch.mockClear();
  2289. appMock.exit.mockClear();
  2290. const quitAndInstallHandler = ipcMainHandle.mock.calls.find(
  2291. ([channel]: [string, unknown]) => channel === PlatformChannels.QuitAndInstallUpdate,
  2292. )?.[1] as (() => Promise<void>) | undefined;
  2293. await quitAndInstallHandler?.();
  2294. // 修复原因:开发态没有真实发布包安装上下文可接管,不能继续依赖
  2295. // electron-updater.quitAndInstall();否则按钮会执行退出准备但应用不重启。
  2296. expect(onBeforeQuitAndInstall).toHaveBeenCalledTimes(1);
  2297. expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled();
  2298. expect(appMock.relaunch).toHaveBeenCalledTimes(1);
  2299. expect(appMock.exit).toHaveBeenCalledWith(0);
  2300. expect(loggerInfoMock).toHaveBeenCalledWith(
  2301. "[auto-update] dev update install fallback: relaunch app",
  2302. );
  2303. });
  2304. it("强制升级下载失败时会恢复菜单并反馈弹窗错误", async () => {
  2305. const downloadError = new Error("network down");
  2306. autoUpdaterMock.downloadUpdate.mockRejectedValueOnce(downloadError);
  2307. const win = {
  2308. isDestroyed: () => false,
  2309. webContents: {
  2310. id: 41,
  2311. send: vi.fn(),
  2312. },
  2313. };
  2314. browserWindows.push(win);
  2315. const { initAutoUpdater, requestForceAutoUpdate } = await import("../src/main/autoUpdater.js");
  2316. const onStateChange = vi.fn();
  2317. initAutoUpdater();
  2318. requestForceAutoUpdate(onStateChange);
  2319. autoUpdaterMock.emit("update-available", { version: "0.1.25" });
  2320. await new Promise((resolve) => setTimeout(resolve, 0));
  2321. expect(onStateChange).toHaveBeenCalledWith({ kind: "checking" });
  2322. expect(onStateChange).toHaveBeenCalledWith(
  2323. expect.objectContaining({
  2324. kind: "downloading",
  2325. version: "0.1.25",
  2326. }),
  2327. );
  2328. expect(onStateChange).toHaveBeenCalledWith({
  2329. kind: "error",
  2330. message: "network down",
  2331. });
  2332. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.UpdateStateChanged, {
  2333. kind: "idle",
  2334. enabled: true,
  2335. });
  2336. });
  2337. it("强制升级自动更新复用检查时,无可用更新会反馈错误状态", async () => {
  2338. const { initAutoUpdater, requestForceAutoUpdate } = await import("../src/main/autoUpdater.js");
  2339. const onStateChange = vi.fn();
  2340. initAutoUpdater();
  2341. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  2342. requestForceAutoUpdate(onStateChange);
  2343. expect(onStateChange).toHaveBeenCalledWith({ kind: "checking" });
  2344. expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1);
  2345. autoUpdaterMock.emit("update-not-available", { version: "0.1.24" });
  2346. // Bugfix: 启动期检查被强更弹窗复用后,无更新也必须通知弹窗,避免一直停留在 checking。
  2347. expect(onStateChange).toHaveBeenCalledWith({
  2348. kind: "error",
  2349. message: "未找到可安装更新,请使用手动升级。",
  2350. });
  2351. });
  2352. it("强制升级自动更新复用检查失败时,会反馈弹窗错误状态", async () => {
  2353. const checkError = new Error("feed offline");
  2354. autoUpdaterMock.checkForUpdates.mockRejectedValueOnce(checkError);
  2355. const { getAutoUpdaterState, initAutoUpdater, requestForceAutoUpdate } =
  2356. await import("../src/main/autoUpdater.js");
  2357. const onStateChange = vi.fn();
  2358. initAutoUpdater();
  2359. requestForceAutoUpdate(onStateChange);
  2360. await Promise.resolve();
  2361. await Promise.resolve();
  2362. // Bugfix: 强更弹窗复用启动期后台检查时,checkForUpdates 直接 reject 也必须反馈给弹窗,
  2363. // 否则用户会一直看到 checking,无法判断自动升级已经失败。
  2364. expect(onStateChange).toHaveBeenCalledWith({ kind: "checking" });
  2365. expect(onStateChange).toHaveBeenCalledWith({
  2366. kind: "error",
  2367. message: "feed offline",
  2368. });
  2369. expect(getAutoUpdaterState()).toEqual({ kind: "idle", enabled: true });
  2370. });
  2371. it("强制升级自动更新无可用更新时按英文 locale 反馈错误文案", async () => {
  2372. const { initAutoUpdater, requestForceAutoUpdate } = await importAutoUpdaterWithLocale();
  2373. const onStateChange = vi.fn();
  2374. initAutoUpdater();
  2375. requestForceAutoUpdate(onStateChange);
  2376. autoUpdaterMock.emit("update-not-available", { version: "0.1.24" });
  2377. expect(onStateChange).toHaveBeenCalledWith({
  2378. kind: "error",
  2379. message: "No installable update was found. Use manual update instead.",
  2380. });
  2381. });
  2382. });