Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(desktop): install the newest release, not the first one downloaded

Samrat Talukdara1364434cfea
diff --git a/apps/app/src/react-app/domains/settings/state/electron-updater-state.test.ts b/apps/app/src/react-app/domains/settings/state/electron-updater-state.test.ts
index 57c1d145..5dfc3973 100644
--- a/apps/app/src/react-app/domains/settings/state/electron-updater-state.test.ts
+++ b/apps/app/src/react-app/domains/settings/state/electron-updater-state.test.ts
@@ -9,6 +9,7 @@ declare const expect: (value: unknown) => {
import {
ELECTRON_UPDATER_UNSUPPORTED_REASON,
describeError,
+ keepsReadyUpdate,
resolveCheckedUpdateState,
shouldScheduleElectronUpdateAutoCheck,
stripRemoteMethodErrorPrefix,
@@ -70,3 +71,22 @@ describe("electron updater availability state", () => {
expect(resolveCheckedUpdateState({ available: false, allowed: false })).toBe("idle");
});
});
+
+describe("electron updater staged update", () => {
+ test("a newer published release replaces the staged one", () => {
+ expect(keepsReadyUpdate({ readyVersion: "2.2.1", checkFailed: false, available: true, latestVersion: "2.2.3" })).toBe(false);
+ });
+
+ test("the same release keeps the staged update ready", () => {
+ expect(keepsReadyUpdate({ readyVersion: "2.2.3", checkFailed: false, available: true, latestVersion: "2.2.3" })).toBe(true);
+ });
+
+ test("a failed re-check keeps the staged update ready", () => {
+ expect(keepsReadyUpdate({ readyVersion: "2.2.1", checkFailed: true, available: false, latestVersion: null })).toBe(true);
+ });
+
+ test("a pulled release clears the staged update", () => {
+ expect(keepsReadyUpdate({ readyVersion: "2.2.1", checkFailed: false, available: false, latestVersion: "2.2.0" })).toBe(false);
+ expect(keepsReadyUpdate({ readyVersion: undefined, checkFailed: true, available: false, latestVersion: null })).toBe(false);
+ });
+});
diff --git a/apps/app/src/react-app/domains/settings/state/electron-updater-state.ts b/apps/app/src/react-app/domains/settings/state/electron-updater-state.ts
index 9ec10c83..5224049a 100644
--- a/apps/app/src/react-app/domains/settings/state/electron-updater-state.ts
+++ b/apps/app/src/react-app/domains/settings/state/electron-updater-state.ts
@@ -91,6 +91,22 @@ export function resolveCheckedUpdateState(input: {
return input.allowed ? "available" : "blocked";
}
+/**
+ * A staged update stays "ready" while the feed still offers that version. A
+ * newer release (or a failed check) must not be hidden behind it: the newer
+ * version replaces the staged one, a failed check keeps it.
+ */
+export function keepsReadyUpdate(input: {
+ readyVersion: string | undefined;
+ checkFailed: boolean;
+ available: boolean;
+ latestVersion: string | null | undefined;
+}): boolean {
+ if (!input.readyVersion) return false;
+ if (input.checkFailed) return true;
+ return input.available && input.latestVersion === input.readyVersion;
+}
+
type ElectronUpdaterEnvAction =
| { type: "app-version"; appVersion: string | null }
| { type: "capabilities"; installMode?: UpdaterInstallMode | null; alphaChannelSupported?: boolean | null }
@@ -435,7 +451,18 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)
return;
}
- setUpdateStatus({ state: "checking" });
+ // Keep a staged update on screen while the feed is re-checked; the check
+ // replaces it only when a newer release is published.
+ const current = updateStatusRef.current;
+ const readyVersion = current?.state === "ready" ? current.version : undefined;
+ const keepReady = (checkFailed: boolean, result?: { available: boolean; latestVersion?: string | null }) =>
+ keepsReadyUpdate({
+ readyVersion,
+ checkFailed,
+ available: result?.available ?? false,
+ latestVersion: result?.latestVersion,
+ });
+ if (!readyVersion) setUpdateStatus({ state: "checking" });
try {
let targetVersion: string | undefined;
const releaseChannelResolution = await resolvePolicyReleaseChannel(
@@ -529,6 +556,7 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)
});
return;
}
+ if (keepReady(Boolean(result.reason), result)) return;
if (result.reason) {
setUpdateStatus({
state: "error",
@@ -552,6 +580,12 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)
: await isUpdateAllowed(result.latestVersion, latestDesktopConfig)
: result.available;
if (!isCurrentRequest()) return;
+ if (readyVersion && result.available && !availableAllowed && checkedReleaseChannel === "stable") {
+ // Policy blocks the newer release: pin the shell to the staged version
+ // so installing it does not jump past what the organization allows.
+ await bridge.check(checkedReleaseChannel, readyVersion);
+ return;
+ }
const checkedUpdateState = resolveCheckedUpdateState({
available: result.available,
allowed: Boolean(availableAllowed),
@@ -580,6 +614,7 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)
}
} catch (error) {
if (!isCurrentRequest()) return;
+ if (keepReady(true)) return;
setUpdateStatus({
state: "error",
message: describeError(error),
@@ -591,7 +626,7 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)
const checkForUpdates = useCallback(
(channelOverride?: ReleaseChannel) => {
const state = updateStatusRef.current?.state;
- if (!channelOverride && (state === "downloading" || state === "ready")) return Promise.resolve();
+ if (!channelOverride && state === "downloading") return Promise.resolve();
return runCheckForUpdates(channelOverride, true);
},
[runCheckForUpdates],
@@ -603,7 +638,8 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)
const interval = 15 * 60 * 1000;
const check = () => {
const state = updateStatusRef.current?.state;
- if (autoCheckInFlightRef.current || state === "checking" || state === "downloading" || state === "ready") return;
+ // A "ready" update keeps being re-checked so a newer release replaces it.
+ if (autoCheckInFlightRef.current || state === "checking" || state === "downloading") return;
if (autoCheckKeyRef.current === key && Date.now() - lastAutoCheckAtRef.current < interval) return;
autoCheckKeyRef.current = key;
lastAutoCheckAtRef.current = Date.now();
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 6f72874b..7865c6b2 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -2846,7 +2846,7 @@ const browserLoginSync = createBrowserLoginSync({
browserLoginSync.registerIpc(ipcMain, { evalSeam: browserLoginEvalSeam });
registerMigrationIpc({ app, ipcMain });
-const { ensureAutoUpdater } = registerUpdaterIpc({
+const { ensureAutoUpdater, prepareInstallOnQuit } = registerUpdaterIpc({
app,
ipcMain,
getMainWindow: () => mainWindow,
@@ -2885,6 +2885,10 @@ or use: pnpm dev:worktree`);
desktopAutomationRunner.stop();
browserLoginSync.shutdown();
runDetachedTask("stop services before quit", async () => {
+ // Re-check the update feed while services stop, so a download staged
+ // before newer releases shipped is replaced by the newest one instead
+ // of installing on quit.
+ const updateInstall = prepareInstallOnQuit();
try {
await Promise.all([
disposeRuntimeBeforeQuit(),
@@ -2893,7 +2897,9 @@ or use: pnpm dev:worktree`);
]);
} finally {
scheduleBlankSlateProfileCleanup();
- app.quit();
+ const installUpdateAndQuit = await updateInstall;
+ if (installUpdateAndQuit) installUpdateAndQuit();
+ else app.quit();
}
});
});
diff --git a/apps/desktop/electron/updater.mjs b/apps/desktop/electron/updater.mjs
index c8c179c4..1dd841fa 100644
--- a/apps/desktop/electron/updater.mjs
+++ b/apps/desktop/electron/updater.mjs
@@ -59,14 +59,37 @@ export const STABLE_UPDATER_FEED_URL = "https://github.com/omnirush-ai/omnirush-
* can enable the Alpha channel. Without it a persisted or requested "alpha"
* normalizes back to stable instead of probing a feed that does not exist.
*/
-export function updaterFeedOptions({ manifestChannel = "latest", alphaFeedUrl = null } = {}) {
+export function updaterFeedOptions({
+ manifestChannel = "latest",
+ alphaFeedUrl = null,
+ devFeedUrl = null,
+} = {}) {
const normalizedAlphaFeedUrl = typeof alphaFeedUrl === "string" ? alphaFeedUrl.trim().replace(/\/+$/, "") : "";
return Object.freeze({
manifestChannel,
alphaFeedUrl: manifestChannel === "latest" && normalizedAlphaFeedUrl ? normalizedAlphaFeedUrl : null,
+ stableFeedUrl: loopbackDevFeedUrl(devFeedUrl) ?? STABLE_UPDATER_FEED_URL,
});
}
+/**
+ * OMNIRUSH_UPDATER_DEV_FEED_URL lets a local update rig serve latest*.yml to a
+ * packaged build. Only a loopback http(s) URL is honored, so the variable can
+ * never point a real install at a remote feed.
+ */
+export function loopbackDevFeedUrl(value) {
+ if (typeof value !== "string" || !value.trim()) return null;
+ let url;
+ try {
+ url = new URL(value.trim());
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
+ if (!["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)) return null;
+ return url.toString().replace(/\/+$/, "");
+}
+
function alphaChannelSupported(feedOptions) {
return feedOptions.alphaFeedUrl !== null;
}
@@ -105,7 +128,7 @@ async function writeElectronUpdaterChannel(app, channel, feedOptions) {
export function electronUpdaterFeedUrl(channel, feedOptions = updaterFeedOptions()) {
return normalizeElectronUpdaterChannel(channel, feedOptions) === "alpha"
? feedOptions.alphaFeedUrl
- : STABLE_UPDATER_FEED_URL;
+ : feedOptions.stableFeedUrl;
}
function normalizeStableTargetVersion(value) {
@@ -258,6 +281,16 @@ async function applyElectronUpdaterFeed(
return state;
}
+function withTimeout(promise, timeoutMs, label) {
+ let timer;
+ return Promise.race([
+ promise,
+ new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs} ms.`)), timeoutMs);
+ }),
+ ]).finally(() => clearTimeout(timer));
+}
+
function runDefaults(args) {
return new Promise((resolve) => {
execFile("/usr/bin/defaults", args, (error) => {
@@ -436,8 +469,18 @@ export function registerUpdaterIpc({
execPath = process.execPath,
isDeveloperIdSigned = () => detectDeveloperIdSignature(execPath),
quitDelayMs = 1500,
+ // Bounds on the feed re-check that runs right before an install, and on the
+ // whole quit-time refresh (check plus any newer download).
+ installCheckTimeoutMs = 15_000,
+ quitUpdateTimeoutMs = 120_000,
+ // Quits anyway if the updater never quits the app after a quit-time install.
+ quitInstallFallbackMs = 30_000,
}) {
- const feedOptions = updaterFeedOptions({ manifestChannel, alphaFeedUrl });
+ const feedOptions = updaterFeedOptions({
+ manifestChannel,
+ alphaFeedUrl,
+ devFeedUrl: env.OMNIRUSH_UPDATER_DEV_FEED_URL,
+ });
let autoUpdaterInstance = null;
let autoUpdaterLoadPromise = null;
let installModePromise = null;
@@ -447,6 +490,12 @@ export function registerUpdaterIpc({
let checkedInstallerArtifact = null;
let downloadedInstallerPath = null;
let updateDownloaded = false;
+ // The version and channel of the staged download. The feed can move past it
+ // before it installs, so every install re-checks against the feed first.
+ let downloadedUpdateVersion = null;
+ let downloadedUpdateChannel = null;
+ let installTriggered = false;
+ let quitInstallInProgress = false;
let recoveryReleases = [];
const recoveryWitness = { installRequests: [], openedArtifactUrls: [], quitRequested: false };
let updaterOperationQueue = Promise.resolve();
@@ -492,6 +541,13 @@ export function registerUpdaterIpc({
};
}
+ function clearDownloadedUpdate() {
+ updateDownloaded = false;
+ downloadedInstallerPath = null;
+ downloadedUpdateVersion = null;
+ downloadedUpdateChannel = null;
+ }
+
function clearCheckedUpdate() {
checkedUpdateVersion = null;
checkedUpdateTargetVersion = null;
@@ -520,7 +576,12 @@ export function registerUpdaterIpc({
autoUpdaterInstance = mod.autoUpdater ?? mod.default?.autoUpdater ?? null;
if (autoUpdaterInstance) {
autoUpdaterInstance.autoDownload = false;
- autoUpdaterInstance.autoInstallOnAppQuit = true;
+ // Nothing installs behind the updater's back: electron-updater's own
+ // quit hook (and Squirrel.Mac, which stages at download time when
+ // this is true) would install whatever was downloaded first, even
+ // after a newer release was published. Quit and restart both go
+ // through ensureNewestDownloaded(), which re-checks the feed first.
+ autoUpdaterInstance.autoInstallOnAppQuit = false;
// Differential (blockmap) downloads reconstruct the update zip from the
// installed app + a diff. On macOS that reconstructed bundle is what
// feeds Squirrel's fragile move-based install, and is a common trigger
@@ -535,9 +596,12 @@ export function registerUpdaterIpc({
// A later transient check failure does not delete the downloaded
// update; quitAndInstall reports a descriptive failure if it is gone.
console.warn("[updater] error", err);
+ // A failed quit-time install must not leave the app running.
+ if (quitInstallInProgress) app.quit();
});
- autoUpdaterInstance.on("update-downloaded", () => {
+ autoUpdaterInstance.on("update-downloaded", (info) => {
updateDownloaded = true;
+ if (typeof info?.version === "string") downloadedUpdateVersion = info.version;
});
// Forward download progress to the renderer so the UI can show
// incremental bytes instead of staying stuck at 0.
@@ -804,6 +868,7 @@ export function registerUpdaterIpc({
}
updater.autoInstallOnAppQuit = true;
await updater.downloadUpdate();
+ installTriggered = true;
updater.quitAndInstall(false, true);
return { ok: true, action: "install" };
} catch (error) {
@@ -851,8 +916,7 @@ export function registerUpdaterIpc({
ipcMain.handle("omnirush:updater:setChannel", async (_event, rawChannel) => queueUpdaterOperation(async () => {
const channel = await writeElectronUpdaterChannel(app, rawChannel, feedOptions);
clearCheckedUpdate();
- downloadedInstallerPath = null;
- updateDownloaded = false;
+ clearDownloadedUpdate();
const installMode = await resolveInstallMode();
const updater = await ensureAutoUpdater();
if (updater) {
@@ -893,10 +957,7 @@ export function registerUpdaterIpc({
throw new Error(`Target update manifest did not resolve to v${targetVersion}.`);
}
const available = recordCheckedUpdate(info, channelState, targetVersion, installMode);
- if (!available) {
- updateDownloaded = false;
- downloadedInstallerPath = null;
- }
+ if (!available) clearDownloadedUpdate();
return {
available,
currentVersion,
@@ -947,36 +1008,141 @@ export function registerUpdaterIpc({
await cacheCurrentHealthyRelease().catch((error) => {
console.warn("[updater] could not cache the current healthy installer", error);
});
- if (installMode === "manual-dmg") {
- // Squirrel.Mac would refuse the zip electron-updater downloads for an
- // ad-hoc signed app, so fetch the DMG the same manifest lists instead.
- // The download is plain HTTPS plus the manifest's sha512.
- if (!checkedInstallerArtifact || checkedInstallerArtifact.version !== checkedUpdateVersion) {
- throw new Error("The release manifest does not list a macOS installer for this update.");
- }
- downloadedInstallerPath = await downloadManualInstaller(checkedInstallerArtifact);
- updateDownloaded = true;
- return { ok: true, mode: "manual-dmg" };
+ await downloadCheckedUpdate(updater, installMode);
+ return { ok: true, mode: installMode };
+ } catch (error) {
+ clearDownloadedUpdate();
+ return { ok: false, reason: String(error?.message ?? error) };
+ }
+ }));
+
+ /** Downloads the version the last successful check recorded. */
+ async function downloadCheckedUpdate(updater, installMode) {
+ const version = checkedUpdateVersion;
+ if (installMode === "manual-dmg") {
+ // Squirrel.Mac would refuse the zip electron-updater downloads for an
+ // ad-hoc signed app, so fetch the DMG the same manifest lists instead.
+ // The download is plain HTTPS plus the manifest's sha512.
+ if (!checkedInstallerArtifact || checkedInstallerArtifact.version !== version) {
+ throw new Error("The release manifest does not list a macOS installer for this update.");
}
+ downloadedInstallerPath = await downloadManualInstaller(checkedInstallerArtifact);
+ } else {
// Clear any stuck ShipIt state from a prior aborted install so this
- // download applies cleanly on quit.
+ // download applies cleanly.
await cleanStaleUpdaterState(app, shipItDefaultsDomain);
- updater.autoInstallOnAppQuit = true;
+ preventPendingUpdaterInstall(updater);
await updater.downloadUpdate();
- updateDownloaded = true;
- return { ok: true, mode: "in-place" };
+ }
+ updateDownloaded = true;
+ downloadedUpdateVersion = version;
+ downloadedUpdateChannel = checkedUpdateChannel;
+ }
+
+ /**
+ * Re-reads the feed right before an install. A staged download can be
+ * several releases behind the feed (it was fetched at launch, the app stayed
+ * open while more releases shipped), and installing it would only make the
+ * next launch find the next release. When the feed has moved on, the newest
+ * release is downloaded now so a single restart lands on it.
+ *
+ * Resolves { ok: true } when the staged download is the version to install.
+ * An unreachable feed keeps the staged download: it is the newest release
+ * this app knows of. A newer release that cannot be downloaded never falls
+ * back to the stale one.
+ */
+ async function ensureNewestDownloaded(updater, installMode) {
+ // A Den-selected target is the exact version the organization allows.
+ if (checkedUpdateTargetVersion) return { ok: true };
+ let info;
+ let channelState;
+ try {
+ channelState = {
+ ...(await applyElectronUpdaterFeed(
+ app,
+ updater,
+ null,
+ feedOptions,
+ false,
+ downloadedUpdateChannel ?? undefined,
+ )),
+ installMode,
+ };
+ const result = await withTimeout(updater.checkForUpdates(), installCheckTimeoutMs, "The update check");
+ info = result?.updateInfo ?? null;
} catch (error) {
- updateDownloaded = false;
- downloadedInstallerPath = null;
- return { ok: false, reason: String(error?.message ?? error) };
+ console.warn("[updater] pre-install check failed; installing the staged update", error?.message ?? error);
+ return { ok: true };
}
- }));
+ if (!info?.version || !isVersionNewer(info.version, resolveAppVersion(app))) {
+ // The feed no longer offers an update (the release was pulled).
+ clearCheckedUpdate();
+ clearDownloadedUpdate();
+ return { ok: false, reason: "update-not-downloaded" };
+ }
+ if (downloadedUpdateVersion && compareVersions(info.version, downloadedUpdateVersion) === 0) {
+ return { ok: true };
+ }
+ console.info(`[updater] feed moved from v${downloadedUpdateVersion ?? "?"} to v${info.version}; downloading it before install`);
+ recordCheckedUpdate(info, channelState, null, installMode);
+ try {
+ await downloadCheckedUpdate(updater, installMode);
+ return { ok: true };
+ } catch (error) {
+ clearDownloadedUpdate();
+ return {
+ ok: false,
+ reason: `Version ${info.version} is available but could not be downloaded: ${String(error?.message ?? error)}`,
+ };
+ }
+ }
+
+ /**
+ * Called from the app's before-quit teardown. Re-checks the feed while
+ * services stop and resolves to a function that installs the newest release
+ * and quits, or to null when nothing should install (no staged download, a
+ * restart already installed it, or a newer release could not be fetched in
+ * time: the stale download is then skipped and the next launch updates).
+ * Never rejects.
+ */
+ async function prepareInstallOnQuit() {
+ try {
+ const updater = autoUpdaterInstance;
+ if (!updater || !updateDownloaded || installTriggered) return null;
+ const installMode = await resolveInstallMode();
+ if (installMode !== "in-place") return null;
+ const newest = await withTimeout(
+ queueUpdaterOperation(() => ensureNewestDownloaded(updater, installMode)),
+ quitUpdateTimeoutMs,
+ "The quit-time update refresh",
+ );
+ if (!newest.ok || !updateDownloaded || installTriggered) return null;
+ return () => {
+ installTriggered = true;
+ quitInstallInProgress = true;
+ // Quit means quit: install silently without relaunching.
+ updater.autoRunAppAfterInstall = false;
+ setTimeout(() => app.quit(), quitInstallFallbackMs);
+ try {
+ updater.quitAndInstall(true, false);
+ } catch (error) {
+ console.warn("[updater] install on quit failed", error?.message ?? error);
+ app.quit();
+ }
+ };
+ } catch (error) {
+ console.warn("[updater] could not prepare the update for quit", error?.message ?? error);
+ return null;
+ }
+ }
ipcMain.handle("omnirush:updater:installAndRestart", async () => queueUpdaterOperation(async () => {
if (!updateDownloaded) return { ok: false, reason: "update-not-downloaded" };
const updater = await ensureAutoUpdater();
if (!updater) return { ok: false, reason: "unavailable" };
const installMode = await resolveInstallMode();
+ const newest = await ensureNewestDownloaded(updater, installMode);
+ if (!newest.ok) return newest;
if (installMode === "manual-dmg") {
if (!downloadedInstallerPath || !checkedInstallerArtifact) {
return { ok: false, reason: "update-not-downloaded" };
@@ -984,8 +1150,7 @@ export function registerUpdaterIpc({
if (!shell?.openPath) return { ok: false, reason: "This package cannot open the downloaded installer." };
try {
if (!(await fileMatchesSha512(downloadedInstallerPath, checkedInstallerArtifact.sha512))) {
- updateDownloaded = false;
- downloadedInstallerPath = null;
+ clearDownloadedUpdate();
return { ok: false, reason: "The downloaded installer could not be verified. Download it again." };
}
const openError = await shell.openPath(downloadedInstallerPath);
@@ -1002,6 +1167,7 @@ export function registerUpdaterIpc({
// Re-assert the in-place-write default right before the swap; the ShipIt
// defaults domain may have been wiped when stale state was cleaned.
await enableSquirrelDirectContentsWrite();
+ installTriggered = true;
updater.quitAndInstall(false, true);
return { ok: true, mode: "in-place" };
} catch (error) {
@@ -1009,5 +1175,5 @@ export function registerUpdaterIpc({
}
}));
- return { ensureAutoUpdater };
+ return { ensureAutoUpdater, prepareInstallOnQuit };
}
diff --git a/apps/desktop/electron/updater.test.mjs b/apps/desktop/electron/updater.test.mjs
index c69c8665..59f8f5a3 100644
--- a/apps/desktop/electron/updater.test.mjs
+++ b/apps/desktop/electron/updater.test.mjs
@@ -8,6 +8,7 @@ import path from "node:path";
import {
detectDeveloperIdSignature,
+ loopbackDevFeedUrl,
developerIdSignatureFromCodesignOutput,
electronUpdaterFeedUrl,
macAppBundlePath,
@@ -87,7 +88,7 @@ async function registerFakeUpdaterIpc({ version, files = undefined, ...options }
getPath: (key) => path.join(tempDir, key),
quit: () => harness.calls.push("quit"),
};
- registerIsolatedUpdaterIpc({
+ const registered = registerIsolatedUpdaterIpc({
app,
ipcMain: { handle: (name, handler) => handlers.set(name, handler) },
getMainWindow: () => ({
@@ -100,7 +101,7 @@ async function registerFakeUpdaterIpc({ version, files = undefined, ...options }
isDeveloperIdSigned: async () => true,
...options,
});
- return { tempDir, handlers, sent, app, ...harness };
+ return { tempDir, handlers, sent, app, ...registered, ...harness };
}
describe("staleUpdaterStatePaths", () => {
@@ -566,7 +567,7 @@ describe("downloaded update lifecycle", () => {
assert.equal(checked.installMode, "in-place");
assert.equal(checked.alphaChannelSupported, false);
assert.deepEqual(await download(), { ok: true, mode: "in-place" });
- assert.equal(updater.autoInstallOnAppQuit, true);
+ assert.equal(updater.autoInstallOnAppQuit, false, "only installNewest may install the staged download");
assert.deepEqual(calls, ["download"], "downloading must not quit the app");
updater.checkForUpdates = async () => {
throw new Error("network flake");
@@ -971,3 +972,187 @@ describe("release channel changes", () => {
}
});
});
+
+// A mutable feed: tests publish releases while an older download is staged.
+async function publishingFeedHarness(options = {}) {
+ const harness = await registerFakeUpdaterIpc({ version: "2.2.1", ...options });
+ harness.app.getVersion = () => "2.2.0";
+ const feed = { version: "2.2.1", failDownloadOf: null, failCheck: false };
+ const downloaded = [];
+ const installs = [];
+ let lastChecked = null;
+ harness.updater.checkForUpdates = async () => {
+ if (feed.failCheck) throw new Error("feed unreachable");
+ lastChecked = feed.version;
+ return { updateInfo: { version: feed.version } };
+ };
+ harness.updater.downloadUpdate = async () => {
+ if (lastChecked === feed.failDownloadOf) throw new Error(`HTTP 503 for ${lastChecked}`);
+ downloaded.push(lastChecked);
+ };
+ harness.updater.quitAndInstall = (isSilent, isForceRunAfter) => {
+ installs.push({ version: downloaded.at(-1), isSilent, isForceRunAfter });
+ };
+ return { ...harness, feed, downloaded, installs };
+}
+
+describe("installing the newest published release", () => {
+ it("downloads 2.2.3 and installs it when 2.2.1 is staged and 2.2.3 was published since", async () => {
+ const { tempDir, handlers, feed, downloaded, installs, updater } = await publishingFeedHarness();
+ try {
+ assert.equal((await handlers.get("omnirush:updater:check")(null, "stable")).latestVersion, "2.2.1");
+ assert.deepEqual(await handlers.get("omnirush:updater:download")(), { ok: true, mode: "in-place" });
+ assert.equal(updater.autoInstallOnAppQuit, false, "the staged 2.2.1 must not install behind the updater's back");
+ feed.version = "2.2.3";
+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });
+ assert.deepEqual(downloaded, ["2.2.1", "2.2.3"]);
+ assert.deepEqual(installs, [{ version: "2.2.3", isSilent: false, isForceRunAfter: true }]);
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("installs the staged download without re-downloading when it is still the newest", async () => {
+ const { tempDir, handlers, downloaded, installs } = await publishingFeedHarness();
+ try {
+ await handlers.get("omnirush:updater:check")(null, "stable");
+ await handlers.get("omnirush:updater:download")();
+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });
+ assert.deepEqual(downloaded, ["2.2.1"]);
+ assert.deepEqual(installs.map((install) => install.version), ["2.2.1"]);
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("reports no update and installs nothing when the feed has nothing newer", async () => {
+ const { tempDir, handlers, feed, downloaded, installs } = await publishingFeedHarness();
+ try {
+ feed.version = "2.2.0";
+ const checked = await handlers.get("omnirush:updater:check")(null, "stable");
+ assert.equal(checked.available, false);
+ assert.deepEqual(await handlers.get("omnirush:updater:download")(), { ok: false, reason: "No update available." });
+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: false, reason: "update-not-downloaded" });
+ assert.deepEqual(downloaded, []);
+ assert.deepEqual(installs, []);
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("never falls back to the stale download when the newer one fails to download", async () => {
+ const { tempDir, handlers, feed, downloaded, installs } = await publishingFeedHarness();
+ try {
+ await handlers.get("omnirush:updater:check")(null, "stable");
+ await handlers.get("omnirush:updater:download")();
+ feed.version = "2.2.3";
+ feed.failDownloadOf = "2.2.3";
+ const failed = await handlers.get("omnirush:updater:installAndRestart")();
+ assert.equal(failed.ok, false);
+ assert.match(failed.reason, /2\.2\.3 is available but could not be downloaded: HTTP 503/);
+ assert.deepEqual(installs, [], "2.2.1 must not install once 2.2.3 is on the feed");
+ // The renderer's retry path: nothing staged, so it re-checks and downloads again.
+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: false, reason: "update-not-downloaded" });
+ feed.failDownloadOf = null;
+ assert.equal((await handlers.get("omnirush:updater:check")(null, "stable")).latestVersion, "2.2.3");
+ assert.deepEqual(await handlers.get("omnirush:updater:download")(), { ok: true, mode: "in-place" });
+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });
+ assert.deepEqual(downloaded, ["2.2.1", "2.2.3"]);
+ assert.deepEqual(installs.map((install) => install.version), ["2.2.3"]);
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("installs the staged download when the feed cannot be reached", async () => {
+ const { tempDir, handlers, feed, installs } = await publishingFeedHarness();
+ try {
+ await handlers.get("omnirush:updater:check")(null, "stable");
+ await handlers.get("omnirush:updater:download")();
+ feed.failCheck = true;
+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });
+ assert.deepEqual(installs.map((install) => install.version), ["2.2.1"]);
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("a periodic check replaces the staged download with the newer release", async () => {
+ const { tempDir, handlers, feed, downloaded, installs } = await publishingFeedHarness();
+ try {
+ await handlers.get("omnirush:updater:check")(null, "stable");
+ await handlers.get("omnirush:updater:download")();
+ feed.version = "2.2.2";
+ assert.equal((await handlers.get("omnirush:updater:check")(null, "stable")).latestVersion, "2.2.2");
+ await handlers.get("omnirush:updater:download")();
+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });
+ assert.deepEqual(downloaded, ["2.2.1", "2.2.2"]);
+ assert.deepEqual(installs.map((install) => install.version), ["2.2.2"]);
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("on quit, re-checks the feed and silently installs the newest release", async () => {
+ const { tempDir, handlers, feed, downloaded, installs, updater, prepareInstallOnQuit } = await publishingFeedHarness({
+ quitInstallFallbackMs: 0,
+ });
+ try {
+ assert.equal(await prepareInstallOnQuit(), null, "nothing staged: plain quit");
+ await handlers.get("omnirush:updater:check")(null, "stable");
+ await handlers.get("omnirush:updater:download")();
+ feed.version = "2.2.3";
+ const installAndQuit = await prepareInstallOnQuit();
+ assert.equal(typeof installAndQuit, "function");
+ installAndQuit();
+ assert.deepEqual(downloaded, ["2.2.1", "2.2.3"]);
+ assert.deepEqual(installs, [{ version: "2.2.3", isSilent: true, isForceRunAfter: false }]);
+ assert.equal(updater.autoRunAppAfterInstall, false);
+ assert.equal(await prepareInstallOnQuit(), null, "an install already started");
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("on quit, skips the stale download when the newer release cannot be fetched", async () => {
+ const { tempDir, handlers, feed, installs, prepareInstallOnQuit } = await publishingFeedHarness();
+ try {
+ await handlers.get("omnirush:updater:check")(null, "stable");
+ await handlers.get("omnirush:updater:download")();
+ feed.version = "2.2.3";
+ feed.failDownloadOf = "2.2.3";
+ assert.equal(await prepareInstallOnQuit(), null);
+ assert.deepEqual(installs, []);
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("on quit, gives up on a slow feed instead of holding the app open", async () => {
+ const { tempDir, handlers, updater, installs, prepareInstallOnQuit } = await publishingFeedHarness({
+ quitUpdateTimeoutMs: 20,
+ installCheckTimeoutMs: 20,
+ });
+ try {
+ await handlers.get("omnirush:updater:check")(null, "stable");
+ await handlers.get("omnirush:updater:download")();
+ updater.checkForUpdates = () => new Promise(() => {});
+ assert.equal(await prepareInstallOnQuit(), null);
+ assert.deepEqual(installs, []);
+ } finally {
+ await rm(tempDir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("dev update feed override", () => {
+ it("honors only loopback URLs", () => {
+ assert.equal(loopbackDevFeedUrl("http://127.0.0.1:8765/feed/"), "http://127.0.0.1:8765/feed");
+ assert.equal(loopbackDevFeedUrl("http://localhost:8765"), "http://localhost:8765");
+ assert.equal(loopbackDevFeedUrl("https://updates.example.com/feed"), null);
+ assert.equal(loopbackDevFeedUrl("file:///tmp/feed"), null);
+ assert.equal(loopbackDevFeedUrl(undefined), null);
+ assert.equal(updaterFeedOptions({ devFeedUrl: "http://127.0.0.1:1/f" }).stableFeedUrl, "http://127.0.0.1:1/f");
+ assert.equal(updaterFeedOptions({ devFeedUrl: "https://evil.example/f" }).stableFeedUrl, STABLE_FEED);
+ });
+});