fix(desktop): gate queued update checks and await macOS install handoff

This commit is contained in:
Mohamed Boudra
2026-11-25 14:23:06 +01:00
parent b4a0226bb0
commit bebcec4e51
6 changed files with 303 additions and 70 deletions
@@ -242,6 +242,7 @@ describe("daemon-manager commands", () => {
releaseChannel: "stable",
intent: "automatic",
autoDownload: false,
shouldCheck: expect.any(Function),
shouldAutoDownload: expect.any(Function),
});
@@ -252,12 +253,14 @@ describe("daemon-manager commands", () => {
releaseChannel: "stable",
intent: "manual",
autoDownload: false,
shouldCheck: undefined,
shouldAutoDownload: expect.any(Function),
});
mocks.settings = { ...DEFAULT_DESKTOP_SETTINGS, updates: { mode: "automatic" } };
await createDaemonCommandHandlers().check_app_update({ intent: "automatic" });
const lastCall = mocks.checkForAppUpdate.mock.calls.at(-1)?.[0] as {
shouldCheck: () => Promise<boolean>;
shouldAutoDownload: () => Promise<boolean>;
};
expect(lastCall).toMatchObject({
@@ -266,8 +269,10 @@ describe("daemon-manager commands", () => {
intent: "automatic",
autoDownload: true,
});
expect(await lastCall.shouldCheck()).toBe(true);
expect(await lastCall.shouldAutoDownload()).toBe(true);
mocks.settings = { ...DEFAULT_DESKTOP_SETTINGS, updates: { mode: "off" } };
expect(await lastCall.shouldCheck()).toBe(false);
expect(await lastCall.shouldAutoDownload()).toBe(false);
});
});
@@ -561,6 +561,10 @@ export function createDaemonCommandHandlers(): Record<string, DesktopCommandHand
releaseChannel: parseReleaseChannel(args) ?? settings.releaseChannel,
intent,
autoDownload: updateMode === "automatic",
shouldCheck:
intent === "automatic"
? async () => (await getDesktopSettingsStore().get()).updates.mode !== "off"
: undefined,
shouldAutoDownload: async () =>
(await getDesktopSettingsStore().get()).updates.mode === "automatic",
});
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import {
createAppUpdateService,
@@ -1147,6 +1147,40 @@ describe("app update service", () => {
});
});
it("skips a queued automatic check after Off is saved while an earlier check is in flight", async () => {
const { runtime, service } = createService({ bucket: async () => 0 });
let allowAutomaticChecks = true;
const firstCheck = runtime.deferNextCheck();
const firstPending = service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: true,
shouldCheck: async () => allowAutomaticChecks,
shouldAutoDownload: async () => allowAutomaticChecks,
});
const queuedPending = service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: true,
shouldCheck: async () => allowAutomaticChecks,
shouldAutoDownload: async () => allowAutomaticChecks,
});
await vi.waitFor(() => {
expect(runtime.checkCount).toBe(1);
});
allowAutomaticChecks = false;
firstCheck.resolve({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const [firstResult, queuedResult] = await Promise.all([firstPending, queuedPending]);
expect(runtime.checkCount).toBe(1);
expect(firstResult.hasUpdate).toBe(false);
expect(queuedResult.hasUpdate).toBe(false);
});
it("reports installer launch failures instead of success on both cached and downloaded paths", async () => {
const { runtime, service } = createService({ bucket: async () => 0 });
@@ -64,6 +64,7 @@ export interface AppUpdateInstallRequest {
targetVersion: string;
isSilent: boolean;
isForceRunAfter: boolean;
signal?: AbortSignal;
}
export interface AppUpdateInstallLaunchResult {
@@ -76,7 +77,9 @@ export interface AppUpdateRuntime {
setAutoDownload?(enabled: boolean): void;
checkForUpdates(): Promise<RuntimeUpdateCheckResult | null>;
downloadUpdate(targetVersion: string): Promise<unknown>;
quitAndInstall(input: AppUpdateInstallRequest): AppUpdateInstallLaunchResult | void;
quitAndInstall(
input: AppUpdateInstallRequest,
): Promise<AppUpdateInstallLaunchResult | void> | AppUpdateInstallLaunchResult | void;
}
export interface AppUpdateService {
@@ -85,6 +88,7 @@ export interface AppUpdateService {
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
shouldCheck?: () => boolean | Promise<boolean>;
shouldAutoDownload?: () => boolean | Promise<boolean>;
}): Promise<AppUpdateCheckResult>;
downloadAndInstallUpdate(
@@ -147,17 +151,20 @@ async function performQuitAndInstall(
targetVersion,
onBeforeQuit,
restart,
signal,
}: {
targetVersion: string;
onBeforeQuit?: () => Promise<void>;
restart: boolean;
signal?: AbortSignal;
},
): Promise<void> {
if (onBeforeQuit) await onBeforeQuit();
const launch = runtime.quitAndInstall({
const launch = await runtime.quitAndInstall({
targetVersion,
isSilent: !restart,
isForceRunAfter: restart,
signal,
});
if (launch && !launch.started) {
throw new Error(launch.errorMessage ?? "Failed to launch update installer.");
@@ -224,6 +231,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
releaseChannel: AppReleaseChannel,
intent: AppUpdateCheckIntent,
autoDownload: boolean,
shouldCheck?: () => boolean | Promise<boolean>,
shouldAutoDownload?: () => boolean | Promise<boolean>,
): void {
if (configuredReleaseChannel !== releaseChannel) {
@@ -236,6 +244,9 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
releaseChannel,
autoDownload,
shouldAdmitUpdate: async (info) => {
if (shouldCheck && !(await shouldCheck())) {
return false;
}
const parsed = rolloutManifestSchema.parse(info);
const admitted = shouldAdmitAppUpdate({
channel: releaseChannel,
@@ -307,17 +318,61 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
return result;
}
function resolveAvailableUpdateResult(
currentVersion: string,
info: RuntimeUpdateInfo,
): AppUpdateCheckResult {
const latestVersion = info.version;
if (latestVersion === currentVersion) {
clearUpdateState();
return buildCheckResult({
currentVersion,
hasUpdate: false,
readyToInstall: false,
});
}
cachedUpdateInfo = info;
const readyToInstall = isReadyToInstallVersion(latestVersion);
const errorMessage =
preparationError?.version === latestVersion ? preparationError.message : null;
if (!errorMessage) {
preparationError = null;
}
if (
!readyToInstall &&
!errorMessage &&
currentAutoDownload &&
preparingUpdateVersion === null
) {
preparingUpdateVersion = latestVersion;
}
return buildCheckResult({
currentVersion,
hasUpdate: true,
readyToInstall,
downloading:
!readyToInstall &&
!errorMessage &&
(currentAutoDownload || preparingUpdateVersion === latestVersion),
info,
errorMessage,
});
}
async function checkForAppUpdate({
currentVersion,
releaseChannel,
intent,
autoDownload = true,
shouldCheck,
shouldAutoDownload,
}: {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
shouldCheck?: () => boolean | Promise<boolean>;
shouldAutoDownload?: () => boolean | Promise<boolean>;
}): Promise<AppUpdateCheckResult> {
if (!deps.isPackaged()) {
@@ -329,13 +384,34 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
}
return runCheckExclusively(async () => {
if (shouldCheck && !(await shouldCheck())) {
return buildCheckResult({
currentVersion,
hasUpdate: false,
readyToInstall: false,
});
}
if (intent === "manual") {
preparationError = null;
}
configureRuntime(releaseChannel, intent, autoDownload, shouldAutoDownload);
const effectiveAutoDownload = shouldAutoDownload ? await shouldAutoDownload() : autoDownload;
configureRuntime(
releaseChannel,
intent,
effectiveAutoDownload,
shouldCheck,
shouldAutoDownload,
);
try {
const result = await deps.runtime.checkForUpdates();
if (shouldCheck && !(await shouldCheck())) {
return buildCheckResult({
currentVersion,
hasUpdate: false,
readyToInstall: false,
});
}
if (!result || !result.updateInfo) {
clearUpdateState();
return buildCheckResult({
@@ -362,45 +438,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
});
}
const info = result.updateInfo;
const latestVersion = info.version;
const hasUpdate = latestVersion !== currentVersion;
if (hasUpdate) {
cachedUpdateInfo = info;
const readyToInstall = isReadyToInstallVersion(latestVersion);
const errorMessage =
preparationError?.version === latestVersion ? preparationError.message : null;
if (!errorMessage) {
preparationError = null;
}
if (
!readyToInstall &&
!errorMessage &&
currentAutoDownload &&
preparingUpdateVersion === null
) {
preparingUpdateVersion = latestVersion;
}
return buildCheckResult({
currentVersion,
hasUpdate: true,
readyToInstall,
downloading:
!readyToInstall &&
!errorMessage &&
(currentAutoDownload || preparingUpdateVersion === latestVersion),
info,
errorMessage,
});
}
clearUpdateState();
return buildCheckResult({
currentVersion,
hasUpdate: false,
readyToInstall: false,
});
return resolveAvailableUpdateResult(currentVersion, result.updateInfo);
} catch (error) {
deps.reportCheckError?.(error);
return buildCheckResult({
@@ -548,6 +586,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
targetVersion: readyVersion,
onBeforeQuit,
restart,
signal,
});
return {
@@ -1,3 +1,4 @@
import { EventEmitter } from "node:events";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -45,6 +46,7 @@ vi.mock("electron", () => ({
getPath: vi.fn(),
isPackaged: true,
},
autoUpdater: undefined,
BrowserWindow: {
getAllWindows: getAllWindowsMock,
},
@@ -61,6 +63,7 @@ import {
downloadAndInstallUpdate,
resolveStagingUserId,
rolloutManifestSchema,
runElectronQuitAndInstall,
shouldAdmitToRollout,
shouldInstallAppUpdateOnQuit,
} from "./auto-updater";
@@ -238,6 +241,58 @@ describe("checkForAppUpdate", () => {
consoleError.mockRestore();
});
it("waits on macOS until Squirrel either reports an async preparation error or signals quit", async () => {
const updater = Object.assign(new EventEmitter(), {
quitAndInstall: vi.fn(),
});
const nativeUpdater = new EventEmitter();
const appEvents = new EventEmitter();
const failedInstall = runElectronQuitAndInstall({
platform: "darwin",
updater,
nativeUpdater,
appEvents,
isSilent: false,
isForceRunAfter: true,
});
expect(
await Promise.race([failedInstall.then(() => "settled"), Promise.resolve("pending")]),
).toBe("pending");
nativeUpdater.emit("error", new Error("Code signature invalid"));
await expect(failedInstall).resolves.toEqual({
started: false,
errorMessage: "Code signature invalid",
});
expect(updater.listenerCount("error")).toBe(0);
expect(nativeUpdater.listenerCount("error")).toBe(0);
expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0);
const restartInstall = runElectronQuitAndInstall({
platform: "darwin",
updater,
nativeUpdater,
appEvents,
isSilent: false,
isForceRunAfter: true,
});
nativeUpdater.emit("before-quit-for-update");
await expect(restartInstall).resolves.toEqual({ started: true });
const quitInstall = runElectronQuitAndInstall({
platform: "darwin",
updater,
nativeUpdater,
appEvents,
isSilent: true,
isForceRunAfter: false,
});
appEvents.emit("before-quit");
await expect(quitInstall).resolves.toEqual({ started: true });
expect(appEvents.listenerCount("before-quit")).toBe(0);
});
it("logs the update handoff with current and selected target versions", () => {
const info = vi.fn();
const lifecycleLog = createAppUpdateLifecycleLogger({ info });
+123 -27
View File
@@ -1,7 +1,7 @@
import { randomBytes } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { app, BrowserWindow } from "electron";
import { app, autoUpdater as electronAutoUpdater, BrowserWindow } from "electron";
import { UUID } from "builder-util-runtime";
import log from "electron-log/main";
import { autoUpdater } from "electron-updater";
@@ -9,6 +9,7 @@ import {
createAppUpdateService,
type AppUpdateCheckResult,
type AppUpdateDownloadProgress,
type AppUpdateInstallLaunchResult,
type AppUpdateInstallRequest,
type AppUpdateInstallResult,
type AppUpdateRuntime,
@@ -172,6 +173,109 @@ function broadcastDownloadProgress(progress: AppUpdateDownloadProgress | null):
}
}
export interface QuitAndInstallEventSource {
on(event: string, listener: (...args: unknown[]) => void): unknown;
removeListener?(event: string, listener: (...args: unknown[]) => void): unknown;
}
function formatLaunchError(error: unknown): string {
return error instanceof Error && typeof error.message === "string"
? error.message
: String(error);
}
export function runElectronQuitAndInstall({
platform,
updater,
nativeUpdater,
appEvents,
isSilent,
isForceRunAfter,
signal,
}: {
platform: NodeJS.Platform;
updater: QuitAndInstallEventSource & {
quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void;
};
nativeUpdater?: QuitAndInstallEventSource;
appEvents?: QuitAndInstallEventSource;
isSilent: boolean;
isForceRunAfter: boolean;
signal?: AbortSignal;
}): Promise<AppUpdateInstallLaunchResult> {
if (platform !== "darwin" || typeof nativeUpdater?.on !== "function") {
let launchError: unknown = null;
const captureLaunchError = (error: unknown) => {
launchError ??= error;
};
updater.on("error", captureLaunchError);
try {
updater.quitAndInstall(isSilent, isForceRunAfter);
} catch (error) {
launchError ??= error;
} finally {
updater.removeListener?.("error", captureLaunchError);
}
if (launchError !== null) {
return Promise.resolve({ started: false, errorMessage: formatLaunchError(launchError) });
}
return Promise.resolve({ started: true });
}
// With autoInstallOnAppQuit disabled, electron-updater's MacUpdater starts
// native Squirrel preparation asynchronously inside quitAndInstall(). Keep
// the install promise pending until Squirrel hands off to quit or fails.
return new Promise<AppUpdateInstallLaunchResult>((resolve) => {
let settled = false;
const finish = (result: AppUpdateInstallLaunchResult) => {
if (settled) return;
settled = true;
updater.removeListener?.("error", handleError);
nativeUpdater.removeListener?.("error", handleError);
nativeUpdater.removeListener?.("update-not-available", handleNotAvailable);
nativeUpdater.removeListener?.("before-quit-for-update", handleQuitStarted);
if (!isForceRunAfter) {
appEvents?.removeListener?.("before-quit", handleQuitStarted);
}
signal?.removeEventListener("abort", handleAbort);
resolve(result);
};
const handleError = (error: unknown) => {
finish({ started: false, errorMessage: formatLaunchError(error) });
};
const handleNotAvailable = () => {
finish({ started: false, errorMessage: "Update could not be prepared for installation." });
};
const handleQuitStarted = () => {
finish({ started: true });
};
const handleAbort = () => {
finish({ started: false, errorMessage: "Update installation was deferred." });
};
if (signal?.aborted) {
handleAbort();
return;
}
updater.on("error", handleError);
nativeUpdater.on("error", handleError);
nativeUpdater.on("update-not-available", handleNotAvailable);
nativeUpdater.on("before-quit-for-update", handleQuitStarted);
if (!isForceRunAfter) {
appEvents?.on("before-quit", handleQuitStarted);
}
signal?.addEventListener("abort", handleAbort, { once: true });
try {
updater.quitAndInstall(isSilent, isForceRunAfter);
} catch (error) {
handleError(error);
}
});
}
class ElectronAppUpdateRuntime implements AppUpdateRuntime {
private configured = false;
private configuration: AppUpdateRuntimeConfiguration | null = null;
@@ -252,10 +356,12 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
return autoUpdater.downloadUpdate();
}
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): {
started: boolean;
errorMessage?: string;
} {
quitAndInstall({
targetVersion,
isSilent,
isForceRunAfter,
signal,
}: AppUpdateInstallRequest): Promise<AppUpdateInstallLaunchResult> {
broadcastDownloadProgress(null);
autoUpdater.autoRunAppAfterInstall = isForceRunAfter;
updateLifecycleLog.quitAndInstallRequested({
@@ -263,28 +369,15 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
isSilent,
isForceRunAfter,
});
let launchError: unknown = null;
const captureLaunchError = (error: unknown) => {
launchError ??= error;
};
autoUpdater.on("error", captureLaunchError);
try {
autoUpdater.quitAndInstall(isSilent, isForceRunAfter);
} catch (error) {
launchError ??= error;
} finally {
if (typeof autoUpdater.removeListener === "function") {
autoUpdater.removeListener("error", captureLaunchError);
}
}
if (launchError !== null) {
const errorMessage =
launchError instanceof Error && typeof launchError.message === "string"
? launchError.message
: String(launchError);
return { started: false, errorMessage };
}
return { started: true };
return runElectronQuitAndInstall({
platform: process.platform,
updater: autoUpdater,
nativeUpdater: electronAutoUpdater,
appEvents: app,
isSilent,
isForceRunAfter,
signal,
});
}
}
@@ -314,12 +407,14 @@ export async function checkForAppUpdate({
releaseChannel,
intent,
autoDownload = true,
shouldCheck,
shouldAutoDownload,
}: {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
shouldCheck?: () => boolean | Promise<boolean>;
shouldAutoDownload?: () => boolean | Promise<boolean>;
}): Promise<AppUpdateCheckResult> {
updateLifecycleLog.checkStarted({ currentVersion, releaseChannel, intent });
@@ -328,6 +423,7 @@ export async function checkForAppUpdate({
releaseChannel,
intent,
autoDownload,
shouldCheck,
shouldAutoDownload,
});
updateLifecycleLog.checkCompleted({