fix(desktop): refresh queued updates before install (#6269)

Co-authored-by: shivam <[email protected]>
This commit is contained in:
Dara Adedejiandshivam authored and GitHub committed 2026-08-20 02:05:40 +05:30
1 parent 51341f2ac1
commit a354dd9ddc
6 files changed
+526 -115

No files matched your search

+267 -15
View File
@@ -27,6 +27,7 @@ interface UpdatesHarnessOptions {
void,
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
>;
readonly beforeSetUpdateChannel?: Effect.Effect<void>;
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
readonly stopBackend?: Effect.Effect<void>;
@@ -153,22 +154,41 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
),
);
let testSettings: DesktopAppSettings.DesktopSettings = {
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
};
const setUpdateChannelError = options.setUpdateChannelError;
const settingsLayer = setUpdateChannelError
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
setWslDistro: () => Effect.die("unexpected WSL distro change"),
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
: DesktopAppSettings.layer;
const settingsLayer =
setUpdateChannelError || options.beforeSetUpdateChannel
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.sync(() => testSettings),
load: Effect.sync(() => testSettings),
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: (channel) =>
setUpdateChannelError
? Effect.fail(setUpdateChannelError)
: (options.beforeSetUpdateChannel ?? Effect.void).pipe(
Effect.andThen(
Effect.sync(() => {
const changed = testSettings.updateChannel !== channel;
testSettings = {
...testSettings,
updateChannel: channel,
updateChannelConfiguredByUser: true,
};
return { settings: testSettings, changed };
}),
),
),
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
setWslDistro: () => Effect.die("unexpected WSL distro change"),
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
: DesktopAppSettings.layer;
const layer = DesktopUpdates.layer.pipe(
Layer.provideMerge(updaterLayer),
@@ -337,6 +357,178 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("checks for newer releases after an update has been downloaded", () => {
const harness = makeHarness();
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", {
version: "1.2.4",
releaseNotes: "## What's changed\n- fix: queued update",
});
yield* flushCallbacks;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.check("poll");
assert.isTrue(result.checked);
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const unchangedState = yield* updates.getState;
assert.equal(unchangedState.status, "downloaded");
assert.equal(unchangedState.downloadedVersion, "1.2.4");
assert.deepEqual(unchangedState.releaseNotes, [
{ version: "1.2.4", items: ["fix: queued update"] },
]);
const nextResult = yield* updates.check("poll");
assert.isTrue(nextResult.checked);
harness.emit("update-available", { version: "1.2.5" });
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "available");
assert.equal(state.availableVersion, "1.2.5");
assert.isNull(state.downloadedVersion);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("preserves a queued installer when the feed has no update", () => {
const harness = makeHarness();
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", {
version: "1.2.4",
releaseNotes: "## What's changed\n- fix: queued update",
});
yield* flushCallbacks;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
yield* updates.check("poll");
harness.emit("update-not-available");
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "downloaded");
assert.equal(state.availableVersion, "1.2.4");
assert.equal(state.downloadedVersion, "1.2.4");
assert.deepEqual(state.releaseNotes, [{ version: "1.2.4", items: ["fix: queued update"] }]);
assert.equal(state.downloadPercent, 100);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("preserves a queued installer when the feed offers another channel", () => {
const harness = makeHarness();
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", {
version: "1.2.4",
releaseNotes: "## What's changed\n- fix: queued update",
});
yield* flushCallbacks;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
yield* updates.check("poll");
harness.emit("update-available", { version: "1.2.5-nightly.20260710.1" });
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "downloaded");
assert.equal(state.availableVersion, "1.2.4");
assert.equal(state.downloadedVersion, "1.2.4");
assert.deepEqual(state.releaseNotes, [{ version: "1.2.4", items: ["fix: queued update"] }]);
assert.equal(state.downloadPercent, 100);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect(
"rejects install while a refresh check is in progress and releases the reservation",
() =>
Effect.gen(function* () {
const checkStarted = yield* Deferred.make<void>();
const releaseCheck = yield* Deferred.make<void>();
const harness = makeHarness({
checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseCheck)),
),
});
yield* Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped);
yield* Deferred.await(checkStarted);
const installResult = yield* updates.install;
assert.isFalse(installResult.accepted);
yield* Deferred.succeed(releaseCheck, undefined);
const checkResult = yield* Fiber.join(checkFiber);
assert.isTrue(checkResult.checked);
const followUpCheck = yield* updates.check("manual");
assert.isTrue(followUpCheck.checked);
assert.equal(harness.checkCount(), 2);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("rejects refresh checks while install is in progress", () =>
Effect.gen(function* () {
const installStarted = yield* Deferred.make<void>();
const releaseInstall = yield* Deferred.make<void>();
const harness = makeHarness({
stopBackend: Deferred.succeed(installStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseInstall)),
),
});
yield* Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
const installFiber = yield* updates.install.pipe(Effect.forkScoped);
yield* Deferred.await(installStarted);
const checkResult = yield* updates.check("manual");
assert.isFalse(checkResult.checked);
assert.equal(harness.checkCount(), 0);
yield* Deferred.succeed(releaseInstall, undefined);
const installResult = yield* Fiber.join(installFiber);
assert.isTrue(installResult.accepted);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("keeps raw updater event failures out of update state", () => {
const harness = makeHarness();
const cause = new Error(
@@ -359,6 +551,30 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("preserves a queued installer after a background updater error", () => {
const harness = makeHarness();
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
harness.emit("error", new Error("background updater failure"));
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "error");
assert.equal(state.downloadedVersion, "1.2.4");
assert.isNull(state.errorContext);
const result = yield* updates.install;
assert.isTrue(result.accepted);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("logs bounded updater failure context without exposing the cause", () => {
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
@@ -581,6 +797,38 @@ describe("DesktopUpdates", () => {
}),
);
it.effect("rejects checks while an update channel change is being persisted", () =>
Effect.gen(function* () {
const channelChangeStarted = yield* Deferred.make<void>();
const releaseChannelChange = yield* Deferred.make<void>();
const harness = makeHarness({
beforeSetUpdateChannel: Deferred.succeed(channelChangeStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseChannelChange)),
),
});
yield* Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
yield* Deferred.await(channelChangeStarted);
const checkResult = yield* updates.check("manual");
assert.isFalse(checkResult.checked);
assert.equal(harness.checkCount(), 0);
yield* Deferred.succeed(releaseChannelChange, undefined);
const state = yield* Fiber.join(channelFiber);
assert.equal(state.channel, "nightly");
assert.equal(harness.checkCount(), 1);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
@@ -604,6 +852,10 @@ describe("DesktopUpdates", () => {
assert.strictEqual(error.cause.cause, diskFailure);
assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
assert.notInclude(error.message, diskFailure.message);
const checkResult = yield* updates.check("manual");
assert.isTrue(checkResult.checked);
assert.equal(harness.checkCount(), 1);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
+102 -82
View File
@@ -45,6 +45,8 @@ import {
const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
type UpdateAction = "check" | "download" | "install" | "channel";
const AppUpdateYmlConfig = Schema.Record(Schema.String, Schema.String);
type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
@@ -68,7 +70,7 @@ const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<DesktopUpdateActionInProgressError>()(
"DesktopUpdateActionInProgressError",
{
action: Schema.Literals(["check", "download", "install"]),
action: Schema.Literals(["check", "download", "install", "channel"]),
requestedChannel: DesktopUpdateChannelSchema,
},
) {
@@ -116,7 +118,7 @@ export class DesktopUpdateEventHandlingError extends Schema.TaggedErrorClass<Des
export class DesktopUpdaterReportedError extends Schema.TaggedErrorClass<DesktopUpdaterReportedError>()(
"DesktopUpdaterReportedError",
{
operation: Schema.Literals(["check", "download", "install", "background"]),
operation: Schema.Literals(["check", "download", "install", "channel", "background"]),
cause: Schema.Defect(),
},
) {
@@ -255,9 +257,7 @@ export const make = Effect.gen(function* () {
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
const updateCheckInFlightRef = yield* Ref.make(false);
const updateDownloadInFlightRef = yield* Ref.make(false);
const updateInstallInFlightRef = yield* Ref.make(false);
const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
const updaterConfiguredRef = yield* Ref.make(false);
const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
const updateStateRef = yield* Ref.make<DesktopUpdateState>(
@@ -313,19 +313,23 @@ export const make = Effect.gen(function* () {
);
});
const resolveUpdaterErrorContext = Effect.gen(function* () {
if (yield* Ref.get(updateInstallInFlightRef)) return "install" as const;
if (yield* Ref.get(updateDownloadInFlightRef)) return "download" as const;
if (yield* Ref.get(updateCheckInFlightRef)) return "check" as const;
return (yield* Ref.get(updateStateRef)).errorContext;
});
const activeUpdateAction = Ref.get(activeUpdateActionRef);
const activeUpdateAction = Effect.gen(function* () {
if (yield* Ref.get(updateInstallInFlightRef)) return Option.some("install" as const);
if (yield* Ref.get(updateDownloadInFlightRef)) return Option.some("download" as const);
if (yield* Ref.get(updateCheckInFlightRef)) return Option.some("check" as const);
return Option.none<"check" | "download" | "install">();
});
const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
Ref.modify(activeUpdateActionRef, (activeAction) =>
Option.isSome(activeAction) ? [false, activeAction] : [true, Option.some(action)],
);
const tryStartChannelChange = Ref.modify(activeUpdateActionRef, (activeAction) =>
Option.isSome(activeAction)
? [activeAction, activeAction]
: [Option.none<UpdateAction>(), Option.some<UpdateAction>("channel")],
);
const finishUpdateAction = (action: UpdateAction): Effect.Effect<void> =>
Ref.update(activeUpdateActionRef, (activeAction) =>
Option.isSome(activeAction) && activeAction.value === action ? Option.none() : activeAction,
);
const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
channel: DesktopUpdateChannel,
@@ -346,14 +350,16 @@ export const make = Effect.gen(function* () {
const shouldEnableAutoUpdates = resolveDisabledReason.pipe(Effect.map(Option.isNone));
const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (reason: string) {
const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
reason: string,
actionReservation: "acquire" | "held" = "acquire",
) {
yield* Effect.annotateCurrentSpan({ reason });
if (yield* Ref.get(desktopState.quitting)) return false;
if (!(yield* Ref.get(updaterConfiguredRef))) return false;
if (yield* Ref.get(updateCheckInFlightRef)) return false;
const state = yield* Ref.get(updateStateRef);
if (state.status === "downloading" || state.status === "downloaded") {
if (state.status === "downloading") {
yield* logUpdaterInfo("skipping update check while update is active", {
reason,
status: state.status,
@@ -361,43 +367,48 @@ export const make = Effect.gen(function* () {
return false;
}
yield* Ref.set(updateCheckInFlightRef, true);
const checkedAt = yield* currentIsoTimestamp;
yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
yield* logUpdaterInfo("checking for updates", { reason });
if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
return yield* electronUpdater.checkForUpdates.pipe(
Effect.as(true),
Effect.catchTags({
ElectronUpdaterCheckForUpdatesError: Effect.fn(
"desktop.updates.handleCheckForUpdatesFailure",
)(function* (error) {
const failedAt = yield* currentIsoTimestamp;
yield* updateState((current) =>
reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
return true;
const check = Effect.gen(function* () {
const checkedAt = yield* currentIsoTimestamp;
yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
yield* logUpdaterInfo("checking for updates", { reason });
return yield* electronUpdater.checkForUpdates.pipe(
Effect.as(true),
Effect.catchTags({
ElectronUpdaterCheckForUpdatesError: Effect.fn(
"desktop.updates.handleCheckForUpdatesFailure",
)(function* (error) {
const failedAt = yield* currentIsoTimestamp;
yield* updateState((current) =>
reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
return true;
}),
}),
}),
Effect.ensuring(Ref.set(updateCheckInFlightRef, false)),
);
);
});
return yield* actionReservation === "held"
? check
: check.pipe(Effect.ensuring(finishUpdateAction("check")));
});
const downloadAvailableUpdate = Effect.gen(function* () {
const state = yield* Ref.get(updateStateRef);
if (
!(yield* Ref.get(updaterConfiguredRef)) ||
(yield* Ref.get(updateDownloadInFlightRef)) ||
state.status !== "available"
) {
if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
return { accepted: false, completed: false };
}
if (!(yield* tryStartUpdateAction("download"))) {
return { accepted: false, completed: false };
}
yield* Ref.set(updateDownloadInFlightRef, true);
return yield* Effect.gen(function* () {
yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
yield* electronUpdater.setDisableDifferentialDownload(
@@ -442,27 +453,35 @@ export const make = Effect.gen(function* () {
return { accepted: true, completed: false };
});
}),
Effect.ensuring(Ref.set(updateDownloadInFlightRef, false)),
Effect.ensuring(finishUpdateAction("download")),
);
}).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
const resetInstallAction = Effect.all(
[Ref.set(updateInstallInFlightRef, false), Ref.set(desktopState.quitting, false)],
[finishUpdateAction("install"), Ref.set(desktopState.quitting, false)],
{ discard: true },
);
const installDownloadedUpdate = Effect.gen(function* () {
const state = yield* Ref.get(updateStateRef);
const hasInstallableDownload =
state.downloadedVersion !== null &&
(state.status === "downloaded" ||
(state.status === "error" &&
(state.errorContext === null || state.errorContext === "install")));
if (
(yield* Ref.get(desktopState.quitting)) ||
!(yield* Ref.get(updaterConfiguredRef)) ||
state.status !== "downloaded"
!hasInstallableDownload
) {
return { accepted: false, completed: false };
}
if (!(yield* tryStartUpdateAction("install"))) {
return { accepted: false, completed: false };
}
yield* Ref.set(desktopState.quitting, true);
yield* Ref.set(updateInstallInFlightRef, true);
return yield* Effect.gen(function* () {
// Stop every backend in the pool, not just the primary. With
@@ -614,8 +633,8 @@ export const make = Effect.gen(function* () {
operation: Option.getOrElse(activeAction, () => "background" as const),
cause,
});
if (yield* Ref.get(updateInstallInFlightRef)) {
yield* Ref.set(updateInstallInFlightRef, false);
if (Option.isSome(activeAction) && activeAction.value === "install") {
yield* finishUpdateAction("install");
yield* Ref.set(desktopState.quitting, false);
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
@@ -627,8 +646,7 @@ export const make = Effect.gen(function* () {
return;
}
if (!(yield* Ref.get(updateCheckInFlightRef)) && !(yield* Ref.get(updateDownloadInFlightRef))) {
const errorContext = yield* resolveUpdaterErrorContext;
if (Option.isNone(activeAction)) {
const checkedAt = yield* currentIsoTimestamp;
yield* updateState((current) => ({
...current,
@@ -636,7 +654,7 @@ export const make = Effect.gen(function* () {
message: error.message,
checkedAt,
downloadPercent: null,
errorContext,
errorContext: current.errorContext,
canRetry: getCanRetryFromState(current),
}));
}
@@ -773,7 +791,7 @@ export const make = Effect.gen(function* () {
nextChannel: DesktopUpdateChannel,
) {
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
const activeAction = yield* activeUpdateAction;
const activeAction = yield* tryStartChannelChange;
if (Option.isSome(activeAction)) {
return yield* new DesktopUpdateActionInProgressError({
action: activeAction.value,
@@ -781,33 +799,35 @@ export const make = Effect.gen(function* () {
});
}
const state = yield* Ref.get(updateStateRef);
if (nextChannel === state.channel) {
return state;
}
return yield* Effect.gen(function* () {
const state = yield* Ref.get(updateStateRef);
if (nextChannel === state.channel) {
return state;
}
yield* desktopSettings
.setUpdateChannel(nextChannel)
.pipe(
Effect.mapError(
(cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
),
yield* desktopSettings
.setUpdateChannel(nextChannel)
.pipe(
Effect.mapError(
(cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
),
);
const enabled = yield* shouldEnableAutoUpdates;
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) {
return yield* Ref.get(updateStateRef);
}
yield* applyAutoUpdaterChannel(nextChannel);
const allowDowngrade = yield* electronUpdater.allowDowngrade;
yield* electronUpdater.setAllowDowngrade(true);
yield* checkForUpdates("channel-change", "held").pipe(
Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
);
const enabled = yield* shouldEnableAutoUpdates;
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) {
return yield* Ref.get(updateStateRef);
}
yield* applyAutoUpdaterChannel(nextChannel);
const allowDowngrade = yield* electronUpdater.allowDowngrade;
yield* electronUpdater.setAllowDowngrade(true);
yield* checkForUpdates("channel-change").pipe(
Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
);
return yield* Ref.get(updateStateRef);
}).pipe(Effect.ensuring(finishUpdateAction("channel")));
}),
check: Effect.fn("desktop.updates.check")(function* (reason: string) {
yield* Effect.annotateCurrentSpan({ reason });
+80 -1
View File
@@ -55,6 +55,57 @@ describe("updateMachine", () => {
expect(state.canRetry).toBe(true);
});
it("preserves an already-downloaded update while checking the feed", () => {
const downloadedState = {
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "downloaded" as const,
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
releaseNotes: [{ version: "1.1.0", items: ["fix: queued update"] }],
downloadPercent: 100,
};
const checking = reduceDesktopUpdateStateOnCheckStart(
downloadedState,
"2026-03-04T00:00:00.000Z",
);
const failed = reduceDesktopUpdateStateOnCheckFailure(
checking,
"network unavailable",
"2026-03-04T00:00:01.000Z",
);
expect(checking.status).toBe("checking");
expect(checking.downloadedVersion).toBe("1.1.0");
expect(checking.releaseNotes).toEqual(downloadedState.releaseNotes);
expect(failed.status).toBe("downloaded");
expect(failed.downloadedVersion).toBe("1.1.0");
expect(failed.releaseNotes).toEqual(downloadedState.releaseNotes);
expect(failed.message).toBeNull();
});
it("keeps the installer when the feed still offers its version", () => {
const releaseNotes = [{ version: "1.1.0", items: ["fix: queued update"] }];
const state = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "downloaded",
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
releaseNotes,
downloadPercent: 100,
},
"1.1.0",
"2026-03-04T00:00:00.000Z",
);
expect(state.status).toBe("downloaded");
expect(state.downloadedVersion).toBe("1.1.0");
expect(state.releaseNotes).toEqual(releaseNotes);
expect(state.downloadPercent).toBe(100);
});
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
@@ -95,7 +146,8 @@ describe("updateMachine", () => {
expect(failedInstall.canRetry).toBe(true);
});
it("clears stale download state when no update is available", () => {
it("preserves a downloaded update when no update is available", () => {
const releaseNotes = [{ version: "1.1.0", items: ["fix: queued update"] }];
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
@@ -103,6 +155,32 @@ describe("updateMachine", () => {
status: "error",
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
releaseNotes,
message: "old failure",
errorContext: "download",
canRetry: true,
},
"2026-03-04T00:00:00.000Z",
);
expect(state.status).toBe("downloaded");
expect(state.availableVersion).toBe("1.1.0");
expect(state.downloadedVersion).toBe("1.1.0");
expect(state.releaseNotes).toBe(releaseNotes);
expect(state.downloadPercent).toBe(100);
expect(state.message).toBeNull();
expect(state.errorContext).toBeNull();
expect(state.canRetry).toBe(true);
});
it("clears stale available state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "error",
availableVersion: "1.1.0",
releaseNotes: [{ version: "1.1.0", items: ["fix: stale update"] }],
message: "old failure",
errorContext: "download",
canRetry: true,
@@ -113,6 +191,7 @@ describe("updateMachine", () => {
expect(state.status).toBe("up-to-date");
expect(state.availableVersion).toBeNull();
expect(state.downloadedVersion).toBeNull();
expect(state.releaseNotes).toEqual([]);
expect(state.message).toBeNull();
expect(state.errorContext).toBeNull();
});
+36 -7
View File
@@ -43,13 +43,14 @@ export function reduceDesktopUpdateStateOnCheckStart(
state: DesktopUpdateState,
checkedAt: string,
): DesktopUpdateState {
const hasDownloadedUpdate = state.downloadedVersion !== null;
return {
...state,
status: "checking",
checkedAt,
releaseNotes: [],
releaseNotes: hasDownloadedUpdate ? state.releaseNotes : [],
message: null,
downloadPercent: null,
downloadPercent: hasDownloadedUpdate ? 100 : null,
errorContext: null,
canRetry: false,
};
@@ -60,6 +61,18 @@ export function reduceDesktopUpdateStateOnCheckFailure(
message: string,
checkedAt: string,
): DesktopUpdateState {
if (state.downloadedVersion !== null) {
return {
...state,
status: "downloaded",
message: null,
checkedAt,
downloadPercent: 100,
errorContext: null,
canRetry: true,
};
}
return {
...state,
status: "error",
@@ -77,17 +90,20 @@ export function reduceDesktopUpdateStateOnUpdateAvailable(
checkedAt: string,
releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote> = [],
): DesktopUpdateState {
const isDownloadedVersion = state.downloadedVersion === version;
const nextReleaseNotes =
isDownloadedVersion && releaseNotes.length === 0 ? state.releaseNotes : releaseNotes;
return {
...state,
status: "available",
status: isDownloadedVersion ? "downloaded" : "available",
availableVersion: version,
downloadedVersion: null,
releaseNotes,
downloadPercent: null,
downloadedVersion: isDownloadedVersion ? version : null,
releaseNotes: nextReleaseNotes,
downloadPercent: isDownloadedVersion ? 100 : null,
checkedAt,
message: null,
errorContext: null,
canRetry: false,
canRetry: isDownloadedVersion,
};
}
@@ -95,6 +111,19 @@ export function reduceDesktopUpdateStateOnNoUpdate(
state: DesktopUpdateState,
checkedAt: string,
): DesktopUpdateState {
if (state.downloadedVersion !== null) {
return {
...state,
status: "downloaded",
availableVersion: state.downloadedVersion,
downloadPercent: 100,
checkedAt,
message: null,
errorContext: null,
canRetry: true,
};
}
return {
...state,
status: "up-to-date",
@@ -73,14 +73,40 @@ describe("desktop update button state", () => {
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
});
it("prefers install when a downloaded version already exists", () => {
it("keeps install action available after a background updater error", () => {
const state: DesktopUpdateState = {
...baseState,
status: "error",
downloadedVersion: "1.1.0",
availableVersion: "1.1.0",
message: "background updater error",
errorContext: null,
canRetry: true,
};
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
expect(resolveDesktopUpdateButtonAction(state)).toBe("install");
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to restart and install");
});
it("prefers a newly available release over a stale downloaded version", () => {
const state: DesktopUpdateState = {
...baseState,
status: "available",
availableVersion: "1.1.0",
availableVersion: "1.2.0",
downloadedVersion: "1.1.0",
};
expect(resolveDesktopUpdateButtonAction(state)).toBe("install");
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
});
it("hides the install action while checking for a newer release", () => {
const state: DesktopUpdateState = {
...baseState,
status: "checking",
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
downloadPercent: 100,
};
expect(resolveDesktopUpdateButtonAction(state)).toBe("none");
});
it("hides the button for non-actionable check errors", () => {
@@ -275,7 +301,7 @@ describe("canCheckForUpdate", () => {
);
});
it("returns false once an update has been downloaded", () => {
it("returns true once an update has been downloaded so newer releases can be found", () => {
expect(
canCheckForUpdate({
...baseState,
@@ -283,7 +309,7 @@ describe("canCheckForUpdate", () => {
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
}),
).toBe(false);
).toBe(true);
});
it("returns true when idle", () => {
+10 -5
View File
@@ -23,7 +23,12 @@ export function getDesktopUpdateReleaseUrl(version: string | null): string | nul
export function resolveDesktopUpdateButtonAction(
state: DesktopUpdateState,
): DesktopUpdateButtonAction {
if (state.downloadedVersion) {
if (
state.downloadedVersion &&
(state.status === "downloaded" ||
(state.status === "error" &&
(state.errorContext === null || state.errorContext === "install")))
) {
return "install";
}
if (state.status === "available") {
@@ -89,6 +94,9 @@ export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string
if (state.errorContext === "install" && state.downloadedVersion) {
return `Install failed for ${state.downloadedVersion}. Click to retry.`;
}
if (state.downloadedVersion) {
return `Update ${state.downloadedVersion} downloaded. Click to restart and install.`;
}
return state.message ?? "Update failed";
}
return "Up to date";
@@ -120,9 +128,6 @@ export function shouldHighlightDesktopUpdateError(state: DesktopUpdateState | nu
export function canCheckForUpdate(state: DesktopUpdateState | null): boolean {
if (!state || !state.enabled) return false;
return (
state.status !== "checking" &&
state.status !== "downloading" &&
state.status !== "downloaded" &&
state.status !== "disabled"
state.status !== "checking" && state.status !== "downloading" && state.status !== "disabled"
);
}