A desktop coding agent with free access to frontier models.
TypeScript
fix: restart to update reports why it stopped
ogsamratd04a4c47e275
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex ae87e910..54adcf2c 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -264,11 +264,15 @@ declare global {installAndRestart?: () => Promise<{ok: boolean;reason?: string;- mode?: UpdaterInstallMode;+ /** "moving": a macOS app is being moved to /Applications and reopens from there. */+ mode?: UpdaterInstallMode | "moving";path?: string | null;command?: string | null;- /** The app could not replace itself (an administrator prompt was cancelled). */- fallback?: "download-page";+ /**+ * "download-page": the app could not replace itself (an administrator prompt was cancelled).+ * "move-to-applications": a macOS app on the DMG or in Downloads must be moved first.+ */+ fallback?: "download-page" | "move-to-applications";}>;showDownloaded?: () => Promise<{ ok: boolean }>;};diff --git a/apps/app/src/react-app/domains/settings/pages/updates-view.tsx b/apps/app/src/react-app/domains/settings/pages/updates-view.tsxindex 451cda1b..008b59c3 100644--- a/apps/app/src/react-app/domains/settings/pages/updates-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/updates-view.tsx@@ -238,6 +238,18 @@ export function UpdatesView(props: UpdatesViewProps) {</Alert>) : null}+ {updateState === "error" && props.updateStatus?.failedAction === "install" ? (+ <div>+ <Button+ variant="outline"+ data-testid="update-install-failed-download"+ onClick={() => void window.__OMNIRUSH_ELECTRON__?.shell?.openExternal?.(downloadPageUrl)}+ >+ {t("settings.update_open_download_page_button")}+ </Button>+ </div>+ ) : null}+{updateState === "blocked" && updateErrorMessage ? (<Alert><Info />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.tsindex d89f7598..ae22e92d 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@@ -178,6 +178,28 @@ function capabilitiesFromBridge(state: {};}+// The main process gives an install 2 minutes to start; the renderer waits a+// little longer for its answer, and as long again for the app to go away.+const RESTART_ANSWER_MS = 150_000;+const RESTART_STALLED_MS = 90_000;+const RESTART_STALLED_MESSAGE =+ "The app did not restart. Quit it fully and open it again to finish the update, or download the new version from the download page.";++type InstallAndRestartResult = Awaited<ReturnType<NonNullable<ElectronUpdaterBridge["installAndRestart"]>>>;++function withRestartWatchdog(pending: Promise<InstallAndRestartResult>): Promise<InstallAndRestartResult> {+ let timer: number | undefined;+ return Promise.race([+ pending,+ new Promise<InstallAndRestartResult>((resolve) => {+ timer = window.setTimeout(+ () => resolve({ ok: false, reason: RESTART_STALLED_MESSAGE } as InstallAndRestartResult),+ RESTART_ANSWER_MS,+ );+ }),+ ]).finally(() => window.clearTimeout(timer));+}+/** Where "Open download page" goes: the server's download_url while an update is required. */function downloadPageUrl(): string {return useUpdateGateStore.getState().state.downloadUrl;@@ -738,7 +760,10 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)return;}}- const result = await bridge.installAndRestart();+ // The main process answers once the install is under way (the app+ // starts quitting) or has failed, so show "Restarting…" meanwhile.+ setUpdateStatus((current) => ({ ...(current ?? {}), state: "ready", restarting: true }));+ const result = await withRestartWatchdog(bridge.installAndRestart());if (!isCurrentReleaseChannel()) return;if (!result?.ok) {if (result?.reason === "update-not-downloaded") {@@ -750,6 +775,17 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)return;}const reason = result?.reason ? stripRemoteMethodErrorPrefix(result.reason) : "Update install failed.";+ if (result?.fallback === "move-to-applications") {+ // macOS app on the DMG or in Downloads: the message says to move it.+ setUpdateStatus((current) => ({+ ...(current ?? {}),+ state: "error",+ restarting: false,+ message: reason,+ failedAction: "install",+ }));+ return;+ }if (result?.fallback === "download-page") {// The app could not replace itself (the administrator prompt was// cancelled): this is the one place the download page opens, and@@ -770,8 +806,16 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)});return;}- if (result.mode === "in-place") {+ if (result.mode === "in-place" || result.mode === "moving") {setUpdateStatus((current) => ({ ...(current ?? {}), state: "ready", restarting: true }));+ // The app is quitting now. Still here much later: something held it open.+ window.setTimeout(() => {+ setUpdateStatus((current) => current?.restarting+ ? { ...current, state: "error", restarting: false, message: RESTART_STALLED_MESSAGE, failedAction: "install" }+ : current);+ }, RESTART_STALLED_MS);+ } else {+ setUpdateStatus((current) => (current?.restarting ? { ...current, restarting: false } : current));}if (result.mode === "manual-dmg") {// The shell opened the DMG and quits shortly; leave the instructionsdiff --git a/apps/app/src/react-app/shell/update-gate.tsx b/apps/app/src/react-app/shell/update-gate.tsxindex 9d22bfb4..4bfbf975 100644--- a/apps/app/src/react-app/shell/update-gate.tsx+++ b/apps/app/src/react-app/shell/update-gate.tsx@@ -154,7 +154,9 @@ function useRequiredUpdate(gate: UpdateGateState) {? "The installer is open. Replace the app from it, then open it again.": null;const command = installMode === "package" && updaterState === "ready" ? status?.installCommand ?? null : null;- return { updateNow, working, detail, label, command, showDownloaded: updater.showDownloadedUpdate };+ // A restart that did not go through: offer the manual download next to the retry.+ const installFailed = updaterState === "error" && status?.failedAction === "install";+ return { updateNow, working, detail, label, command, installFailed, showDownloaded: updater.showDownloadedUpdate };}type RequiredUpdate = ReturnType<typeof useRequiredUpdate>;@@ -194,6 +196,16 @@ export function RequiredUpdateBanner(props: { gate: UpdateGateState; appName: st<span className="truncate" data-testid="update-required-banner-text">{text}</span>{detail ? <span className={props.update.command ? "hidden truncate font-mono text-amber-900/80 select-text md:inline" : "hidden truncate text-amber-900/80 md:inline"}>· {detail}</span> : null}<UpdateNowButton update={props.update} testId="update-required-banner-button" />+ {props.update.installFailed ? (+ <button+ type="button"+ data-testid="update-required-banner-download"+ onClick={() => openDownload(props.gate.downloadUrl)}+ className="shrink-0 text-[11px] font-semibold underline underline-offset-2 hover:text-black mac:titlebar-no-drag"+ >+ Download manually+ </button>+ ) : null}</div>);}diff --git a/apps/app/tests/update-gate.test.tsx b/apps/app/tests/update-gate.test.tsxindex a46569e5..3e25c10d 100644--- a/apps/app/tests/update-gate.test.tsx+++ b/apps/app/tests/update-gate.test.tsx@@ -31,13 +31,14 @@ const required: UpdateGateState = {};const blocked: UpdateGateState = { ...required, status: "blocked", message: "Update OmniRush.ai to 3.1.0 to keep using models.", source: "rejection" };-function fakeUpdate(over: Partial<{ label: string; working: boolean; detail: string | null; command: string | null }> = {}) {+function fakeUpdate(over: Partial<{ label: string; working: boolean; detail: string | null; command: string | null; installFailed: boolean }> = {}) {return {updateNow: () => undefined,working: false,detail: null,label: "Update and restart",command: null,+ installFailed: false,showDownloaded: () => undefined,...over,};@@ -156,11 +157,28 @@ describe("Update now", () => {test("nothing opens a browser by itself", () => {const hook = read("../src/react-app/shell/update-gate.tsx");- // openDownload runs only from the "open-download" action and the explicit link.- expect(hook.match(/openDownload\(/g)?.length).toBe(3);+ // openDownload runs only from the "open-download" action and the explicit links.+ expect(hook.match(/openDownload\(/g)?.length).toBe(4);expect(hook).toContain('case "open-download":\n openDownload(gate.downloadUrl);');});+ test("a restart that did not go through offers the manual download beside the retry", () => {+ const failed = renderToStaticMarkup(+ <RequiredUpdateBanner gate={required} appName="OmniRush.ai" update={fakeUpdate({ installFailed: true, detail: "The update did not finish: moved" })} />,+ );+ expect(failed).toContain('data-testid="update-required-banner-download"');+ expect(failed).toContain("Download manually");+ const fine = renderToStaticMarkup(<RequiredUpdateBanner gate={required} appName="OmniRush.ai" update={fakeUpdate()} />);+ expect(fine).not.toContain("update-required-banner-download");+ });++ test("Restarting… never spins forever: the main answer and the quit both have a watchdog", () => {+ const state = read("../src/react-app/domains/settings/state/electron-updater-state.ts");+ expect(state).toContain("withRestartWatchdog(bridge.installAndRestart())");+ expect(state).toContain("RESTART_STALLED_MS");+ expect(state).toContain('result?.fallback === "move-to-applications"');+ });+test("the download starts in the background as soon as an update is required", () => {const base = { supported: true, installMode: "in-place" as const };expect(shouldStartBackgroundDownload({ ...base, gate: required, updaterState: null })).toBe(true);diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex e16157b5..e56d7927 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -2939,10 +2939,15 @@ const browserLoginSync = createBrowserLoginSync({browserLoginSync.registerIpc(ipcMain, { evalSeam: browserLoginEvalSeam });registerMigrationIpc({ app, ipcMain });-const { ensureAutoUpdater, prepareInstallOnQuit } = registerUpdaterIpc({+const { ensureAutoUpdater, prepareInstallOnQuit, offerMoveAtLaunch } = registerUpdaterIpc({app,ipcMain,allowQuit: () => turnGuard.allowQuit(),+ restoreQuitGuard: () => turnGuard.restoreQuit(),+ nativeUpdater: require("electron").autoUpdater,+ showMessageBox: (options) => (mainWindow && !mainWindow.isDestroyed()+ ? dialog.showMessageBox(mainWindow, options)+ : dialog.showMessageBox(options)),getMainWindow: () => mainWindow,// All distributions intentionally share one application identifier, so they also// share Squirrel's ShipIt domain. Keep the shared default rather than@@ -3112,6 +3117,10 @@ or use: pnpm dev:worktree`);// a working app first. Renderer-owned checks pass the selected release// channel explicitly, avoiding stale stable-feed results for alpha users.runDetachedTask("initialize updater", ensureAutoUpdater);+ // macOS: a copy running from the DMG or Downloads can never update itself.+ if (process.platform === "darwin" && !BLANK_SLATE_LAUNCH.enabled) {+ runDetachedTask("offer move to Applications", offerMoveAtLaunch);+ }}).catch((error) => {console.error("[desktop] startup failed", error);dialog.showErrorBox(diff --git a/apps/desktop/electron/self-install.mjs b/apps/desktop/electron/self-install.mjsindex 29b0fb49..620f438e 100644--- a/apps/desktop/electron/self-install.mjs+++ b/apps/desktop/electron/self-install.mjs@@ -34,6 +34,23 @@ export function isTranslocatedBundle(bundlePath) {return typeof bundlePath === "string" && bundlePath.includes("/AppTranslocation/");}+/**+ * Whether the bundle sits on a read-only volume: the mounted DMG, or the+ * read-only mount App Translocation runs a quarantined app from. Squirrel.Mac+ * refuses to update from either ("Cannot update while running on a read-only+ * volume"). A folder this user merely cannot write (a standard user's+ * /Applications) is not read-only: ShipIt asks for an administrator there.+ */+export async function isOnReadOnlyVolume(bundlePath, check = access) {+ if (typeof bundlePath !== "string" || !bundlePath) return false;+ try {+ await check(path.dirname(bundlePath), fsConstants.W_OK);+ return false;+ } catch (error) {+ return error?.code === "EROFS";+ }+}+export async function isWritable(target) {try {await access(target, fsConstants.W_OK);diff --git a/apps/desktop/electron/turn-guard.mjs b/apps/desktop/electron/turn-guard.mjsindex 08d670ae..6b65e4bf 100644--- a/apps/desktop/electron/turn-guard.mjs+++ b/apps/desktop/electron/turn-guard.mjs@@ -136,6 +136,10 @@ export function createTurnGuard(deps) {allowed = true;closeDialog();},+ /** An update install that was let through did not start: ask again from now on. */+ restoreQuit() {+ allowed = false;+ },get state() {return guard.state;},diff --git a/apps/desktop/electron/turn-guard.test.mjs b/apps/desktop/electron/turn-guard.test.mjsindex c3266957..fdc30cfa 100644--- a/apps/desktop/electron/turn-guard.test.mjs+++ b/apps/desktop/electron/turn-guard.test.mjs@@ -126,6 +126,17 @@ test("allowQuit while the dialog is open closes it", async () => {assert.equal(dialogs[0].aborted, true);});+test("restoreQuit after an update install that did not start asks again", () => {+ const { guard, dialogs } = setup();+ guard.setTurnRunning(true);+ guard.allowQuit();+ guard.restoreQuit();+ const event = fakeEvent();+ assert.equal(guard.guardQuit(event, () => {}), false);+ assert.equal(event.prevented, true);+ assert.equal(dialogs.length, 1);+});+test("only a strict true marks a turn running", () => {const { guard } = setup();assert.equal(guard.setTurnRunning("yes"), false);diff --git a/apps/desktop/electron/updater.mjs b/apps/desktop/electron/updater.mjsindex c766936b..b7ec060f 100644--- a/apps/desktop/electron/updater.mjs+++ b/apps/desktop/electron/updater.mjs@@ -22,6 +22,7 @@ import {canReplaceInPlace,fileExists,isAuthorizationCancelled,+ isOnReadOnlyVolume,isTranslocatedBundle,launchMacSwap,linuxAppImagePath,@@ -525,6 +526,20 @@ export function registerUpdaterIpc({installAppImage = replaceAppImage,relaunchAppImage = relaunchAppImageAfterExit,restartDelayMs = 300,+ // Re-arms the quit guard when an install that was let through did not start.+ restoreQuitGuard = () => {},+ // Electron's own autoUpdater: it emits before-quit-for-update once an+ // in-place install is accepted and the app starts closing.+ nativeUpdater = null,+ // How long an in-place install may take to start quitting the app (Squirrel+ // copies and verifies the whole bundle first) before the user is told.+ installStartTimeoutMs = 120_000,+ // macOS: Squirrel cannot update an app on a read-only volume (the DMG, App+ // Translocation); the user is offered a move to /Applications instead.+ showMessageBox = null,+ isReadOnlyVolume = isOnReadOnlyVolume,+ isInApplicationsFolder = () => (typeof app.isInApplicationsFolder === "function" ? app.isInApplicationsFolder() : true),+ moveToApplicationsFolder = () => app.moveToApplicationsFolder(),}) {const quitApp = () => {allowQuit();@@ -644,6 +659,145 @@ export function registerUpdaterIpc({};}+ function appDisplayName() {+ try {+ return (typeof app.getName === "function" && app.getName()) || "OmniRush.ai";+ } catch {+ return "OmniRush.ai";+ }+ }++ function runningMacBundle() {+ try {+ return macBundleFromPath(getAppPath()) ?? macAppBundlePath(execPath);+ } catch {+ return macAppBundlePath(execPath);+ }+ }++ /**+ * macOS: the running bundle when it sits where Squirrel.Mac cannot update+ * it (the mounted DMG, an App Translocation mount), else null.+ */+ async function macBundleBlockingUpdate() {+ if (platform !== "darwin" || !app.isPackaged) return null;+ const bundle = runningMacBundle();+ if (!bundle) return null;+ try {+ if (isInApplicationsFolder()) return null;+ } catch {+ // Unknown: judge by the location alone.+ }+ if (isTranslocatedBundle(bundle) || (await isReadOnlyVolume(bundle))) return bundle;+ return null;+ }++ function moveNeededReason() {+ const name = appDisplayName();+ return `${name} is running from the disk image or the Downloads folder, where it cannot update itself. Quit ${name}, drag it into Applications, open it from there and update again, or download the new version from the download page.`;+ }++ /**+ * Offers to move the app into /Applications. Electron copies it there,+ * quits this copy and reopens the moved one, which can then update.+ * OMNIRUSH_UPDATER_MOVE_ANSWER=move|cancel answers without the dialog+ * (unattended update rigs).+ */+ async function offerMoveToApplications({ atLaunch = false } = {}) {+ const name = appDisplayName();+ const preset = typeof env.OMNIRUSH_UPDATER_MOVE_ANSWER === "string" ? env.OMNIRUSH_UPDATER_MOVE_ANSWER.trim() : "";+ let move = false;+ if (preset === "move" || preset === "cancel") {+ move = preset === "move";+ } else if (typeof showMessageBox === "function") {+ try {+ const { response } = await showMessageBox({+ type: "info",+ message: atLaunch ? `Move ${name} to Applications?` : `Move ${name} to Applications to update`,+ detail: `${name} is running from the disk image or the Downloads folder, where it cannot update itself. Move it to Applications and it reopens from there${atLaunch ? "." : ". Then choose Restart to update again."}`,+ buttons: ["Move to Applications", atLaunch ? "Not Now" : "Cancel"],+ defaultId: 0,+ cancelId: 1,+ noLink: true,+ });+ move = response === 0;+ } catch {+ move = false;+ }+ }+ const notMoved = (detail = "") => ({+ ok: false,+ fallback: "move-to-applications",+ reason: `${detail}${moveNeededReason()}`,+ });+ if (!move) return notMoved();+ allowQuit();+ try {+ if (!moveToApplicationsFolder()) {+ restoreQuitGuard();+ return notMoved();+ }+ } catch (error) {+ restoreQuitGuard();+ return notMoved(`${name} could not be moved to Applications: ${String(error?.message ?? error)}. `);+ }+ // Electron quits by itself after the move; make sure this copy goes.+ setTimeout(() => quitApp(), restartDelayMs);+ return { ok: true, mode: "moving" };+ }++ function installFailureReason(error) {+ const message = String(error?.message ?? error ?? "unknown error").replace(/^Error:\s*/, "");+ if (/read-only volume/i.test(message)) return moveNeededReason();+ return `The update could not be installed: ${message}`;+ }++ /**+ * Starts an electron-updater install and resolves only once it is under+ * way (the app starts quitting) or has failed. Squirrel.Mac reports a+ * refused update (read-only volume, signature mismatch) through the+ * updater's error event after quitAndInstall returned; answering before+ * that left the renderer on "Restarting…" with nothing happening.+ */+ function startInPlaceInstall(updater) {+ return new Promise((resolve) => {+ const cleanups = [];+ let settled = false;+ const settle = (result) => {+ if (settled) return;+ settled = true;+ for (const cleanup of cleanups) {+ try {+ cleanup();+ } catch {+ // Already detached.+ }+ }+ resolve(result);+ };+ const listen = (emitter, name, handler) => {+ if (typeof emitter?.on !== "function") return;+ emitter.on(name, handler);+ const off = emitter.removeListener ?? emitter.off;+ if (typeof off === "function") cleanups.push(() => off.call(emitter, name, handler));+ };+ const started = () => settle({ ok: true, mode: "in-place" });+ listen(updater, "error", (error) => settle({ ok: false, reason: installFailureReason(error) }));+ listen(app, "before-quit", started);+ listen(nativeUpdater, "before-quit-for-update", started);+ const timer = setTimeout(() => settle({+ ok: false,+ reason: `The update did not start within ${Math.round(installStartTimeoutMs / 1000)} seconds. Quit ${appDisplayName()} and open it again to finish the update, or download the new version from the download page.`,+ }), installStartTimeoutMs);+ cleanups.push(() => clearTimeout(timer));+ try {+ updater.quitAndInstall(false, true);+ } catch (error) {+ settle({ ok: false, reason: installFailureReason(error) });+ }+ });+ }+/** The file a self-install mode downloads itself, from the manifest just read. */function selfInstallAsset(info, feedUrl, installMode) {switch (installMode) {@@ -1284,6 +1438,8 @@ export function registerUpdaterIpc({// Quitting never asks for a password: an /Applications this user cannot// write waits for "Restart to update".if (installMode === "mac-swap" && !(await canReplace(installTarget))) return null;+ // Squirrel would refuse it (DMG, App Translocation); the next launch asks to move.+ if (installMode === "in-place" && (await macBundleBlockingUpdate())) return null;const newest = await withTimeout(queueUpdaterOperation(() => ensureNewestDownloaded(updater, installMode)),quitUpdateTimeoutMs,@@ -1421,18 +1577,35 @@ export function registerUpdaterIpc({return { ok: false, reason: String(error?.message ?? error) };}}+ if (await macBundleBlockingUpdate()) return offerMoveToApplications();+ // 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(shipItDefaultsDomain);+ installTriggered = true;+ // An update install is never held up by the running-turn question.+ allowQuit();+ const started = await startInPlaceInstall(updater);+ if (!started.ok) {+ installTriggered = false;+ restoreQuitGuard();+ console.warn("[updater] install did not start", started.reason);+ }+ return started;+ }));++ /**+ * At launch (macOS): an app that runs from the DMG or a translocated copy+ * can never update itself, so offer the move to /Applications right away.+ */+ async function offerMoveAtLaunch() {try {- // 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;- allowQuit();- updater.quitAndInstall(false, true);- return { ok: true, mode: "in-place" };+ if (!(await macBundleBlockingUpdate())) return { offered: false };+ return { offered: true, ...(await offerMoveToApplications({ atLaunch: true })) };} catch (error) {- return { ok: false, reason: String(error?.message ?? error) };+ console.warn("[updater] move check failed", error?.message ?? error);+ return { offered: false };}- }));+ }- return { ensureAutoUpdater, prepareInstallOnQuit };+ return { ensureAutoUpdater, prepareInstallOnQuit, offerMoveAtLaunch };}diff --git a/apps/desktop/electron/updater.test.mjs b/apps/desktop/electron/updater.test.mjsindex f0d7af45..12d16fb5 100644--- a/apps/desktop/electron/updater.test.mjs+++ b/apps/desktop/electron/updater.test.mjs@@ -1,6 +1,7 @@import { describe, it } from "node:test";import assert from "node:assert/strict";import { createHash } from "node:crypto";+import { EventEmitter } from "node:events";import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync } from "node:fs";import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import os from "node:os";@@ -45,7 +46,16 @@ const desktopVersion = JSON.parse(let isolatedUpdaterImportId = 0;function fakeUpdaterHarness({ version, files }) {- const listeners = new Map();+ // Several listeners per event, like an EventEmitter; `listeners.get(name)`+ // fires them all (undefined while none is registered).+ const registered = new Map();+ const listeners = {+ get: (name) => (registered.get(name)?.size+ ? (...args) => { for (const fn of [...registered.get(name)]) fn(...args); }+ : undefined),+ };+ // The app's own events: a real install quits the app (before-quit).+ const appEvents = new EventEmitter();const calls = [];const feeds = [];const downloadFeeds = [];@@ -55,7 +65,11 @@ function fakeUpdaterHarness({ version, files }) {disableDifferentialDownload: false,allowPrerelease: false,allowDowngrade: false,- on: (name, fn) => listeners.set(name, fn),+ on: (name, fn) => {+ if (!registered.has(name)) registered.set(name, new Set());+ registered.get(name).add(fn);+ },+ removeListener: (name, fn) => registered.get(name)?.delete(fn),setFeedURL: (feed) => feeds.push(feed),checkForUpdates: async () => ({ updateInfo: { version, ...(files ? { files } : {}) } }),downloadUpdate: async () => {@@ -64,9 +78,10 @@ function fakeUpdaterHarness({ version, files }) {},quitAndInstall: () => {calls.push("quitAndInstall");+ appEvents.emit("before-quit");},};- return { updater, listeners, calls, feeds, downloadFeeds };+ return { updater, listeners, appEvents, calls, feeds, downloadFeeds };}async function registerFakeUpdaterIpc({ version, files = undefined, ...options }) {@@ -87,6 +102,8 @@ async function registerFakeUpdaterIpc({ version, files = undefined, ...options }getVersion: () => "0.17.0",getPath: (key) => path.join(tempDir, key),quit: () => harness.calls.push("quit"),+ on: (name, fn) => harness.appEvents.on(name, fn),+ removeListener: (name, fn) => harness.appEvents.removeListener(name, fn),};const registered = registerIsolatedUpdaterIpc({app,@@ -998,6 +1015,7 @@ async function publishingFeedHarness(options = {}) {};harness.updater.quitAndInstall = (isSilent, isForceRunAfter) => {installs.push({ version: downloaded.at(-1), isSilent, isForceRunAfter });+ harness.appEvents.emit("before-quit");};return { ...harness, feed, downloaded, installs };}@@ -1459,3 +1477,272 @@ describe("Linux package installs", () => {assert.equal(shellQuote("/home/o'neil/My Downloads/x.deb"), "'/home/o'\\''neil/My Downloads/x.deb'");});});++describe("restart to update finishes or says why", () => {+ const READ_ONLY = "Cannot update while running on a read-only volume. The application is on a read-only volume. Please move the application and try again.";++ async function stagedInPlace(options = {}) {+ const order = [];+ const registered = await registerFakeUpdaterIpc({+ version: "3.3.3",+ allowQuit: () => order.push("allowQuit"),+ restoreQuitGuard: () => order.push("restoreQuitGuard"),+ ...options,+ });+ assert.equal((await registered.handlers.get("omnirush:updater:check")(null, "stable")).available, true);+ assert.deepEqual(await registered.handlers.get("omnirush:updater:download")(), { ok: true, mode: "in-place" });+ return { ...registered, order };+ }++ it("lets the install through the quit guard before it quits the app", async () => {+ const { tempDir, handlers, updater, order, calls } = await stagedInPlace();+ try {+ const original = updater.quitAndInstall;+ updater.quitAndInstall = (...args) => {+ order.push("quitAndInstall");+ original(...args);+ };+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });+ assert.deepEqual(order, ["allowQuit", "quitAndInstall"]);+ assert.deepEqual(calls, ["download", "quitAndInstall"]);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("reports an error Squirrel raises after quitAndInstall instead of answering ok", async () => {+ const { tempDir, handlers, updater, listeners, appEvents, order } = await stagedInPlace();+ try {+ let attempts = 0;+ updater.quitAndInstall = () => {+ attempts += 1;+ // Squirrel.Mac answers asynchronously through the updater's error event.+ setTimeout(() => listeners.get("error")(new Error("Code signature at URL did not pass validation")), 5);+ };+ const result = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(result.ok, false);+ assert.match(result.reason, /could not be installed: Code signature at URL did not pass validation/);+ assert.deepEqual(order, ["allowQuit", "restoreQuitGuard"], "a failed install re-arms the quit guard");+ // The staged download stays and installTriggered is reset: the button retries.+ updater.quitAndInstall = () => {+ attempts += 1;+ appEvents.emit("before-quit");+ };+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });+ assert.equal(attempts, 2);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("explains a read-only volume refusal as a move to Applications", async () => {+ const { tempDir, handlers, updater, listeners } = await stagedInPlace();+ try {+ updater.quitAndInstall = () => setTimeout(() => listeners.get("error")(new Error(READ_ONLY)), 5);+ const result = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(result.ok, false);+ assert.match(result.reason, /drag it into Applications, open it from there and update again, or download the new version/);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("answers ok when Electron's updater announces before-quit-for-update", async () => {+ const nativeUpdater = new EventEmitter();+ const { tempDir, handlers, updater } = await stagedInPlace({ nativeUpdater });+ try {+ updater.quitAndInstall = () => setTimeout(() => nativeUpdater.emit("before-quit-for-update"), 5);+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });+ assert.equal(nativeUpdater.listenerCount("before-quit-for-update"), 0, "listeners are removed");+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("gives up with a message when the install never starts", async () => {+ const { tempDir, handlers, updater, order } = await stagedInPlace({ installStartTimeoutMs: 30 });+ try {+ updater.quitAndInstall = () => {};+ const result = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(result.ok, false);+ assert.match(result.reason, /did not start within 0 seconds\. Quit .* and open it again to finish the update, or download the new version/);+ assert.deepEqual(order, ["allowQuit", "restoreQuitGuard"]);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("reports a synchronous quitAndInstall throw", async () => {+ const { tempDir, handlers, updater } = await stagedInPlace();+ try {+ updater.quitAndInstall = () => {+ throw new Error("No update filepath provided, can't quit and install");+ };+ const result = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(result.ok, false);+ assert.match(result.reason, /No update filepath provided/);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });+});++describe("macOS app outside Applications", () => {+ const DMG_BUNDLE = "/Volumes/OmniRush.ai 3.3.2-arm64/OmniRush.ai.app";+ const TRANSLOCATED = "/private/var/folders/xy/T/AppTranslocation/0A1B/d/OmniRush.ai.app";++ async function stagedMac({ bundle = DMG_BUNDLE, readOnly = true, inApplications = false, answer = 1, move = () => true, ...options } = {}) {+ const order = [];+ const dialogs = [];+ const registered = await registerFakeUpdaterIpc({+ version: "3.3.3",+ platform: "darwin",+ isDeveloperIdSigned: async () => true,+ getAppPath: () => `${bundle}/Contents/Resources/app.asar`,+ execPath: `${bundle}/Contents/MacOS/OmniRush.ai`,+ isReadOnlyVolume: async () => readOnly,+ isInApplicationsFolder: () => inApplications,+ moveToApplicationsFolder: () => {+ order.push("move");+ return move();+ },+ showMessageBox: async (options) => {+ dialogs.push(options);+ return { response: answer };+ },+ allowQuit: () => order.push("allowQuit"),+ restoreQuitGuard: () => order.push("restoreQuitGuard"),+ restartDelayMs: 1,+ ...options,+ });+ registered.app.quit = () => order.push("quit");+ assert.equal((await registered.handlers.get("omnirush:updater:check")(null, "stable")).installMode, "in-place");+ assert.deepEqual(await registered.handlers.get("omnirush:updater:download")(), { ok: true, mode: "in-place" });+ return { ...registered, order, dialogs };+ }++ it("from the DMG: asks to move instead of handing Squirrel an update it refuses", async () => {+ const { tempDir, handlers, calls, order, dialogs } = await stagedMac({ answer: 1 });+ try {+ const result = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(result.ok, false);+ assert.equal(result.fallback, "move-to-applications");+ assert.match(result.reason, /disk image or the Downloads folder/);+ assert.equal(dialogs.length, 1);+ assert.deepEqual(dialogs[0].buttons, ["Move to Applications", "Cancel"]);+ assert.deepEqual(calls, ["download"], "quitAndInstall never runs from a read-only volume");+ assert.deepEqual(order, []);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("from the DMG: Move to Applications moves the app and quits this copy", async () => {+ const { tempDir, handlers, calls, order } = await stagedMac({ answer: 0 });+ try {+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "moving" });+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.deepEqual(order, ["allowQuit", "move", "allowQuit", "quit"]);+ assert.deepEqual(calls, ["download"]);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("a failed move says why and re-arms the quit guard", async () => {+ const { tempDir, handlers, order } = await stagedMac({+ answer: 0,+ move: () => {+ throw new Error("Failed to copy bundle");+ },+ });+ try {+ const result = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(result.ok, false);+ assert.match(result.reason, /could not be moved to Applications: Failed to copy bundle/);+ assert.deepEqual(order, ["allowQuit", "move", "restoreQuitGuard"]);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("App Translocation counts as outside Applications even when the check cannot see a read-only volume", async () => {+ const { tempDir, handlers, calls } = await stagedMac({ bundle: TRANSLOCATED, readOnly: false, answer: 1 });+ try {+ const result = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(result.fallback, "move-to-applications");+ assert.deepEqual(calls, ["download"]);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("in Applications (or any writable folder) installs in place", async () => {+ for (const setup of [+ { bundle: "/Applications/OmniRush.ai.app", readOnly: false, inApplications: true },+ { bundle: "/Users/test/Apps/OmniRush.ai.app", readOnly: false, inApplications: false },+ ]) {+ const { tempDir, handlers, calls, dialogs } = await stagedMac(setup);+ try {+ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });+ assert.deepEqual(calls, ["download", "quitAndInstall"]);+ assert.equal(dialogs.length, 0);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ }+ });++ it("asks at launch only when the app cannot update where it is", async () => {+ const blocked = await stagedMac({ answer: 1 });+ const fine = await stagedMac({ bundle: "/Applications/OmniRush.ai.app", readOnly: false, inApplications: true });+ try {+ const asked = await blocked.offerMoveAtLaunch();+ assert.equal(asked.offered, true);+ assert.equal(asked.ok, false);+ assert.deepEqual(blocked.dialogs[0].buttons, ["Move to Applications", "Not Now"]);+ assert.deepEqual(await fine.offerMoveAtLaunch(), { offered: false });+ assert.equal(fine.dialogs.length, 0);+ } finally {+ await rm(blocked.tempDir, { recursive: true, force: true });+ await rm(fine.tempDir, { recursive: true, force: true });+ }+ });++ it("OMNIRUSH_UPDATER_MOVE_ANSWER answers without a dialog", async () => {+ const { tempDir, offerMoveAtLaunch, dialogs, order } = await stagedMac({ env: { OMNIRUSH_UPDATER_MOVE_ANSWER: "move" } });+ try {+ assert.deepEqual(await offerMoveAtLaunch(), { offered: true, ok: true, mode: "moving" });+ assert.equal(dialogs.length, 0);+ assert.ok(order.includes("move"));+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("quitting from the DMG installs nothing (Squirrel would refuse it)", async () => {+ const { tempDir, prepareInstallOnQuit } = await stagedMac();+ try {+ assert.equal(await prepareInstallOnQuit(), null);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });+});++describe("read-only volume detection", async () => {+ const { isOnReadOnlyVolume } = await import("./self-install.mjs");+ const failing = (code) => async () => {+ const error = new Error(code);+ error.code = code;+ throw error;+ };+ it("EROFS on the bundle's folder is a read-only volume", async () => {+ assert.equal(await isOnReadOnlyVolume("/Volumes/X/OmniRush.ai.app", failing("EROFS")), true);+ });+ it("a folder this user cannot write is not", async () => {+ assert.equal(await isOnReadOnlyVolume("/Applications/OmniRush.ai.app", failing("EACCES")), false);+ assert.equal(await isOnReadOnlyVolume("/Applications/OmniRush.ai.app", async () => undefined), false);+ assert.equal(await isOnReadOnlyVolume(null), false);+ });+});