From e20bb560cb95fd4777dd0c35dc4fda08f9899271 Mon Sep 17 00:00:00 2001 From: Sharad-Patel1 Date: Mon, 16 Nov 2026 01:25:58 +0000 Subject: [PATCH] fix(desktop): a download finished before quitting is ready again after relaunch (prototype) Co-Authored-By: Claude Opus 5.5 --- .../src/updates/DesktopUpdates.test.ts | 165 ++++++++++++++++++ apps/desktop/src/updates/DesktopUpdates.ts | 77 +++++++- .../desktop/src/updates/updatesTestHarness.ts | 35 +++- 3 files changed, 265 insertions(+), 12 deletions(-) diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 53bd956ca6..dee42cf9d8 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -641,10 +641,174 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("restores a finished download after quitting without installing", () => + Effect.gen(function* () { + const firstLaunch = makeHarness(); + yield* Effect.scoped( + Effect.gen(function* () { + yield* (yield* DesktopUpdates.DesktopUpdates).configure; + firstLaunch.emit("update-downloaded", { version: "1.2.4" }); + yield* flushCallbacks; + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), firstLaunch.layer))); + + const downloaded = yield* Deferred.make(); + const recordWrite = yield* Deferred.make(); + const relaunch = makeHarness({ + downloadRecord: firstLaunch.downloadRecord(), + // The ready state must not wait on the record's async write. + beforeDownloadRecordWrite: Deferred.await(recordWrite), + checkForUpdates: Effect.sync(() => relaunch.emit("update-available", { version: "1.2.4" })), + // electron-updater satisfies the download from its verified cache. + downloadUpdate: Effect.sync(() => + relaunch.emit("update-downloaded", { version: "1.2.4" }), + ).pipe(Effect.andThen(Deferred.succeed(downloaded, undefined))), + }); + yield* Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("startup"); + yield* Deferred.await(downloaded); + + const state = yield* updates.getState; + assert.equal(state.status, "downloaded"); + assert.equal(state.downloadedVersion, "1.2.4"); + assert.equal(relaunch.downloadCount(), 1); + yield* Deferred.succeed(recordWrite, undefined); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), relaunch.layer))); + }), + ); + + it.effect("restores on the next check when a track switch held the updater", () => + Effect.gen(function* () { + const downloaded = yield* Deferred.make(); + const harness = makeHarness({ + savedChannel: "nightly", + downloadRecord: JSON.stringify({ fromVersion: "1.2.3", targetVersion: "1.2.4" }), + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: "1.2.4" })), + downloadUpdate: Deferred.succeed(downloaded, undefined), + }); + yield* Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.setChannel("latest"); + assert.equal(harness.downloadCount(), 0); + + yield* updates.check("poll"); + yield* Deferred.await(downloaded); + assert.equal(harness.downloadCount(), 1); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }), + ); + + it.effect("does not restore after the user's own download of that release failed", () => + Effect.gen(function* () { + const checkStarted = yield* Deferred.make(); + const finishCheck = yield* Deferred.make(); + const harness = makeHarness({ + savedChannel: "nightly", + downloadRecord: JSON.stringify({ fromVersion: "1.2.3", targetVersion: "1.2.4" }), + // The track switch's check answers at once; the next one waits so a click can queue on it. + checkForUpdates: Effect.suspend(() => + (harness.checkCount() === 1 + ? Effect.void + : Deferred.succeed(checkStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishCheck)), + ) + ).pipe( + Effect.andThen( + Effect.sync(() => harness.emit("update-available", { version: "1.2.4" })), + ), + ), + ), + downloadUpdate: Effect.fail( + new ElectronUpdater.ElectronUpdaterDownloadUpdateError({ + channel: "latest", + cause: new Error("net::ERR_INTERNET_DISCONNECTED"), + }), + ), + }); + + yield* Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + // The track switch's check holds the updater, so the restore waits for a later check. + yield* updates.setChannel("latest"); + const check = yield* updates.check("poll").pipe(Effect.forkScoped); + yield* Deferred.await(checkStarted); + // The click and the restore both wait on this check; the click is admitted first and fails. + const click = yield* updates.download.pipe(Effect.forkScoped); + yield* flushCallbacks; + yield* Deferred.succeed(finishCheck, undefined); + yield* Fiber.join(check); + assert.isFalse((yield* Fiber.join(click)).completed); + yield* flushCallbacks; + + assert.equal(harness.downloadCount(), 1); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }), + ); + + it.effect.each([ + { + name: "a newer release than the one downloaded", + recordedBy: "1.2.3", + offers: ["1.2.5"], + quits: false, + }, + { + name: "a download another build recorded", + recordedBy: "1.2.2", + offers: ["1.2.4"], + quits: false, + }, + { + name: "an offer that changed while the restore waited", + recordedBy: "1.2.3", + offers: ["1.2.4", "1.2.5"], + quits: false, + }, + { + name: "a release offered as quitting begins", + recordedBy: "1.2.3", + offers: ["1.2.4"], + quits: true, + }, + ])("keeps $name click-to-download after relaunch", ({ recordedBy, offers, quits }) => { + let startQuitting = Effect.void; + const harness = makeHarness({ + downloadRecord: JSON.stringify({ fromVersion: recordedBy, targetVersion: "1.2.4" }), + checkForUpdates: Effect.suspend(() => { + for (const version of offers) harness.emit("update-available", { version }); + return startQuitting; + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + if (quits) startQuitting = Ref.set((yield* DesktopState.DesktopState).quitting, true); + yield* updates.configure; + yield* updates.check("startup"); + yield* flushCallbacks; + + assert.equal((yield* updates.getState).status, "available"); + assert.equal(harness.downloadCount(), 0); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + // regression: #19291 an install that did apply was still flagged as not applied it.effect("does not flag an install that applied", () => { const harness = makeHarness({ installRecord: JSON.stringify({ fromVersion: "1.2.2", targetVersion: "1.2.3" }), + downloadRecord: JSON.stringify({ fromVersion: "1.2.2", targetVersion: "1.2.3" }), }); return Effect.scoped( @@ -653,6 +817,7 @@ describe("DesktopUpdates", () => { yield* updates.configure; assert.isUndefined((yield* updates.getState).notAppliedVersion); assert.isUndefined(harness.previousInstallRecord()); + assert.isUndefined(harness.previousDownloadRecord()); }), ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 055c657439..74b68ffd54 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -86,6 +86,8 @@ const DownloadProgressInfo = Schema.Struct({ percent: Schema.Number, }); export const DESKTOP_UPDATE_INSTALL_RECORD_FILE = "desktop-update-install.json"; +// Same shape as the install record: the release this build finished downloading. +export const DESKTOP_UPDATE_DOWNLOAD_RECORD_FILE = "desktop-update-download.json"; const DesktopUpdateInstallRecord = Schema.fromJsonString( Schema.Struct({ fromVersion: Schema.String, targetVersion: Schema.String }), ); @@ -396,6 +398,7 @@ export const make = Effect.gen(function* () { const updaterConfiguredRef = yield* Ref.make(false); const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1); const notAppliedVersionRef = yield* Ref.make(Option.none()); + const downloadedBeforeRelaunchRef = yield* Ref.make(Option.none()); // The release a track switch's database check cleared. A build crosses to another track only // through such a switch, and never below that release: version order alone cannot tell whether // a Stable knows a Nightly's migrations. @@ -619,12 +622,22 @@ export const make = Effect.gen(function* () { ); }); - const downloadAvailableUpdate = Effect.gen(function* () { + const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* ( + restoreVersion?: string, + ) { const admission = yield* Effect.scoped( admitAfterCheck( Effect.gen(function* () { const state = yield* Ref.get(updateStateRef); - if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") { + if ( + !(yield* Ref.get(updaterConfiguredRef)) || + (yield* Ref.get(desktopState.quitting)) || + state.status !== "available" || + // A restore is admitted only while its release is offered and no download used it up. + (restoreVersion !== undefined && + (state.availableVersion !== restoreVersion || + !Option.contains(yield* Ref.get(downloadedBeforeRelaunchRef), restoreVersion))) + ) { return "refused" as const; } const activeAction = yield* Ref.get(activeUpdateActionRef); @@ -642,6 +655,8 @@ export const make = Effect.gen(function* () { if (admission === "refused") { return { accepted: false, completed: false }; } + // Any download stands in for the restore, so a failed one is never retried unprompted. + yield* Ref.set(downloadedBeforeRelaunchRef, Option.none()); const state = yield* Ref.get(updateStateRef); return yield* Effect.gen(function* () { @@ -693,7 +708,7 @@ export const make = Effect.gen(function* () { }), Effect.ensuring(finishUpdateAction("download")), ); - }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate")); + }); const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime"); const updateRestartMarkerPath = environment.path.join( @@ -757,6 +772,39 @@ export const make = Effect.gen(function* () { .remove(installRecordPath, { force: true }) .pipe(Effect.ignore); + const downloadRecordPath = environment.path.join( + updateRestartMarkerDir, + DESKTOP_UPDATE_DOWNLOAD_RECORD_FILE, + ); + const writeDownloadRecord = (targetVersion: string) => + encodeInstallRecord({ fromVersion: environment.appVersion, targetVersion }).pipe( + Effect.flatMap((text) => + fileSystem + .makeDirectory(updateRestartMarkerDir, { recursive: true }) + .pipe(Effect.andThen(fileSystem.writeFileString(downloadRecordPath, text))), + ), + Effect.catch((error) => + logUpdaterWarning("Could not record the update download.", { errorTag: error._tag }), + ), + ); + const readDownloadedBeforeRelaunch = fileSystem.readFileString(downloadRecordPath).pipe( + Effect.flatMap(decodeInstallRecord), + Effect.option, + Effect.map((record) => + Option.flatMap(record, (value) => + value.fromVersion === environment.appVersion + ? Option.some(value.targetVersion) + : Option.none(), + ), + ), + // Another build's record must not match again after a reinstall of the build that wrote it. + Effect.tap((version) => + Option.isNone(version) + ? fileSystem.remove(downloadRecordPath, { force: true }).pipe(Effect.ignore) + : Effect.void, + ), + ); + const readNotAppliedInstallVersion = fileSystem.readFileString(installRecordPath).pipe( Effect.flatMap(decodeInstallRecord), Effect.option, @@ -991,6 +1039,16 @@ export const make = Effect.gen(function* () { ); }).pipe(Effect.withSpan("desktop.updates.startPollers")); + // electron-updater keeps a finished download's verified package across quits; downloading that + // release again reuses it, and fetches it only if that cache is gone. + const restoreDownloadedBeforeRelaunch = Effect.fn( + "desktop.updates.restoreDownloadedBeforeRelaunch", + )(function* (version: string) { + if (!Option.contains(yield* Ref.get(downloadedBeforeRelaunchRef), version)) return; + yield* logUpdaterInfo("restoring the update downloaded before relaunch", { version }); + yield* downloadAvailableUpdate(version); + }); + const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* ( raw: unknown, ) { @@ -1008,7 +1066,11 @@ export const make = Effect.gen(function* () { yield* Ref.set(lastLoggedDownloadMilestoneRef, -1); return; } - if (isOffered(state) && state.availableVersion === info.version) return; + if (isOffered(state) && state.availableVersion === info.version) { + // A restore refused while another action held the updater gets a later check's turn. + if (state.status === "available") yield* restoreDownloadedBeforeRelaunch(info.version); + return; + } const checkedAt = yield* currentIsoTimestamp; const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes( @@ -1032,6 +1094,7 @@ export const make = Effect.gen(function* () { releaseNoteGroups: releaseNotes.length, omittedReleaseCount, }); + yield* restoreDownloadedBeforeRelaunch(info.version); }), ), Effect.catchCause((cause) => { @@ -1153,6 +1216,9 @@ export const make = Effect.gen(function* () { } yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version)); yield* logUpdaterInfo("update downloaded", { version: info.version }); + // After the state: downloadUpdate can resolve before this async write, and its result + // reads the state. + yield* writeDownloadRecord(info.version); }), ), Effect.catchCause((cause) => { @@ -1199,6 +1265,7 @@ export const make = Effect.gen(function* () { const notAppliedVersion = yield* readNotAppliedInstallVersion; yield* Ref.set(notAppliedVersionRef, notAppliedVersion); + yield* Ref.set(downloadedBeforeRelaunchRef, yield* readDownloadedBeforeRelaunch); if (Option.isSome(notAppliedVersion)) { yield* logUpdaterWarning("the last update install did not apply", { version: environment.appVersion, @@ -1357,7 +1424,7 @@ export const make = Effect.gen(function* () { }; }), download: Effect.gen(function* () { - const result = yield* downloadAvailableUpdate; + const result = yield* downloadAvailableUpdate(); return { accepted: result.accepted, completed: result.completed, diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index b118d15ced..c46462ab28 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -38,6 +38,10 @@ export interface UpdatesHarnessOptions { readonly platform?: NodeJS.Platform; readonly packageType?: string | undefined; readonly installRecord?: string | undefined; + /** The download record a previous launch left. */ + readonly downloadRecord?: string | undefined; + /** Runs before the download record is stored, as a slow disk would. */ + readonly beforeDownloadRecordWrite?: Effect.Effect; readonly policy?: DesktopUpdatePolicy.UpdatePolicy; readonly appVersion?: string; /** Starts from in-memory settings with this track saved, as after a restart. */ @@ -247,14 +251,21 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { const updateMarkerContents = new Map(); const installRecords = new Map(); let previousInstallRecord = options.installRecord; + let previousDownloadRecord = options.downloadRecord; const isInstallRecord = (path: string) => path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE); + const isDownloadRecord = (path: string) => + path.endsWith(DesktopUpdates.DESKTOP_UPDATE_DOWNLOAD_RECORD_FILE); const layerFileSystem = FileSystem.layerNoop({ readFileString: (path) => { const installRecord = isInstallRecord(path) ? (installRecords.get(path) ?? previousInstallRecord) : undefined; if (installRecord !== undefined) return Effect.succeed(installRecord); + const downloadRecord = isDownloadRecord(path) + ? (updateMarkerContents.get(path) ?? previousDownloadRecord) + : undefined; + if (downloadRecord !== undefined) return Effect.succeed(downloadRecord); return path === "/missing/resources/package-type" && options.packageType !== undefined ? Effect.succeed(options.packageType) : Effect.fail( @@ -268,13 +279,20 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { }, makeDirectory: () => Effect.void, writeFileString: (path, data) => - Effect.sync(() => { - if (isInstallRecord(path)) installRecords.set(path, data); - else { - if (path.endsWith("/desktop-update-restart")) updateRestartMarkers.add(path); - updateMarkerContents.set(path, data); - } - }), + (isDownloadRecord(path) + ? (options.beforeDownloadRecordWrite ?? Effect.void) + : Effect.void + ).pipe( + Effect.andThen( + Effect.sync(() => { + if (isInstallRecord(path)) installRecords.set(path, data); + else { + if (path.endsWith("/desktop-update-restart")) updateRestartMarkers.add(path); + updateMarkerContents.set(path, data); + } + }), + ), + ), rename: (from, to) => Effect.sync(() => { const contents = updateMarkerContents.get(from); @@ -287,6 +305,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { updateMarkerContents.delete(path); installRecords.delete(path); if (isInstallRecord(path)) previousInstallRecord = undefined; + if (isDownloadRecord(path)) previousDownloadRecord = undefined; }), }); @@ -321,6 +340,8 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { [...updateMarkerContents].find(([path]) => path.endsWith("/desktop-update-in-progress"))?.[1], installRecords, previousInstallRecord: () => previousInstallRecord, + previousDownloadRecord: () => previousDownloadRecord, + downloadRecord: () => [...updateMarkerContents].find(([path]) => isDownloadRecord(path))?.[1], downloadCount: () => downloadCount, feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls, fullChangelog: () => fullChangelog,