Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(desktop): refresh pending updates on every platform (#776)

tianma-if7e9630dd8291
diff --git a/apps/desktop/src/main/windows-update-controller.mjs b/apps/desktop/src/main/desktop-update-controller.mjs
similarity index 61%
rename from apps/desktop/src/main/windows-update-controller.mjs
rename to apps/desktop/src/main/desktop-update-controller.mjs
index 03c66f24..42efdd0e 100644
--- a/apps/desktop/src/main/windows-update-controller.mjs
+++ b/apps/desktop/src/main/desktop-update-controller.mjs
@@ -1,9 +1,11 @@
import { isDeepStrictEqual } from "node:util";
+import { prepareMacUpdate } from "./mac-update-install.mjs";
// electron-updater owns one mutable download/install target. Keep checks,
// downloads and package verification serialized around that target.
-export const createWindowsUpdateController = ({
- updater, fetchWindowsMetadata, verifyWindowsPackage,
+export const createDesktopUpdateController = ({
+ updater, platform, nativeUpdater, fetchWindowsMetadata, verifyWindowsPackage,
+ quitApplication = () => {},
onStatus, onError, onDownloaded, beforeInstall,
onStage = () => {}, onCheckStarted = () => {}, onSettled = () => {},
log = () => {},
@@ -16,13 +18,23 @@ export const createWindowsUpdateController = ({
let verificationInFlight = null;
let installInFlight = null;
let installing = false;
+ let quittingForUpdate = false;
+ let quitRequested = false;
+ let skipQuitInstall = false;
+ let nativePreparationStarted = false;
+ let nativePreparationFailed = false;
+ const windows = platform === "win32";
+ const mac = platform === "darwin";
+ const downloadedPath = () => mac ? updater.downloadedUpdateHelper?.file : updater.installerPath;
const publish = (next) => { status = { ...status, ...next }; onStatus({ ...status }); };
const packageMatches = (candidate) => Boolean(candidate && (
- candidate.manifest?.version === candidate.info.version &&
- candidate.path && updater.installerPath === candidate.path
+ (!windows || candidate.manifest?.version === candidate.info.version) &&
+ candidate.path && downloadedPath() === candidate.path
));
const refreshQuitInstall = () => {
- updater.autoInstallOnAppQuit = !checkInFlight && !downloadInFlight &&
+ // Squirrel must not stage an intermediate background download. The shared
+ // before-quit hook refreshes the target before normal quit installation.
+ updater.autoInstallOnAppQuit = !mac && !checkInFlight && !downloadInFlight &&
!verificationInFlight && ready === target && packageMatches(ready);
if (updater.autoInstallOnAppQuit) {
// BaseUpdater normally registers this during update-downloaded, before
@@ -63,19 +75,21 @@ export const createWindowsUpdateController = ({
updater.on("update-downloaded", (info) => {
const candidate = target;
if (!downloadInFlight || verificationInFlight) {
- fail(new Error("Unexpected update download completion"), "verify-windows-package");
+ fail(new Error("Unexpected update download completion"), windows ? "verify-windows-package" : "download");
return;
}
verificationInFlight = Promise.resolve().then(async () => {
if (!candidate || candidate.info.version !== info?.version) {
throw new Error("Downloaded update does not match the selected target");
}
- onStage("verify-windows-package");
- if (!candidate.manifest || candidate.manifest.version !== info.version ||
- !info.downloadedFile || updater.installerPath !== info.downloadedFile) {
- throw new Error("Downloaded Windows update has no matching trusted installer");
+ if (windows) {
+ onStage("verify-windows-package");
+ if (!candidate.manifest || candidate.manifest.version !== info.version ||
+ !info.downloadedFile || updater.installerPath !== info.downloadedFile) {
+ throw new Error("Downloaded Windows update has no matching trusted installer");
+ }
+ await verifyWindowsPackage({ path: info.downloadedFile, manifest: candidate.manifest });
}
- await verifyWindowsPackage({ path: info.downloadedFile, manifest: candidate.manifest });
if (target !== candidate) throw new Error("Update target changed during package verification");
candidate.path = info.downloadedFile;
candidate.verified = true;
@@ -87,7 +101,7 @@ export const createWindowsUpdateController = ({
const download = (reason) => {
if (downloadInFlight) return downloadInFlight;
const candidate = target;
- if (!candidate || !candidate.manifest) {
+ if (!candidate || (windows && !candidate.manifest)) {
return Promise.reject(new Error("Update metadata has not passed the signature gate"));
}
if (ready === candidate && packageMatches(ready)) return Promise.resolve();
@@ -103,8 +117,8 @@ export const createWindowsUpdateController = ({
publish({ state: "downloaded", version: candidate.info.version, progress: null });
log("update.downloaded", { version: candidate.info.version });
}).catch((error) => {
- fail(error, verificationInFlight ? "verify-windows-package" : "download");
- log(verificationInFlight ? "update.windows-package-blocked" : "update.download-failed", {
+ fail(error, windows && verificationInFlight ? "verify-windows-package" : "download");
+ log(windows && verificationInFlight ? "update.windows-package-blocked" : "update.download-failed", {
reason, message: error.message,
});
}).finally(() => {
@@ -112,12 +126,15 @@ export const createWindowsUpdateController = ({
verificationInFlight = null;
refreshQuitInstall();
if (!checkInFlight) onSettled();
- if (ready === candidate) onDownloaded(candidate.info.version);
+ if (ready === candidate && !quitRequested) onDownloaded(candidate.info.version);
});
return downloadInFlight;
};
const check = (reason) => {
+ if (nativePreparationFailed) {
+ return Promise.reject(new Error("Restart EdgeEver before retrying native macOS update preparation"));
+ }
if (installing) return Promise.resolve(null);
if (checkInFlight) return checkInFlight;
// In particular, do not change updater.updateInfoAndProvider while a
@@ -145,11 +162,13 @@ export const createWindowsUpdateController = ({
target = { info, manifest: null, path: null, verified: false };
publish({ state: "available", version: info.version, progress: null });
log("update.available", { version: info.version });
- stage = "verify-windows-metadata";
- onStage(stage);
- target.manifest = await fetchWindowsMetadata({ version: info.version, updateInfo: info });
- if (target.manifest.version !== info.version) throw new Error("Windows manifest target mismatch");
- log("update.windows-manifest-verified", { version: info.version, keyId: target.manifest.keyId });
+ if (windows) {
+ stage = "verify-windows-metadata";
+ onStage(stage);
+ target.manifest = await fetchWindowsMetadata({ version: info.version, updateInfo: info });
+ if (target.manifest.version !== info.version) throw new Error("Windows manifest target mismatch");
+ log("update.windows-manifest-verified", { version: info.version, keyId: target.manifest.keyId });
+ }
void download(reason);
return result;
}).catch((error) => {
@@ -174,21 +193,59 @@ export const createWindowsUpdateController = ({
if (downloadInFlight) await downloadInFlight;
if (!ready || ready !== target || !ready.verified || !packageMatches(ready) ||
checkInFlight || downloadInFlight || verificationInFlight ||
- (expectedVersion && expectedVersion !== ready.info.version)) {
+ (expectedVersion && !quitRequested && expectedVersion !== ready.info.version)) {
return { started: false };
}
installing = true;
log("update.install-confirmed", { version: ready.info.version });
+ if (mac) {
+ onStage("install");
+ nativePreparationStarted = true;
+ await prepareMacUpdate(nativeUpdater);
+ if (ready !== target || !packageMatches(ready)) {
+ throw new Error("macOS installation target changed during native preparation");
+ }
+ }
beforeInstall();
- updater.quitAndInstall(true, true);
+ quittingForUpdate = true;
+ updater.autoRunAppAfterInstall = !quitRequested;
+ if (mac) {
+ if (quitRequested) quitApplication(); // Squirrel applies the staged ZIP without relaunching.
+ else nativeUpdater.quitAndInstall();
+ } else {
+ updater.quitAndInstall(windows, !quitRequested);
+ }
return { started: true };
}).catch((error) => {
installing = false;
- if (status.state !== "idle") fail(error, "install");
+ quittingForUpdate = false;
+ if (mac && nativePreparationStarted) {
+ // Electron exposes no cancellation for Squirrel. A timed-out or failed
+ // operation may still complete later; never let it race a new target.
+ nativePreparationFailed = true;
+ fail(new Error(`macOS native update preparation failed; restart EdgeEver before retrying: ${error.message}`), "install");
+ } else if (status.state !== "idle") {
+ fail(error, "install");
+ }
return { started: false };
- }).finally(() => { installInFlight = null; });
+ }).finally(() => {
+ installInFlight = null;
+ if (quitRequested && !quittingForUpdate) {
+ skipQuitInstall = true;
+ quitApplication();
+ }
+ });
return installInFlight;
};
- return { check, download, install, snapshot: () => ({ ...status }) };
+ const handleBeforeQuit = (event) => {
+ if (skipQuitInstall || quittingForUpdate || (!ready && !installInFlight)) return false;
+ event.preventDefault();
+ quitRequested = true;
+ // If a check or preparation fails, quit without installing the old package.
+ if (!installInFlight) void install();
+ return true;
+ };
+
+ return { check, download, install, handleBeforeQuit, snapshot: () => ({ ...status }) };
};
diff --git a/apps/desktop/src/main/desktop-update-controller.test.mjs b/apps/desktop/src/main/desktop-update-controller.test.mjs
new file mode 100644
index 00000000..f566c4b4
--- /dev/null
+++ b/apps/desktop/src/main/desktop-update-controller.test.mjs
@@ -0,0 +1,325 @@
+import { createRequire } from "node:module";
+import { EventEmitter } from "node:events";
+import { createHash } from "node:crypto";
+import { mkdtemp, writeFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, test } from "bun:test";
+import { createDesktopUpdateController } from "./desktop-update-controller.mjs";
+import { prepareMacUpdate } from "./mac-update-install.mjs";
+
+const require = createRequire(new URL("../../package.json", import.meta.url));
+const { BaseUpdater } = require("electron-updater/out/BaseUpdater.js");
+const { MacUpdater } = require("electron-updater/out/MacUpdater.js");
+const { AppImageUpdater } = require("electron-updater/out/AppImageUpdater.js");
+const cleanup = [];
+afterEach(async () => { for (const close of cleanup.splice(0)) await close(); });
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((yes) => { resolve = yes; });
+ return { promise, resolve };
+};
+const flush = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); };
+
+// Use real AppUpdater selection/download bookkeeping and MacUpdater's real
+// authenticated loopback proxy. The native Squirrel API and installer process
+// are simulated; these tests do not claim OS signing or installation coverage.
+const harness = async (platform) => {
+ const directory = await mkdtemp(join(tmpdir(), "edgeever-desktop-update-"));
+ cleanup.push(() => rm(directory, { recursive: true, force: true }));
+ const releases = new Map();
+ for (const version of ["2.17.0", "2.18.0", "2.19.0"]) {
+ const bytes = Buffer.from(`package ${version}`);
+ const name = platform === "darwin" ? `EdgeEver-${version}-mac-arm64.zip` : `EdgeEver-${version}-linux-x64.AppImage`;
+ const path = join(directory, name);
+ await writeFile(path, bytes);
+ releases.set(version, { path, bytes, info: { version, files: [{ url: name, size: bytes.length,
+ sha512: createHash("sha512").update(bytes).digest("base64") }] } });
+ }
+ const h = { latest: "2.17.0", checks: 0, downloads: [], installs: [], errors: [], notices: [],
+ prepared: [], quitFallbacks: 0, relaunches: [], checkError: null, downloadError: null, eventVersion: null,
+ downloadGate: null, checkGate: null, nativeGate: null, nativeError: null };
+ const app = { version: "2.16.1", isPackaged: true, onQuit: (handler) => { h.quitHandler = handler; } };
+ const updater = platform === "linux" ? new AppImageUpdater(null, app) : new BaseUpdater(null, app);
+ updater.logger = null;
+ if (platform === "linux") updater.forceDevUpdateConfig = true;
+ const native = new EventEmitter();
+ let feed;
+ let preparedVersion;
+ native.setFeedURL = (options) => { feed = options; };
+ native.getFeedURL = () => feed?.url;
+ native.checkForUpdates = () => {
+ void (async () => {
+ if (h.nativeGate) await h.nativeGate.promise;
+ if (h.nativeError) throw h.nativeError;
+ const expectedFeed = feed;
+ const response = await fetch(expectedFeed.url, { headers: expectedFeed.headers });
+ if (!response.ok) throw new Error(`Feed returned ${response.status}`);
+ const metadata = await response.json();
+ const zip = await fetch(metadata.url);
+ if (!zip.ok) throw new Error(`Archive returned ${zip.status}`);
+ const bytes = Buffer.from(await zip.arrayBuffer());
+ const release = [...releases].find(([, value]) => value.bytes.equals(bytes));
+ if (!release) throw new Error("Native updater received an unexpected ZIP");
+ preparedVersion = release[0];
+ h.prepared.push(preparedVersion);
+ native.emit("update-downloaded");
+ })().catch((error) => native.emit("error", error));
+ };
+ native.quitAndInstall = () => {
+ h.relaunches.push(true);
+ h.installs.push({ version: preparedVersion, path: releases.get(preparedVersion).path });
+ updater.closeServerIfExists();
+ };
+ if (platform === "darwin") {
+ // Initialize the real MacUpdater methods without loading Electron's native
+ // module into the test runner. Its global native updater is injected here.
+ Object.setPrototypeOf(updater, MacUpdater.prototype);
+ updater.nativeUpdater = native;
+ updater.squirrelDownloadedUpdate = false;
+ native.on("error", (error) => updater.emit("error", error));
+ native.on("update-downloaded", () => { updater.squirrelDownloadedUpdate = true; });
+ cleanup.push(() => { updater.closeServerIfExists(); });
+ }
+ updater.getUpdateInfoAndProvider = async () => {
+ h.checks++;
+ if (h.checkGate) await h.checkGate.promise;
+ if (h.checkError) throw h.checkError;
+ const info = h.latest ? structuredClone(releases.get(h.latest).info) : { version: "2.16.1" };
+ return { info, provider: {} };
+ };
+ updater.doDownloadUpdate = async ({ updateInfoAndProvider: { info } }) => {
+ const version = info.version;
+ h.downloads.push(version);
+ if (h.downloadGate) await h.downloadGate.promise;
+ if (h.downloadError) throw h.downloadError;
+ const path = releases.get(version).path;
+ updater.downloadedUpdateHelper = { file: path, downloadedFileInfo: { isAdminRightsRequired: false } };
+ const event = { ...info, version: h.eventVersion || version, downloadedFile: path };
+ if (platform === "darwin") {
+ return updater.updateDownloaded({ url: new URL(`https://example.invalid/${info.files[0].url}`), info: info.files[0] }, event);
+ }
+ updater.dispatchUpdateDownloaded(event);
+ updater.addQuitHandler();
+ return [path];
+ };
+ if (platform === "linux") {
+ updater.doInstall = ({ isForceRunAfter }) => {
+ h.relaunches.push(isForceRunAfter);
+ const path = updater.installerPath;
+ h.installs.push({ version: [...releases].find(([, value]) => value.path === path)[0], path });
+ return true;
+ };
+ updater.quitAndInstall = (silent, forceRun) => updater.install(silent, forceRun);
+ }
+ const controller = createDesktopUpdateController({
+ updater, platform, nativeUpdater: native,
+ fetchWindowsMetadata: () => { throw new Error("Windows trust must not run on another platform"); },
+ verifyWindowsPackage: () => { throw new Error("Windows trust must not run on another platform"); },
+ onStatus: () => {}, onError: (error, stage) => h.errors.push({ error, stage }),
+ onDownloaded: (version) => h.notices.push(version), beforeInstall: () => {},
+ quitApplication: () => {
+ if (platform === "darwin" && preparedVersion) {
+ h.relaunches.push(false);
+ h.installs.push({ version: preparedVersion, path: releases.get(preparedVersion).path });
+ updater.closeServerIfExists();
+ } else {
+ h.quitFallbacks++;
+ }
+ },
+ });
+ const settle = () => controller.download("wait").catch(() => {});
+ const ready = async () => { await controller.check("startup"); await settle(); };
+ return Object.assign(h, { updater, native, controller, releases, settle, ready });
+};
+
+for (const platform of ["darwin", "linux"]) {
+ describe(`${platform} update target lifecycle (#776)`, () => {
+ test("replaces a downloaded intermediate release and installs only the latest package", async () => {
+ const h = await harness(platform);
+ await h.ready();
+ h.latest = "2.19.0";
+ await h.controller.check("interval");
+ await h.settle();
+ expect(h.downloads).toEqual(["2.17.0", "2.19.0"]);
+ expect(h.prepared).toEqual([]);
+ expect(await h.controller.install()).toEqual({ started: true });
+ expect(h.installs).toEqual([{ version: "2.19.0", path: h.releases.get("2.19.0").path }]);
+ });
+
+ test("refreshes the latest target at installation time", async () => {
+ const h = await harness(platform);
+ await h.ready();
+ h.latest = "2.18.0";
+ expect(await h.controller.install()).toEqual({ started: true });
+ expect(h.installs.map((entry) => entry.version)).toEqual(["2.18.0"]);
+ });
+
+ test("normal quit refreshes the target and installs without relaunching", async () => {
+ const h = await harness(platform);
+ await h.ready();
+ h.latest = "2.19.0";
+ expect(h.controller.handleBeforeQuit({ preventDefault() {} })).toBe(true);
+ await h.controller.install();
+ expect(h.installs.map((entry) => entry.version)).toEqual(["2.19.0"]);
+ expect(h.relaunches).toEqual([false]);
+ expect(h.notices).toEqual(["2.17.0"]);
+ expect(h.controller.handleBeforeQuit({ preventDefault() { throw new Error("quit loop"); } })).toBe(false);
+ });
+
+ test("unchanged metadata does not download or prompt twice", async () => {
+ const h = await harness(platform);
+ await h.ready();
+ await h.controller.check("manual");
+ expect(h.checks).toBe(2);
+ expect(h.downloads).toEqual(["2.17.0"]);
+ expect(h.notices).toEqual(["2.17.0"]);
+ });
+
+ test("a stale dialog approval cannot install a replacement", async () => {
+ const h = await harness(platform);
+ await h.ready();
+ h.latest = "2.18.0";
+ expect(await h.controller.install("2.17.0")).toEqual({ started: false });
+ expect(h.installs).toEqual([]);
+ expect(h.prepared).toEqual([]);
+ expect(await h.controller.install("2.18.0")).toEqual({ started: true });
+ });
+
+ test("does not change the target while another version is downloading", async () => {
+ const h = await harness(platform);
+ await h.ready();
+ h.latest = "2.18.0";
+ h.downloadGate = deferred();
+ await h.controller.check("manual");
+ h.latest = "2.19.0";
+ await h.controller.check("resume");
+ expect(h.checks).toBe(2);
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ h.downloadGate.resolve();
+ await h.settle();
+ expect(h.controller.snapshot().version).toBe("2.18.0");
+ });
+
+ for (const failure of ["check", "download", "event-version"]) {
+ test(`a ${failure} failure never installs the old package`, async () => {
+ const h = await harness(platform);
+ await h.ready();
+ h.latest = "2.18.0";
+ if (failure === "check") h.checkError = new Error("offline");
+ if (failure === "download") h.downloadError = new Error("download failed");
+ if (failure === "event-version") h.eventVersion = "2.17.0";
+ await h.controller.check("interval").catch(() => {});
+ await h.settle();
+ expect(await h.controller.install()).toEqual({ started: false });
+ expect(h.installs).toEqual([]);
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ });
+ }
+ });
+}
+
+describe("macOS native installation", () => {
+ test("never stages intermediate background downloads in Squirrel", async () => {
+ const h = await harness("darwin");
+ await h.ready();
+ h.latest = "2.18.0";
+ await h.controller.check("interval");
+ await h.settle();
+ expect(h.prepared).toEqual([]);
+ expect(h.updater.squirrelDownloadedUpdate).toBe(false);
+ // Even stale bookkeeping must not shortcut preparation of the current ZIP.
+ h.updater.squirrelDownloadedUpdate = true;
+ expect(await h.controller.install()).toEqual({ started: true });
+ expect(h.prepared).toEqual(["2.18.0"]);
+ expect(h.installs.map((entry) => entry.version)).toEqual(["2.18.0"]);
+ });
+
+ test("normal quit refreshes and prepares the latest version before installation", async () => {
+ const h = await harness("darwin");
+ await h.ready();
+ h.latest = "2.19.0";
+ let prevented = false;
+ expect(h.controller.handleBeforeQuit({ preventDefault() { prevented = true; } })).toBe(true);
+ expect(prevented).toBe(true);
+ await h.controller.install();
+ expect(h.prepared).toEqual(["2.19.0"]);
+ expect(h.installs.map((entry) => entry.version)).toEqual(["2.19.0"]);
+ expect(h.quitFallbacks).toBe(0);
+ expect(h.controller.handleBeforeQuit({ preventDefault() { throw new Error("blocked final quit"); } })).toBe(false);
+ });
+
+ test("native signature failure does not install or retain an installation listener", async () => {
+ const h = await harness("darwin");
+ await h.ready();
+ h.nativeError = new Error("native code signature rejected");
+ expect(await h.controller.install()).toEqual({ started: false });
+ expect(h.installs).toEqual([]);
+ expect(h.native.listenerCount("update-downloaded")).toBe(1); // MacUpdater bookkeeping only.
+ expect(h.errors[0].stage).toBe("install");
+ h.nativeError = null;
+ h.latest = "2.19.0";
+ await expect(h.controller.check("interval")).rejects.toThrow("Restart EdgeEver");
+ h.native.emit("update-downloaded"); // Late completion cannot authorize another target.
+ expect(h.installs).toEqual([]);
+ expect(h.downloads).toEqual(["2.17.0"]);
+ });
+
+ test("a failed check while quitting exits without staging an older package", async () => {
+ const h = await harness("darwin");
+ await h.ready();
+ h.checkError = new Error("offline");
+ h.controller.handleBeforeQuit({ preventDefault() {} });
+ await h.controller.install();
+ expect(h.quitFallbacks).toBe(1);
+ expect(h.prepared).toEqual([]);
+ expect(h.installs).toEqual([]);
+ expect(h.controller.handleBeforeQuit({ preventDefault() { throw new Error("quit loop"); } })).toBe(false);
+ });
+
+ test("quit waits for ongoing native preparation and does not start a second install", async () => {
+ const h = await harness("darwin");
+ await h.ready();
+ h.nativeGate = deferred();
+ const install = h.controller.install();
+ await flush();
+ expect(h.controller.handleBeforeQuit({ preventDefault() {} })).toBe(true);
+ expect(h.installs).toEqual([]);
+ h.nativeGate.resolve();
+ await install;
+ expect(h.prepared).toEqual(["2.17.0"]);
+ expect(h.installs).toHaveLength(1);
+ });
+
+ test("a changed native feed cannot complete preparation of another target", async () => {
+ const native = new EventEmitter();
+ let feed = "http://127.0.0.1:1/";
+ native.getFeedURL = () => feed;
+ native.checkForUpdates = () => {
+ feed = "http://127.0.0.1:2/";
+ native.emit("update-downloaded");
+ };
+ await expect(prepareMacUpdate(native)).rejects.toThrow("feed changed");
+ expect(native.listenerCount("update-downloaded")).toBe(0);
+ expect(native.listenerCount("error")).toBe(0);
+ });
+
+ test("native update-not-available fails immediately and removes temporary listeners", async () => {
+ const native = new EventEmitter();
+ native.getFeedURL = () => "http://127.0.0.1:1/";
+ native.checkForUpdates = () => native.emit("update-not-available");
+ await expect(prepareMacUpdate(native)).rejects.toThrow("not available");
+ expect(native.listenerCount("update-downloaded")).toBe(0);
+ expect(native.listenerCount("error")).toBe(0);
+ expect(native.listenerCount("update-not-available")).toBe(0);
+ });
+
+ test("native timeout removes temporary listeners", async () => {
+ const native = new EventEmitter();
+ native.getFeedURL = () => "http://127.0.0.1:1/";
+ native.checkForUpdates = () => {};
+ await expect(prepareMacUpdate(native, { timeoutMs: 1 })).rejects.toThrow("timed out");
+ expect(native.listenerCount("update-downloaded")).toBe(0);
+ expect(native.listenerCount("error")).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/main/desktop-update-flow.test.mjs b/apps/desktop/src/main/desktop-update-flow.test.mjs
index acc94758..4e81ba34 100644
--- a/apps/desktop/src/main/desktop-update-flow.test.mjs
+++ b/apps/desktop/src/main/desktop-update-flow.test.mjs
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
import { describe, expect, test } from "bun:test";
const mainSource = readFileSync(new URL("./index.mjs", import.meta.url), "utf8");
-const windowsUpdateSource = readFileSync(new URL("./windows-update-controller.mjs", import.meta.url), "utf8");
+const controllerSource = readFileSync(new URL("./desktop-update-controller.mjs", import.meta.url), "utf8");
const preloadSource = readFileSync(new URL("../preload/index.cjs", import.meta.url), "utf8");
const noticeSource = readFileSync(new URL("../../../web/src/components/DesktopUpdateNotice.tsx", import.meta.url), "utf8");
const systemInfoSource = readFileSync(new URL("../../../web/src/components/settings/SystemInfoPanel.tsx", import.meta.url), "utf8");
@@ -18,21 +18,23 @@ describe("desktop update flow", () => {
expect(systemInfoSource).toContain('t("systemInfo.desktopDownloadLatest")');
});
- test("downloads updates in the background and relaunches after installation", () => {
- expect(mainSource).toContain("autoUpdater.autoDownload = true");
- expect(windowsUpdateSource).toContain("void download(reason)");
- expect(mainSource).toContain("autoUpdater.autoRunAppAfterInstall = true");
- expect(mainSource).toContain('autoUpdater.quitAndInstall(process.platform === "win32", true)');
- expect(mainSource).toContain("result?.downloadPromise");
- expect(mainSource).toContain("windowsUpdateController.download(reason)");
+ test("routes every desktop platform through one update controller", () => {
+ expect(mainSource).toContain("desktopUpdateController = createDesktopUpdateController({");
+ expect(mainSource).toContain("platform: process.platform");
+ expect(mainSource).not.toContain("windowsUpdateController");
+ expect(mainSource).not.toContain('updateState === "downloaded") {');
+ expect(mainSource).toContain("desktopUpdateController.check(reason)");
+ expect(mainSource).toContain("desktopUpdateController?.install(expectedVersion)");
+ expect(mainSource).toContain("desktopUpdateController?.download(reason)");
+ expect(controllerSource).toContain("void download(reason)");
+ expect(controllerSource).toContain("updater.autoRunAppAfterInstall = true");
});
- test("routes Windows through the serialized, signed update controller", () => {
- expect(mainSource).toContain('if (process.platform === "win32") {\n windowsUpdateController = createWindowsUpdateController({');
+ test("provides Windows trust gates and macOS native installation to the shared controller", () => {
expect(mainSource).toContain("fetchTrustedWindowsUpdate({ ...options, fetchImpl: net.fetch })");
expect(mainSource).toContain("verifyWindowsPackage: verifyDownloadedWindowsUpdate");
- expect(mainSource).toContain("windowsUpdateController.check(reason)");
- expect(mainSource).toContain("windowsUpdateController.install(expectedVersion)");
+ expect(mainSource).toContain("nativeUpdater: nativeAutoUpdater");
+ expect(mainSource).toContain("desktopUpdateController?.handleBeforeQuit(event)");
expect(mainSource).toContain('downloadTrustedDesktopUpdate("manual-download")');
});
@@ -62,8 +64,7 @@ describe("desktop update flow", () => {
expect(mainSource).toContain('checkForDesktopUpdate("interval", { force: true })');
expect(mainSource).toContain('powerMonitor.on("resume"');
expect(mainSource).toContain('checkForDesktopUpdate("activate")');
- expect(mainSource).toContain("if (updateCheckInFlight) {");
- expect(mainSource).toContain("return throwOnError ? updateCheckInFlight : updateCheckInFlight.catch(() => null)");
+ expect(controllerSource).toContain("if (checkInFlight) return checkInFlight;");
expect(mainSource).toContain("clearInterval(updateCheckTimer)");
});
@@ -75,7 +76,7 @@ describe("desktop update flow", () => {
test("pushes update status and shows a native restart prompt after download", () => {
expect(mainSource).toContain('mainWindow.webContents.send("desktop:update-status-changed"');
- expect(mainSource).toContain("promptForDownloadedUpdate(downloadedUpdateVersion)");
+ expect(mainSource).toContain("promptForDownloadedUpdate(version)");
expect(mainSource).toContain("title: copy.updateReadyTitle");
expect(preloadSource).toContain('ipcRenderer.on("desktop:update-status-changed"');
expect(noticeSource).toContain("bridge.onUpdateStatus");
@@ -89,7 +90,7 @@ describe("desktop update flow", () => {
expect(mainSource).not.toContain("holdAutoRestartUpdate");
expect(mainSource).not.toContain("heldUpdateVersion");
expect(mainSource).not.toContain("update.held-for-instance");
- expect(mainSource).toContain("promptForDownloadedUpdate(downloadedUpdateVersion)");
+ expect(mainSource).toContain("promptForDownloadedUpdate(version)");
expect(systemInfoSource).toContain("clientAheadOfInstanceByPlatform");
expect(systemInfoSource).toContain("isClientAheadOfInstance");
});
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index fbf719bf..5eb6baea 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -1,4 +1,4 @@
-import { app, Notification, BrowserWindow, Menu, Tray, globalShortcut, nativeImage, ipcMain, session, net, protocol, shell, dialog, safeStorage, clipboard, ClipboardItem, powerMonitor, desktopCapturer, screen, utilityProcess } from "electron";
+import { app, autoUpdater as nativeAutoUpdater, Notification, BrowserWindow, Menu, Tray, globalShortcut, nativeImage, ipcMain, session, net, protocol, shell, dialog, safeStorage, clipboard, ClipboardItem, powerMonitor, desktopCapturer, screen, utilityProcess } from "electron";
import { createReadStream, existsSync } from "node:fs";
import { appendFile, mkdir, open, readdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
import { basename, join } from "node:path";
@@ -60,7 +60,7 @@ import {
verifyDownloadedWindowsUpdate,
} from "./windows-update-trust.mjs";
import electronUpdater from "electron-updater";
-import { createWindowsUpdateController } from "./windows-update-controller.mjs";
+import { createDesktopUpdateController } from "./desktop-update-controller.mjs";
import { createUpdateDiagnostic } from "./update-diagnostics.mjs";
import { createUpdateNetworkDiagnostics } from "./update-network-diagnostics.mjs";
import { normalizeUpdateProgress } from "./update-progress.mjs";
@@ -155,9 +155,7 @@ let isQuitting = false;
let updateState = "idle";
let updateError = null;
let updateProgress = null;
-let updateCheckInFlight = null;
-let updateDownloadInFlight = null;
-let windowsUpdateController = null;
+let desktopUpdateController = null;
let updateCheckTimer = null;
let lastUpdateCheckAt = 0;
let downloadedUpdateVersion = null;
@@ -1249,38 +1247,11 @@ const publishDesktopUpdateStatus = () => {
mainWindow.webContents.send("desktop:update-status-changed", desktopUpdateStatus());
};
-const installDownloadedUpdate = (expectedVersion) => {
- if (windowsUpdateController) return windowsUpdateController.install(expectedVersion);
- if (updateState !== "downloaded") return { started: false };
- // The normal window close handler hides the app. Mark this as a real quit
- // before electron-updater closes windows so installation can proceed.
- isQuitting = true;
- // Keep Windows updates silent and reuse the registered installation directory.
- autoUpdater.quitAndInstall(process.platform === "win32", true);
- return { started: true };
-};
-
-const trackDesktopUpdateDownload = (downloadPromise, reason) => {
- updateDownloadInFlight = Promise.resolve(downloadPromise)
- .catch(async (error) => {
- updateState = "idle";
- updateProgress = null;
- downloadedUpdateVersion = null;
- refreshTrayMenu();
- recordUpdateError(error, "download");
- publishDesktopUpdateStatus();
- await writeDiagnostic("update.download-failed", { reason, message: error.message });
- })
- .finally(() => { updateDownloadInFlight = null; updateNetworkDiagnostics.stop(); });
- return updateDownloadInFlight;
-};
+const installDownloadedUpdate = (expectedVersion) =>
+ desktopUpdateController?.install(expectedVersion) ?? Promise.resolve({ started: false });
-const downloadTrustedDesktopUpdate = (reason) => {
- if (windowsUpdateController) return windowsUpdateController.download(reason);
- if (updateDownloadInFlight) return updateDownloadInFlight;
- updateNetworkDiagnostics.setStage("download");
- return trackDesktopUpdateDownload(autoUpdater.downloadUpdate(), reason);
-};
+const downloadTrustedDesktopUpdate = (reason) =>
+ desktopUpdateController?.download(reason) ?? Promise.resolve();
const promptForDownloadedUpdate = async (version) => {
const promptKey = version || "unknown";
@@ -1299,7 +1270,6 @@ const promptForDownloadedUpdate = async (version) => {
noLink: true,
});
if (result.response === 0) {
- if (!windowsUpdateController) void writeDiagnostic("update.install-confirmed", { version });
void installDownloadedUpdate(version);
} else {
void writeDiagnostic("update.install-deferred", { version });
@@ -1307,49 +1277,10 @@ const promptForDownloadedUpdate = async (version) => {
};
const checkForDesktopUpdate = (reason, { force = false, throwOnError = false } = {}) => {
- if (windowsUpdateController) {
- if (!force && Date.now() - lastUpdateCheckAt < updateCheckFocusThrottleMs) return Promise.resolve(null);
- const result = windowsUpdateController.check(reason);
- return throwOnError ? result : result.catch(() => null);
- }
- if (!app.isPackaged || process.env.EDGE_EVER_DISABLE_AUTO_UPDATE === "1" || updateState === "downloaded") {
- return Promise.resolve(null);
- }
- if (updateCheckInFlight) {
- return throwOnError ? updateCheckInFlight : updateCheckInFlight.catch(() => null);
- }
- if (updateDownloadInFlight) return Promise.resolve(null);
- const now = Date.now();
- if (!force && now - lastUpdateCheckAt < updateCheckFocusThrottleMs) return Promise.resolve(null);
- lastUpdateCheckAt = now;
- updateError = null;
- updateNetworkDiagnostics.beginCheck();
- publishDesktopUpdateStatus();
- const diagnosticStage = "check";
- void writeDiagnostic("update.check-started", { reason });
- updateCheckInFlight = autoUpdater.checkForUpdates()
- .then(async (result) => {
- if (result?.downloadPromise) {
- updateNetworkDiagnostics.setStage("download");
- trackDesktopUpdateDownload(result.downloadPromise, reason);
- }
- return result;
- })
- .catch(async (error) => {
- updateState = "idle";
- updateProgress = null;
- downloadedUpdateVersion = null;
- refreshTrayMenu();
- recordUpdateError(error, diagnosticStage);
- publishDesktopUpdateStatus();
- await writeDiagnostic("update.check-failed", { reason, message: error.message });
- throw error;
- })
- .finally(() => {
- updateCheckInFlight = null;
- if (!updateDownloadInFlight) updateNetworkDiagnostics.stop();
- });
- return throwOnError ? updateCheckInFlight : updateCheckInFlight.catch(() => null);
+ if (!desktopUpdateController) return Promise.resolve(null);
+ if (!force && Date.now() - lastUpdateCheckAt < updateCheckFocusThrottleMs) return Promise.resolve(null);
+ const result = desktopUpdateController.check(reason);
+ return throwOnError ? result : result.catch(() => null);
};
const configureAutoUpdater = () => {
@@ -1378,104 +1309,53 @@ const configureAutoUpdater = () => {
appImage: process.env.APPIMAGE || null,
});
}
- if (process.platform === "win32") {
- windowsUpdateController = createWindowsUpdateController({
- updater: autoUpdater,
- fetchWindowsMetadata: (options) => fetchTrustedWindowsUpdate({ ...options, fetchImpl: net.fetch }),
- verifyWindowsPackage: verifyDownloadedWindowsUpdate,
- onStatus: (status) => {
- updateState = status.state;
- downloadedUpdateVersion = status.version;
- updateProgress = status.progress ? normalizeUpdateProgress(status.progress) : null;
- updateError = null;
- refreshTrayMenu();
- publishDesktopUpdateStatus();
- },
- onError: (error, stage) => {
- isQuitting = false;
- recordUpdateError(error, stage);
- publishDesktopUpdateStatus();
- },
- onCheckStarted: (reason) => {
- lastUpdateCheckAt = Date.now();
- updateError = null;
- updateNetworkDiagnostics.beginCheck();
- publishDesktopUpdateStatus();
- void writeDiagnostic("update.check-started", { reason });
- },
- onStage: (stage) => updateNetworkDiagnostics.setStage(stage),
- onSettled: () => updateNetworkDiagnostics.stop(),
- log: (event, details) => { void writeDiagnostic(event, details); },
- beforeInstall: () => { isQuitting = true; },
- onDownloaded: (version) => {
- void promptForDownloadedUpdate(version).catch((error) => {
- promptedUpdateVersion = null;
- void writeDiagnostic("update.prompt-failed", { message: error.message });
- });
- },
- });
- } else {
- autoUpdater.autoDownload = true;
- autoUpdater.autoInstallOnAppQuit = true;
- autoUpdater.autoRunAppAfterInstall = true;
- autoUpdater.on("update-available", (info) => {
- updateState = "available";
- updateProgress = null;
- downloadedUpdateVersion = info?.version || null;
+ desktopUpdateController = createDesktopUpdateController({
+ updater: autoUpdater,
+ platform: process.platform,
+ nativeUpdater: nativeAutoUpdater,
+ quitApplication: () => app.quit(),
+ fetchWindowsMetadata: (options) => fetchTrustedWindowsUpdate({ ...options, fetchImpl: net.fetch }),
+ verifyWindowsPackage: verifyDownloadedWindowsUpdate,
+ onStatus: (status) => {
+ updateState = status.state;
+ downloadedUpdateVersion = status.version;
+ updateProgress = status.progress ? normalizeUpdateProgress(status.progress) : null;
+ updateError = null;
refreshTrayMenu();
publishDesktopUpdateStatus();
- void writeDiagnostic("update.available", { version: info?.version });
- });
- autoUpdater.on("update-not-available", () => {
- updateState = "idle";
- updateProgress = null;
- downloadedUpdateVersion = null;
- refreshTrayMenu();
+ },
+ onError: (error, stage) => {
+ isQuitting = false;
+ recordUpdateError(error, stage);
publishDesktopUpdateStatus();
- const diagnosticWritten = writeDiagnostic("update.not-available");
+ },
+ onCheckStarted: (reason) => {
+ lastUpdateCheckAt = Date.now();
+ updateError = null;
+ updateNetworkDiagnostics.beginCheck();
+ publishDesktopUpdateStatus();
+ void writeDiagnostic("update.check-started", { reason });
+ },
+ onStage: (stage) => updateNetworkDiagnostics.setStage(stage),
+ onSettled: () => updateNetworkDiagnostics.stop(),
+ log: (event, details) => {
+ const written = writeDiagnostic(event, details);
+ if (linuxUpdateTestMode && event === "update.not-available") {
+ void written.finally(() => setTimeout(() => app.quit(), 100));
+ }
+ },
+ beforeInstall: () => { isQuitting = true; },
+ onDownloaded: (version) => {
if (linuxUpdateTestMode) {
- void diagnosticWritten.finally(() => setTimeout(() => app.quit(), 100));
+ void installDownloadedUpdate(version);
+ return;
}
- });
- autoUpdater.on("download-progress", (progress) => {
- updateProgress = normalizeUpdateProgress(progress);
- publishDesktopUpdateStatus();
- void writeDiagnostic("update.download-progress", { percent: progress.percent });
- });
- autoUpdater.on("update-downloaded", (info) => {
- void (async () => {
- updateState = "downloaded";
- updateProgress = null;
- updateError = null;
- downloadedUpdateVersion = info?.version || downloadedUpdateVersion;
- refreshTrayMenu();
- publishDesktopUpdateStatus();
- await writeDiagnostic("update.downloaded", { version: downloadedUpdateVersion });
- if (linuxUpdateTestMode) {
- installDownloadedUpdate();
- return;
- }
- await promptForDownloadedUpdate(downloadedUpdateVersion).catch((error) => {
- promptedUpdateVersion = null;
- void writeDiagnostic("update.prompt-failed", { message: error.message });
- });
- })().catch(async (error) => {
- await writeDiagnostic("update.download-handler-failed", { message: error.message });
+ void promptForDownloadedUpdate(version).catch((error) => {
+ promptedUpdateVersion = null;
+ void writeDiagnostic("update.prompt-failed", { message: error.message });
});
- });
- autoUpdater.on("error", (error) => {
- isQuitting = false;
- if (updateState !== "downloaded") {
- updateState = "idle";
- updateProgress = null;
- downloadedUpdateVersion = null;
- }
- refreshTrayMenu();
- recordUpdateError(error, updateDownloadInFlight ? "download" : "check");
- publishDesktopUpdateStatus();
- void writeDiagnostic("update.error", { message: error.message });
- });
- }
+ },
+ });
void checkForDesktopUpdate("startup", { force: true });
updateCheckTimer = setInterval(() => {
void checkForDesktopUpdate("interval", { force: true });
@@ -2589,6 +2469,7 @@ app.on("window-all-closed", () => {
});
app.on("before-quit", (event) => {
+ if (desktopUpdateController?.handleBeforeQuit(event)) return;
if (shutdownCleanupStarted) return;
event.preventDefault();
shutdownCleanupStarted = true;
diff --git a/apps/desktop/src/main/mac-update-install.mjs b/apps/desktop/src/main/mac-update-install.mjs
new file mode 100644
index 00000000..649064fd
--- /dev/null
+++ b/apps/desktop/src/main/mac-update-install.mjs
@@ -0,0 +1,28 @@
+// Keep Squirrel out of background downloads. Its staged update can otherwise
+// survive a later ZIP download and be installed instead of the selected target.
+// Only prepare the current loopback feed once the controller has frozen it.
+export const prepareMacUpdate = (nativeUpdater, { timeoutMs = 120_000 } = {}) => new Promise((resolve, reject) => {
+ const feed = nativeUpdater.getFeedURL();
+ let timer;
+ const cleanup = () => {
+ clearTimeout(timer);
+ nativeUpdater.removeListener("update-downloaded", downloaded);
+ nativeUpdater.removeListener("error", failed);
+ nativeUpdater.removeListener("update-not-available", unavailable);
+ };
+ const failed = (error) => { cleanup(); reject(error); };
+ const unavailable = () => failed(new Error("Native macOS update is not available for the selected package"));
+ const downloaded = () => {
+ cleanup();
+ if (nativeUpdater.getFeedURL() !== feed) {
+ reject(new Error("Native macOS update feed changed during preparation"));
+ } else {
+ resolve();
+ }
+ };
+ nativeUpdater.once("update-downloaded", downloaded);
+ nativeUpdater.once("error", failed);
+ nativeUpdater.once("update-not-available", unavailable);
+ timer = setTimeout(() => failed(new Error("Native macOS update preparation timed out")), timeoutMs);
+ try { nativeUpdater.checkForUpdates(); } catch (error) { failed(error); }
+});
diff --git a/apps/desktop/src/main/windows-update-controller.test.mjs b/apps/desktop/src/main/windows-update-controller.test.mjs
index e3ed8512..293d50cb 100644
--- a/apps/desktop/src/main/windows-update-controller.test.mjs
+++ b/apps/desktop/src/main/windows-update-controller.test.mjs
@@ -4,7 +4,7 @@ import { mkdtemp, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
-import { createWindowsUpdateController } from "./windows-update-controller.mjs";
+import { createDesktopUpdateController } from "./desktop-update-controller.mjs";
import { WINDOWS_UPDATE_KEY_ID, verifyWindowsUpdateMetadata, verifyDownloadedWindowsUpdate } from "./windows-update-trust.mjs";
// Exercise the installed electron-updater's real check, download promise and
@@ -86,8 +86,8 @@ const harness = async () => {
return true;
};
updater.quitAndInstall = (silent, forceRun) => updater.install(silent, forceRun);
- const controller = createWindowsUpdateController({
- updater,
+ const controller = createDesktopUpdateController({
+ updater, platform: "win32",
fetchWindowsMetadata: async ({ version, updateInfo }) => {
if (h.metadataGate) await h.metadataGate.promise;
if (h.metadataError) throw h.metadataError;
@@ -135,6 +135,16 @@ describe("desktop update target lifecycle (#776)", () => {
expect(h.installs.map((entry) => entry.version)).toEqual(["2.18.0"]);
});
+ test("normal Windows quit refreshes the installer and does not relaunch", async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = "2.19.0";
+ expect(h.controller.handleBeforeQuit({ preventDefault() {} })).toBe(true);
+ await h.controller.install();
+ expect(h.installs).toEqual([{ version: "2.19.0", path: h.releases.get("2.19.0").path, silent: true, forceRun: false }]);
+ expect(h.notices).toEqual(["2.17.0"]);
+ });
+
test("an unchanged release does not download or prompt again", async () => {
const h = await harness();
await h.ready();