A desktop coding agent with free access to frontier models.
TypeScript
fix(updater): install updates in place on unsigned macOS and AppImage, show the command for .deb/.rpm/.pacman
ogsamrat6f261af60756
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex 19e18c85..a3d42f92 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -149,12 +149,18 @@ export type RecoveryActionResult = {// ---------------------------------------------------------------------------/**- * How the desktop shell applies a downloaded update. "in-place" is- * electron-updater's swap (Squirrel.Mac, NSIS, AppImage); "manual-dmg" means- * the running macOS app is not Developer ID signed, so the shell downloads- * the DMG and opens it for a drag-to-Applications install instead.+ * How the desktop shell applies a downloaded update. "in-place": it replaces+ * itself and restarts (Squirrel.Mac, NSIS, the AppImage file, or the .app+ * bundle of a macOS build without a Developer ID signature). "package": a+ * .deb/.rpm/.pacman install the package manager owns; the shell downloads the+ * package and the user runs the install command. "manual-dmg": a macOS copy+ * that cannot be replaced (run from a translocated Downloads copy); the DMG+ * is downloaded and opened.*/-export type UpdaterInstallMode = "in-place" | "manual-dmg";+export type UpdaterInstallMode = "in-place" | "manual-dmg" | "package";++/** The package a "package" install updates with (null: none in the feed, e.g. a tar.gz). */+export type UpdaterPackageKind = "deb" | "rpm" | "pacman" | "appimage";declare global {interface Window {@@ -222,6 +228,7 @@ declare global {feedUrl: string;currentVersion: string;installMode?: UpdaterInstallMode;+ packageKind?: UpdaterPackageKind | null;alphaChannelSupported?: boolean;}>;setChannel?: (channel: "stable" | "alpha") => Promise<{@@ -229,6 +236,7 @@ declare global {feedUrl: string;currentVersion: string;installMode?: UpdaterInstallMode;+ packageKind?: UpdaterPackageKind | null;alphaChannelSupported?: boolean;}>;check?: (channel?: "stable" | "alpha", targetVersion?: string) => Promise<{@@ -241,10 +249,28 @@ declare global {feedUrl?: string;reason?: string;installMode?: UpdaterInstallMode;+ packageKind?: UpdaterPackageKind | null;alphaChannelSupported?: boolean;}>;- download?: () => Promise<{ ok: boolean; reason?: string; mode?: UpdaterInstallMode }>;- installAndRestart?: () => Promise<{ ok: boolean; reason?: string; mode?: UpdaterInstallMode; path?: string }>;+ download?: () => Promise<{+ ok: boolean;+ reason?: string;+ mode?: UpdaterInstallMode;+ packageKind?: UpdaterPackageKind | null;+ path?: string | null;+ /** "package" mode: the command that installs the downloaded package. */+ command?: string | null;+ }>;+ installAndRestart?: () => Promise<{+ ok: boolean;+ reason?: string;+ mode?: UpdaterInstallMode;+ path?: string | null;+ command?: string | null;+ /** The app could not replace itself (an administrator prompt was cancelled). */+ fallback?: "download-page";+ }>;+ showDownloaded?: () => Promise<{ ok: boolean }>;};recovery?: {recordHealthy?: () => Promise<unknown>;diff --git a/apps/app/src/app/lib/update-gate.ts b/apps/app/src/app/lib/update-gate.tsindex 5e84a815..24934dca 100644--- a/apps/app/src/app/lib/update-gate.ts+++ b/apps/app/src/app/lib/update-gate.ts@@ -84,28 +84,50 @@ export function chatBlockedByUpdate(state: UpdateGateState): boolean {}export type RequiredUpdateAction =- /** A staged update is ready: install it (Linux AppImage, Windows, Developer ID macOS). */+ /** A staged update is ready: restart into it. */| "install"- /** The updater cannot install this build (ad-hoc macOS, no updater): open the download page. */+ /** The app cannot update itself here (no updater, a DMG-only copy): the button opens the download page. */| "open-download"- /** Start (or keep) the download and install as soon as it is ready. */+ /** Start (or retry) the download and restart as soon as it is ready. */| "download-then-install"+ /** A package install: download the package; the user runs the command. */+ | "download-package"+ /** The package is downloaded: copy the command that installs it. */+ | "copy-command"/** A check or download is running: install when it is ready. */| "wait";+type UpdaterInstallMode = "in-place" | "manual-dmg" | "package";+/**- * What "Update now" does, from the shell's updater: `installMode`- * "manual-dmg" (a macOS build without a Developer ID signature, which- * Squirrel cannot swap) and an unsupported updater send the user to- * `download_url`. After a failed check or download "Update now" tries- * once more, and opens `download_url` if that fails too.+ * What "Update now" does, from the shell's updater. The app replaces itself+ * wherever it can ("in-place": Squirrel, NSIS, the AppImage file, or the .app+ * bundle of an unsigned macOS build). A .deb/.rpm/.pacman install downloads+ * the package and shows the command. Only where none of that applies does+ * the button open `download_url`, and then its label says so. A failed check+ * or download is retried from the button; nothing opens a browser by itself.*/export function requiredUpdateAction(input: {supported: boolean;- installMode: "in-place" | "manual-dmg" | null;+ installMode: UpdaterInstallMode | null;updaterState: string | null | undefined;+ packageKind?: string | null;}): RequiredUpdateAction {if (!input.supported || input.installMode === "manual-dmg") return "open-download";+ if (input.installMode === "package") {+ if (!input.packageKind) return "open-download";+ switch (input.updaterState) {+ case "ready":+ return "copy-command";+ case "checking":+ case "downloading":+ return "wait";+ case "blocked":+ return "open-download";+ default:+ return "download-package";+ }+ }switch (input.updaterState) {case "ready":return "install";@@ -120,14 +142,52 @@ export function requiredUpdateAction(input: {}}-/** Whether the background download should start now (in-place updaters only, once per gate). */+const PACKAGE_LABELS: Record<string, string> = { deb: ".deb", rpm: ".rpm", pacman: ".pacman", appimage: "AppImage" };++/**+ * The button says what pressing it does: "Restart to update",+ * "Downloading 3.1.1… 42%", "Download 3.1.1 (.deb)", "Copy install command",+ * or "Open download page".+ */+export function updateButtonLabel(input: {+ action: RequiredUpdateAction;+ version?: string | null;+ progress?: number | null;+ updaterState?: string | null;+ packageKind?: string | null;+ restarting?: boolean;+}): string {+ const version = input.version ? ` ${input.version}` : "";+ switch (input.action) {+ case "install":+ return input.restarting ? "Restarting…" : "Restart to update";+ case "copy-command":+ return "Copy install command";+ case "open-download":+ return "Open download page";+ case "download-package":+ return `Download${version} (${PACKAGE_LABELS[input.packageKind ?? ""] ?? "package"})`;+ case "wait":+ if (input.updaterState === "downloading") {+ return input.progress == null ? `Downloading${version}…` : `Downloading${version}… ${input.progress}%`;+ }+ return "Checking for the update…";+ default:+ return input.updaterState === "error" ? "Try the update again" : "Update and restart";+ }+}++/** Whether the background download should start now (self-updating installs only, once per gate). */export function shouldStartBackgroundDownload(input: {gate: UpdateGateState;supported: boolean;- installMode: "in-place" | "manual-dmg" | null;+ installMode: UpdaterInstallMode | null;updaterState: string | null | undefined;}): boolean {- if (input.gate.status === "none" || !input.supported || input.installMode === "manual-dmg") return false;+ if (input.gate.status === "none" || !input.supported) return false;+ // A DMG-only copy cannot replace itself, and a package lands in Downloads:+ // both wait for a click.+ if (input.installMode === "manual-dmg" || input.installMode === "package") return false;return !["checking", "downloading", "ready", "installer-opened"].includes(input.updaterState ?? "");}diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.tsindex a399e7b0..ce5df783 100644--- a/apps/app/src/i18n/locales/en.ts+++ b/apps/app/src/i18n/locales/en.ts@@ -1819,6 +1819,12 @@ export default {"settings.update_check_failed": "Couldn't check for updates","settings.update_checking": "Checking for updates…","settings.update_download_button": "Download",+ "settings.update_download_package_button": "Download {kind}",+ "settings.update_copy_command_button": "Copy install command",+ "settings.update_open_download_page_button": "Open download page",+ "settings.update_install_version_button": "Install {version}",+ "settings.update_package_title": "Install version {version}",+ "settings.update_package_hint": "This copy was installed with your package manager, so it updates the same way. Run this command in a terminal, then open the app again.","settings.update_download_failed": "Couldn't download the update","settings.update_downloading": "Downloading update…","settings.update_restart_button": "Restart to update",@@ -1830,7 +1836,7 @@ export default {"settings.update_install_button": "Install & restart","settings.update_open_installer_button": "Open installer","settings.update_installer_opened": "Installer opened. Drag omnirush.ai to Applications, replace the old copy, then reopen it.",- "settings.update_manual_install_hint": "This build is not signed with a Developer ID, so it cannot replace itself. The installer opens and omnirush.ai quits.",+ "settings.update_manual_install_hint": "This copy runs from a read-only location (opened from Downloads), so it cannot replace itself. The installer opens and omnirush.ai quits.","settings.update_open_installer_now_title": "Open the installer?","settings.update_open_installer_now_message": "{appName} will quit and the installer will open. Drag omnirush.ai to Applications, replace the old copy, then reopen it.","settings.update_install_failed": "Couldn't install the update",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 6b2cd0cc..451cda1b 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@@ -18,7 +18,9 @@ import { Switch } from "@/components/ui/switch";import { formatBytes, formatRelativeTime } from "../../../../app/utils";import { t } from "../../../../i18n";import type { ReleaseChannel } from "../../../../app/types";-import type { UpdaterInstallMode } from "../../../../app/lib/desktop";+import type { UpdaterInstallMode, UpdaterPackageKind } from "../../../../app/lib/desktop";+import { useUpdateGateStore } from "../../../../app/lib/update-gate";+import { InstallCommand } from "../../../shell/install-command";import type { SettingsUpdateStatus } from "../state/electron-updater-state";import {LayoutSectionItem,@@ -89,13 +91,18 @@ export type UpdatesViewProps = {*/alphaChannelSupported?: boolean;/**- * How the shell applies a downloaded update. "manual-dmg" (macOS builds- * without a Developer ID signature) opens the installer instead of- * restarting in place, so the buttons say so.+ * How the shell applies a downloaded update. "manual-dmg" (a macOS copy+ * that cannot be replaced) opens the installer, and "package" (a .deb,+ * .rpm or .pacman install) downloads the package and shows the command+ * that installs it, so the buttons say so.*/installMode?: UpdaterInstallMode | null;+ packageKind?: UpdaterPackageKind | null;+ showDownloadedUpdate?: () => void;};+const PACKAGE_LABELS: Record<UpdaterPackageKind, string> = { deb: ".deb", rpm: ".rpm", pacman: ".pacman", appimage: "AppImage" };+export function UpdatesView(props: UpdatesViewProps) {const [confirmRestartOpen, setConfirmRestartOpen] = useState(false);const updateState = props.updateStatus?.state ?? "idle";@@ -112,6 +119,10 @@ export function UpdatesView(props: UpdatesViewProps) {: t("settings.update_check_failed");const updateNotes = props.updateStatus?.notes ?? null;const manualInstall = props.installMode === "manual-dmg";+ const packageInstall = props.installMode === "package";+ const packageLabel = props.packageKind ? PACKAGE_LABELS[props.packageKind] : null;+ const installCommand = packageInstall ? props.updateStatus?.installCommand ?? null : null;+ const downloadPageUrl = useUpdateGateStore((store) => store.state.downloadUrl);const installButtonLabel = manualInstall? t("settings.update_open_installer_button"): t("settings.update_install_button");@@ -168,17 +179,36 @@ export function UpdatesView(props: UpdatesViewProps) {{t("settings.update_check_button")}</Button>- {updateState === "available" ? (+ {updateState === "available" && packageInstall && !packageLabel ? (+ // A tar.gz install: the feed has no package for it.+ <Button+ variant="secondary"+ onClick={() => void window.__OMNIRUSH_ELECTRON__?.shell?.openExternal?.(downloadPageUrl)}+ disabled={props.busy}+ >+ {t("settings.update_open_download_page_button")}+ </Button>+ ) : updateState === "available" ? (<Buttonvariant="secondary"onClick={() => void props.downloadUpdate()}disabled={props.busy}>- {t("settings.update_download_button")}+ {packageLabel+ ? t("settings.update_download_package_button", undefined, { kind: packageLabel })+ : t("settings.update_download_button")}</Button>) : null}- {updateState === "ready" ? (+ {updateState === "ready" && installCommand ? (+ <Button+ variant="secondary"+ onClick={() => void navigator.clipboard?.writeText(installCommand)}+ disabled={props.busy}+ >+ {t("settings.update_copy_command_button")}+ </Button>+ ) : updateState === "ready" && !packageInstall ? (<Buttonvariant="secondary"onClick={() => {@@ -215,6 +245,13 @@ export function UpdatesView(props: UpdatesViewProps) {</Alert>) : null}+ {updateState === "ready" && installCommand ? (+ <div>+ <p className="text-sm text-muted-foreground">{t("settings.update_package_hint")}</p>+ <InstallCommand command={installCommand} onShowFile={props.showDownloadedUpdate ?? null} tone="light" />+ </div>+ ) : null}+{updateState === "ready" && manualInstall ? (<Alert><Info />diff --git a/apps/app/src/react-app/domains/settings/state/desktop-updater-provider.tsx b/apps/app/src/react-app/domains/settings/state/desktop-updater-provider.tsxindex e1515a05..1ad7bba3 100644--- a/apps/app/src/react-app/domains/settings/state/desktop-updater-provider.tsx+++ b/apps/app/src/react-app/domains/settings/state/desktop-updater-provider.tsx@@ -10,6 +10,7 @@ import { useDesktopConfig } from "../../cloud/desktop-config-provider";import { useBrandAppName } from "../../cloud/brand-theme";import { notifyAlert } from "../../../shell/notifications";import { useElectronUpdaterState } from "./electron-updater-state";+import { InstallCommand } from "../../../shell/install-command";function useUpdatePreference(key: string) {const [enabled, setEnabled] = useState(() => {@@ -65,15 +66,53 @@ export function DesktopUpdaterProvider({ children }: { children: ReactNode }) {return <DesktopUpdaterContext.Provider value={updater}>{children}</DesktopUpdaterContext.Provider>;}+function PackageUpdateButton(props: { command: string; version: string; onShowFile: () => void }) {+ const [open, setOpen] = useState(false);+ return (+ <>+ <Button+ variant="ghost"+ size="sm"+ data-update-button+ onClick={() => setOpen(true)}+ className="mac:titlebar-no-drag h-7 gap-1.5 rounded-lg border border-foreground/[0.06] bg-foreground/[0.04] px-2.5 text-xs font-medium text-foreground/80 shadow-none transition-colors hover:bg-foreground/[0.08] hover:text-foreground"+ >+ <RotateCw className="size-3.5 opacity-70" strokeWidth={1.75} aria-hidden="true" />+ {t("settings.update_install_version_button", undefined, { version: props.version })}+ </Button>+ <AlertDialog open={open} onOpenChange={setOpen}>+ <AlertDialogContent className="max-w-[420px] gap-0 rounded-[15px] border border-border p-6 ring-0 sm:max-w-[420px]">+ <AlertDialogTitle className="mb-2 text-[19px] leading-tight tracking-tight">+ {t("settings.update_package_title", undefined, { version: props.version })}+ </AlertDialogTitle>+ <AlertDialogDescription className="text-xs leading-[1.75]">{t("settings.update_package_hint")}</AlertDialogDescription>+ <InstallCommand command={props.command} onShowFile={props.onShowFile} tone="light" />+ <AlertDialogFooter className="mt-5">+ <AlertDialogCancel variant="ghost" size="sm" className="rounded-[7px] text-[11px] text-muted-foreground">{t("settings.update_keep_working")}</AlertDialogCancel>+ <AlertDialogAction size="sm" className="rounded-[7px] text-[11px]" onClick={() => {+ void navigator.clipboard?.writeText(props.command);+ setOpen(false);+ }}>{t("settings.update_copy_command_button")}</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}+export function DesktopUpdateButton() {const updater = useContext(DesktopUpdaterContext);const appName = useBrandAppName();const [confirmRestart, setConfirmRestart] = useState(false);if (updater?.updateStatus?.state !== "ready") return null;- // macOS builds without a Developer ID signature cannot swap themselves:- // the shell opens the downloaded DMG and quits, so say that instead of- // promising a restart.+ // A macOS copy that cannot be replaced opens the downloaded DMG and quits,+ // so say that instead of promising a restart.const manualInstall = updater.installMode === "manual-dmg";+ // A .deb/.rpm/.pacman install: the package manager installs it.+ const installCommand = updater.installMode === "package" ? updater.updateStatus.installCommand ?? null : null;+ if (installCommand) {+ return <PackageUpdateButton command={installCommand} version={updater.updateStatus.version ?? ""} onShowFile={updater.showDownloadedUpdate} />;+ }return (<><Tooltip>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 5224049a..d89f7598 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@@ -2,7 +2,8 @@import { useCallback, useEffect, useReducer, useRef, useState } from "react";import { isDenControlPlaneConfigured, type DenDesktopConfig } from "../../../../app/lib/den";-import type { UpdaterInstallMode } from "../../../../app/lib/desktop";+import type { UpdaterInstallMode, UpdaterPackageKind } from "../../../../app/lib/desktop";+import { useUpdateGateStore } from "../../../../app/lib/update-gate";import {isAlphaChannelAllowedByDesktopConfig,isAlphaUpdateAllowed,@@ -27,6 +28,11 @@ export type SettingsUpdateStatus = {downloadedBytes?: number;message?: string;failedAction?: "check" | "download" | "install";+ /** "package" installs: the downloaded package and the command that installs it. */+ installerPath?: string | null;+ installCommand?: string | null;+ /** The app is quitting to install the update. */+ restarting?: boolean;} | null;type ElectronUpdaterBridge = NonNullable<Window["__OMNIRUSH_ELECTRON__"]>["updater"] & {@@ -54,6 +60,8 @@ export type ElectronUpdaterEnvState = {updateEnv: { supported?: boolean; reason?: string | null } | null;/** How the shell applies updates; null until the bridge reports it. */installMode: UpdaterInstallMode | null;+ /** "package" installs: which package the feed offers (null: none, e.g. a tar.gz install). */+ packageKind: UpdaterPackageKind | null;/*** Whether this distribution ships an Alpha feed. null until the bridge* reports it so a stored Alpha preference is not rewritten before we know.@@ -68,10 +76,22 @@ export function unsupportedElectronUpdaterEnvState(): ElectronUpdaterEnvState {appVersion: null,updateEnv: { supported: false, reason: ELECTRON_UPDATER_UNSUPPORTED_REASON },installMode: null,+ packageKind: null,alphaChannelSupported: null,};}+/**+ * Whether a check may start the download by itself. A package lands in the+ * user's Downloads folder, so that one waits for a click.+ */+export function downloadsAutomatically(input: {+ updateAutoDownload: boolean;+ installMode: UpdaterInstallMode | null;+}): boolean {+ return input.updateAutoDownload && input.installMode !== "package";+}+export function shouldScheduleElectronUpdateAutoCheck(input: {updateAutoCheck: boolean;updateEnv: ElectronUpdaterEnvState["updateEnv"];@@ -109,7 +129,7 @@ export function keepsReadyUpdate(input: {type ElectronUpdaterEnvAction =| { type: "app-version"; appVersion: string | null }- | { type: "capabilities"; installMode?: UpdaterInstallMode | null; alphaChannelSupported?: boolean | null }+ | { type: "capabilities"; installMode?: UpdaterInstallMode | null; packageKind?: UpdaterPackageKind | null; alphaChannelSupported?: boolean | null }| { type: "unsupported"; reason: string };function electronUpdaterEnvReducer(@@ -121,9 +141,14 @@ function electronUpdaterEnvReducer(return { ...state, appVersion: action.appVersion };case "capabilities": {const installMode = action.installMode ?? state.installMode;+ const packageKind = action.packageKind !== undefined ? action.packageKind : state.packageKind;const alphaChannelSupported = action.alphaChannelSupported ?? state.alphaChannelSupported;- if (installMode === state.installMode && alphaChannelSupported === state.alphaChannelSupported) return state;- return { ...state, installMode, alphaChannelSupported };+ if (+ installMode === state.installMode+ && packageKind === state.packageKind+ && alphaChannelSupported === state.alphaChannelSupported+ ) return state;+ return { ...state, installMode, packageKind, alphaChannelSupported };}case "unsupported":return {@@ -133,17 +158,31 @@ function electronUpdaterEnvReducer(}}+const INSTALL_MODES: readonly UpdaterInstallMode[] = ["in-place", "manual-dmg", "package"];+const PACKAGE_KINDS: readonly UpdaterPackageKind[] = ["deb", "rpm", "pacman", "appimage"];+function capabilitiesFromBridge(state: {installMode?: UpdaterInstallMode;+ packageKind?: UpdaterPackageKind | null;alphaChannelSupported?: boolean;} | null | undefined): ElectronUpdaterEnvAction {+ const installMode = state?.installMode && INSTALL_MODES.includes(state.installMode) ? state.installMode : null;return {type: "capabilities",- installMode: state?.installMode === "manual-dmg" || state?.installMode === "in-place" ? state.installMode : null,+ installMode,+ // Only a package install reports a kind; leave it alone otherwise.+ ...(installMode === "package"+ ? { packageKind: state?.packageKind && PACKAGE_KINDS.includes(state.packageKind) ? state.packageKind : null }+ : {}),alphaChannelSupported: typeof state?.alphaChannelSupported === "boolean" ? state.alphaChannelSupported : null,};}+/** Where "Open download page" goes: the server's download_url while an update is required. */+function downloadPageUrl(): string {+ return useUpdateGateStore.getState().state.downloadUrl;+}+function electronUpdaterBridge(): ElectronUpdaterBridge | null {if (typeof window === "undefined") return null;if (import.meta.env.DEV && window.__omnirushUpdaterEvalBridge) {@@ -218,9 +257,12 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)? null: { supported: false, reason: ELECTRON_UPDATER_UNSUPPORTED_REASON },installMode: null,+ packageKind: null,alphaChannelSupported: null,});- const { appVersion, updateEnv, installMode, alphaChannelSupported } = envState;+ const { appVersion, updateEnv, installMode, packageKind, alphaChannelSupported } = envState;+ const installModeRef = useRef(installMode);+ installModeRef.current = installMode;const updateStatusRef = useRef(updateStatus);updateStatusRef.current = updateStatus;const lastAutoCheckAtRef = useRef(0);@@ -399,7 +441,7 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)});return;}- dispatchEnvState(capabilitiesFromBridge({ installMode: result.mode }));+ dispatchEnvState(capabilitiesFromBridge({ installMode: result.mode, packageKind: result.packageKind }));if (releaseChannelResolution.channel === "alpha" &&!isAlphaChannelAllowedByDesktopConfig(desktopConfigRef.current)@@ -416,6 +458,8 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)setUpdateStatus((current) => ({...(current ?? {}),state: "ready",+ installerPath: result.mode === "package" ? result.path ?? null : null,+ installCommand: result.mode === "package" ? result.command ?? null : null,}));} catch (error) {if (!isCurrentReleaseChannel()) return;@@ -609,7 +653,7 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions): null;downloadedReleaseChannelRef.current = null;setUpdateStatus(nextStatus);- if (availableAllowed && updateAutoDownload) {+ if (availableAllowed && downloadsAutomatically({ updateAutoDownload, installMode: result.installMode ?? installModeRef.current })) {await downloadUpdate(checkedReleaseChannel);}} catch (error) {@@ -705,13 +749,30 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)await runCheckForUpdates(undefined, true);return;}+ const reason = result?.reason ? stripRemoteMethodErrorPrefix(result.reason) : "Update install failed.";+ 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+ // the message says so.+ void window.__OMNIRUSH_ELECTRON__?.shell?.openExternal?.(downloadPageUrl());+ setUpdateStatus((current) => ({+ ...(current ?? {}),+ state: "error",+ message: `${reason} The download page is open in your browser.`,+ failedAction: "install",+ }));+ return;+ }setUpdateStatus({state: "error",- message: result?.reason ? stripRemoteMethodErrorPrefix(result.reason) : "Update install failed.",+ message: reason,failedAction: "install",});return;}+ if (result.mode === "in-place") {+ setUpdateStatus((current) => ({ ...(current ?? {}), state: "ready", restarting: true }));+ }if (result.mode === "manual-dmg") {// The shell opened the DMG and quits shortly; leave the instructions// on screen instead of a stale "Ready to install" button.@@ -763,10 +824,16 @@ export function useElectronUpdaterState(options: UseElectronUpdaterStateOptions)[checkForUpdates, onReleaseChannelChange, resolvePolicyReleaseChannel],);+ const showDownloadedUpdate = useCallback(() => {+ void electronUpdaterBridge()?.showDownloaded?.();+ }, []);+return {appVersion,updateEnv,installMode,+ packageKind,+ showDownloadedUpdate,alphaChannelSupported: alphaChannelSupported === true,updateStatus,checkForUpdates,diff --git a/apps/app/src/react-app/shell/install-command.tsx b/apps/app/src/react-app/shell/install-command.tsxnew file mode 100644index 00000000..17520f6b--- /dev/null+++ b/apps/app/src/react-app/shell/install-command.tsx@@ -0,0 +1,25 @@+/** @jsxImportSource react */++/** The command that installs a downloaded package, with the package's folder one click away. */+export function InstallCommand(props: { command: string; onShowFile?: (() => void) | null; tone?: "dark" | "light" }) {+ const dark = props.tone !== "light";+ return (+ <div data-testid="update-install-command" className="mt-4 w-full">+ <pre className={dark+ ? "overflow-x-auto rounded-xl border border-white/10 bg-black/40 px-3 py-2 font-mono text-xs text-emerald-100 select-text"+ : "overflow-x-auto rounded-lg border border-border bg-muted px-3 py-2 font-mono text-xs text-foreground select-text"}+ >{props.command}</pre>+ {props.onShowFile ? (+ <button+ type="button"+ onClick={props.onShowFile}+ className={dark+ ? "mt-2 text-xs font-medium text-white/60 underline-offset-4 hover:text-white hover:underline mac:titlebar-no-drag"+ : "mt-2 text-xs font-medium text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"}+ >+ Show the downloaded file+ </button>+ ) : null}+ </div>+ );+}diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsxindex 4941c5ca..c7e92205 100644--- a/apps/app/src/react-app/shell/settings-route.tsx+++ b/apps/app/src/react-app/shell/settings-route.tsx@@ -2595,6 +2595,8 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {desktopConfig.config.allowAlphaUpdates !== false}installMode={electronUpdaterState.installMode}+ packageKind={electronUpdaterState.packageKind}+ showDownloadedUpdate={electronUpdaterState.showDownloadedUpdate}/>);case "environment":diff --git a/apps/app/src/react-app/shell/update-gate.tsx b/apps/app/src/react-app/shell/update-gate.tsxindex 32b162ec..9d22bfb4 100644--- a/apps/app/src/react-app/shell/update-gate.tsx+++ b/apps/app/src/react-app/shell/update-gate.tsx@@ -8,11 +8,13 @@ import {requiredUpdateAction,shouldStartBackgroundDownload,updateBannerText,+ updateButtonLabel,useUpdateGateState,type UpdateGateState,} from "../../app/lib/update-gate";import { useBrandAppName } from "../domains/cloud/brand-theme";import { useDesktopUpdater } from "../domains/settings/state/desktop-updater-provider";+import { InstallCommand } from "./install-command";/** Height of the required-update banner; the app below it is shifted by this much. */const BANNER_HEIGHT_PX = 36;@@ -34,17 +36,22 @@ function openDownload(url: string) {/*** Starts the update download in the background as soon as an update is- * required, and runs "Update now": install the staged update (electron-updater- * quitAndInstall on Linux, Windows and Developer ID macOS), or open- * `download_url` where the app cannot replace itself (ad-hoc signed macOS- * builds, no updater, a failed download).+ * required, and runs "Update now": restart into the staged update wherever+ * the app can replace itself (Linux AppImage, Windows, macOS with or without+ * a Developer ID signature), download the package and show its install+ * command for a .deb/.rpm/.pacman install, and open `download_url` only from+ * a button that says so. A failed check or download is shown and retried+ * from the button, never answered by opening a browser.*/function useRequiredUpdate(gate: UpdateGateState) {const updater = useDesktopUpdater();const supported = updater.updateEnv?.supported !== false && Boolean(updater.appVersion);const installMode = updater.installMode;- const updaterState = updater.updateStatus?.state ?? null;+ const packageKind = updater.packageKind;+ const status = updater.updateStatus;+ const updaterState = status?.state ?? null;const [installRequested, setInstallRequested] = useState(false);+ const [copied, setCopied] = useState(false);const backgroundStarted = useRef(false);const downloadRequested = useRef(false);@@ -63,96 +70,117 @@ function useRequiredUpdate(gate: UpdateGateState) {}, [gate, installMode, supported, updater, updaterState]);useEffect(() => {- if (gate.status === "none" || installMode === "manual-dmg") return;+ if (gate.status === "none" || installMode !== "in-place") return;if (updaterState === "available" && !downloadRequested.current) {downloadRequested.current = true;void updater.downloadUpdate();}}, [gate.status, installMode, updater, updaterState]);- // After "Update now": install once the download is ready; where it cannot- // be (the check found nothing, the download failed, policy holds it back),- // open download_url instead.- const previousState = useRef(updaterState);+ // After "Update now": restart once the download is ready. A failure ends+ // the request; the detail line says what went wrong and the button retries.const installDownloadStarted = useRef(false);useEffect(() => {- const previous = previousState.current;- previousState.current = updaterState;if (!installRequested) return;- const finish = (next: () => void) => {+ const finish = (next?: () => void) => {setInstallRequested(false);installDownloadStarted.current = false;- next();+ next?.();};- if (!supported || installMode === "manual-dmg") return finish(() => openDownload(gate.downloadUrl));- if (updaterState === "ready") return finish(() => void updater.installUpdateAndRestart());+ if (updaterState === "ready") {+ return finish(installMode === "in-place" ? () => void updater.installUpdateAndRestart() : undefined);+ }if (updaterState === "available" && !installDownloadStarted.current) {installDownloadStarted.current = true;void updater.downloadUpdate();return;}- const failed = previous !== updaterState- && (updaterState === "error" || updaterState === "blocked" || updaterState === "installer-opened");- const nothingFound = previous === "checking" && (updaterState === "idle" || updaterState === null);- if (failed || nothingFound) finish(() => openDownload(gate.downloadUrl));- }, [gate.downloadUrl, installMode, installRequested, supported, updater, updaterState]);+ if (updaterState === "error" || updaterState === "blocked" || updaterState === "installer-opened") finish();+ }, [installMode, installRequested, updater, updaterState]);++ const action = requiredUpdateAction({ supported, installMode, updaterState, packageKind });const updateNow = useCallback(() => {- const action = requiredUpdateAction({ supported, installMode, updaterState });- if (action === "open-download") {- openDownload(gate.downloadUrl);- return;- }- if (action === "install") {- void updater.installUpdateAndRestart();- return;- }- installDownloadStarted.current = false;- setInstallRequested(true);- if (action === "download-then-install") {- if (updaterState === "available") {- installDownloadStarted.current = true;- void updater.downloadUpdate();- } else {- void updater.checkForUpdates();+ switch (action) {+ case "open-download":+ openDownload(gate.downloadUrl);+ return;+ case "install":+ void updater.installUpdateAndRestart();+ return;+ case "copy-command": {+ const command = status?.installCommand;+ if (command) {+ void navigator.clipboard?.writeText(command).then(() => setCopied(true)).catch(() => undefined);+ }+ return;}+ case "wait":+ setInstallRequested(true);+ return;+ default:+ installDownloadStarted.current = false;+ setInstallRequested(true);+ if (updaterState === "available") {+ installDownloadStarted.current = true;+ void updater.downloadUpdate();+ } else {+ void updater.checkForUpdates();+ }}- }, [gate.downloadUrl, installMode, supported, updater, updaterState]);+ }, [action, gate.downloadUrl, status?.installCommand, updater, updaterState]);++ useEffect(() => {+ if (!copied) return;+ const timer = window.setTimeout(() => setCopied(false), 2_000);+ return () => window.clearTimeout(timer);+ }, [copied]);- const progress = updater.updateStatus?.state === "downloading" && updater.updateStatus.totalBytes- ? Math.min(100, Math.round(((updater.updateStatus.downloadedBytes ?? 0) / updater.updateStatus.totalBytes) * 100))+ const progress = updaterState === "downloading" && status?.totalBytes+ ? Math.min(100, Math.round(((status.downloadedBytes ?? 0) / status.totalBytes) * 100)): null;- const working = installRequested && (updaterState === "checking" || updaterState === "downloading" || updaterState === "available" || updaterState === "idle");- const detail = updaterState === "downloading"- ? progress === null ? "Downloading the update…" : `Downloading the update… ${progress}%`- : updaterState === "ready"- ? "The update is downloaded and ready to install."- : updaterState === "installer-opened"- ? "The installer is open. Replace the app from it, then open it again."- : null;- return { updateNow, working, detail };+ const version = status?.version ?? gate.minimum;+ const label = copied+ ? "Copied"+ : updateButtonLabel({ action, version, progress, updaterState, packageKind, restarting: status?.restarting });+ const working = action === "wait" || Boolean(status?.restarting);+ const detail = updaterState === "error" && status?.message+ ? `The update did not finish: ${status.message}`+ : updaterState === "ready" && installMode === "package" && status?.installCommand+ ? "Downloaded. Run the install command in a terminal, then open the app again."+ : updaterState === "ready" && installMode === "in-place" && !status?.restarting+ ? "Downloaded. The app closes and reopens on the new version."+ : updaterState === "installer-opened"+ ? "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 };}-function UpdateNowButton(props: { onClick: () => void; working: boolean; large?: boolean; testId: string }) {+type RequiredUpdate = ReturnType<typeof useRequiredUpdate>;++function UpdateNowButton(props: { update: RequiredUpdate; large?: boolean; testId: string }) {+ const { update } = props;return (<buttontype="button"data-testid={props.testId}- onClick={props.onClick}- disabled={props.working}+ onClick={update.updateNow}+ disabled={update.working}className={props.large? "inline-flex items-center justify-center gap-2 rounded-full bg-white px-6 py-3 text-sm font-semibold text-black transition hover:bg-emerald-100 disabled:cursor-wait disabled:opacity-80 mac:titlebar-no-drag": "inline-flex h-6 shrink-0 items-center gap-1.5 rounded-md bg-black/85 px-2.5 text-[11px] font-semibold text-amber-50 transition hover:bg-black disabled:cursor-wait disabled:opacity-80 mac:titlebar-no-drag"}>- {props.working ? <Loader2 className={props.large ? "size-4 animate-spin" : "size-3 animate-spin"} aria-hidden="true" /> : <Download className={props.large ? "size-4" : "size-3"} aria-hidden="true" />}- Update now+ {update.working ? <Loader2 className={props.large ? "size-4 animate-spin" : "size-3 animate-spin"} aria-hidden="true" /> : <Download className={props.large ? "size-4" : "size-3"} aria-hidden="true" />}+ {update.label}</button>);}-export function RequiredUpdateBanner(props: { gate: UpdateGateState; appName: string; onUpdateNow: () => void; working: boolean; detail: string | null }) {+export function RequiredUpdateBanner(props: { gate: UpdateGateState; appName: string; update: RequiredUpdate }) {const now = useNow(true);const text = updateBannerText(props.gate, props.appName, now);+ const detail = props.update.command ?? props.update.detail;return (<divrole="alert"@@ -164,14 +192,14 @@ export function RequiredUpdateBanner(props: { gate: UpdateGateState; appName: st><ArrowUpCircle className="size-4 shrink-0" aria-hidden="true" /><span className="truncate" data-testid="update-required-banner-text">{text}</span>- {props.detail ? <span className="hidden truncate text-amber-900/80 md:inline">· {props.detail}</span> : null}- <UpdateNowButton onClick={props.onUpdateNow} working={props.working} testId="update-required-banner-button" />+ {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" /></div>);}-export function UpdateRequiredView(props: { gate: UpdateGateState; appName: string; onUpdateNow: () => void; working: boolean; detail: string | null }) {- const { gate, appName } = props;+export function UpdateRequiredView(props: { gate: UpdateGateState; appName: string; update: RequiredUpdate }) {+ const { gate, appName, update } = props;return (<mainrole="alertdialog"@@ -204,16 +232,17 @@ export function UpdateRequiredView(props: { gate: UpdateGateState; appName: stri</div></div><div className="mt-8 flex flex-col items-start gap-3 sm:flex-row sm:items-center">- <UpdateNowButton onClick={props.onUpdateNow} working={props.working} large testId="update-required-button" />+ <UpdateNowButton update={update} large testId="update-required-button" /><buttontype="button"onClick={() => openDownload(gate.downloadUrl)}className="text-sm font-medium text-white/60 underline-offset-4 hover:text-white hover:underline mac:titlebar-no-drag">- Download from omnirush.ai+ Open the download page instead</button></div>- {props.detail ? <p className="mt-4 text-sm text-white/60" data-testid="update-required-detail">{props.detail}</p> : null}+ {update.command ? <InstallCommand command={update.command} onShowFile={update.showDownloaded} /> : null}+ {update.detail ? <p className="mt-4 text-sm text-white/60" data-testid="update-required-detail">{update.detail}</p> : null}</section></main>);@@ -231,7 +260,7 @@ export function UpdateGate({ children }: { children: ReactNode }) {// The product name as the release names it, unless an organization brands the app.const brandName = useBrandAppName();const appName = brandName === "omnirush.ai" ? "OmniRush.ai" : brandName;- const { updateNow, working, detail } = useRequiredUpdate(gate);+ const update = useRequiredUpdate(gate);useEffect(() => {connectUpdateGate();@@ -248,7 +277,7 @@ export function UpdateGate({ children }: { children: ReactNode }) {const banner = gate.status === "required";return (<>- {banner ? <RequiredUpdateBanner gate={gate} appName={appName} onUpdateNow={updateNow} working={working} detail={detail} /> : null}+ {banner ? <RequiredUpdateBanner gate={gate} appName={appName} update={update} /> : null}<divdata-update-gate-shifted={banner ? "" : undefined}style={banner@@ -257,7 +286,7 @@ export function UpdateGate({ children }: { children: ReactNode }) {>{children}</div>- {gate.status === "blocked" ? <UpdateRequiredView gate={gate} appName={appName} onUpdateNow={updateNow} working={working} detail={detail} /> : null}+ {gate.status === "blocked" ? <UpdateRequiredView gate={gate} appName={appName} update={update} /> : null}</>);}diff --git a/apps/app/tests/update-gate.test.tsx b/apps/app/tests/update-gate.test.tsxindex 7be61cbd..a46569e5 100644--- a/apps/app/tests/update-gate.test.tsx+++ b/apps/app/tests/update-gate.test.tsx@@ -11,6 +11,7 @@ import {requiredUpdateAction,shouldStartBackgroundDownload,updateBannerText,+ updateButtonLabel,useUpdateGateStore,type UpdateGateState,} from "../src/app/lib/update-gate";@@ -30,6 +31,18 @@ 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 }> = {}) {+ return {+ updateNow: () => undefined,+ working: false,+ detail: null,+ label: "Update and restart",+ command: null,+ showDownloaded: () => undefined,+ ...over,+ };+}+describe("update gate state from the desktop bridge", () => {test("normalizes the main-process state and rejects anything malformed", () => {expect(normalizeUpdateGateState(required)).toEqual(required);@@ -61,22 +74,22 @@ describe("required-update banner", () => {expect(updateBannerText({ ...required, minimum: null, deadline: null }, "OmniRush.ai", NOW)).toBe("A newer OmniRush.ai is required");});- test("renders the countdown and an Update now button, with no way to dismiss it", () => {+ test("renders the countdown and a button that says what it does, with no way to dismiss it", () => {const html = renderToStaticMarkup(- <RequiredUpdateBanner gate={required} appName="OmniRush.ai" onUpdateNow={() => undefined} working={false} detail={null} />,+ <RequiredUpdateBanner gate={required} appName="OmniRush.ai" update={fakeUpdate({ label: "Restart to update" })} />,);expect(html).toContain("data-testid=\"update-required-banner\"");expect(html).toMatch(/OmniRush\.ai 3\.1\.0 is required in \d+(d \d+h|h \d+m|m)|less than a minute/);- expect(html).toContain("Update now");+ expect(html).toContain("Restart to update");expect(html.toLowerCase()).not.toContain("dismiss");expect(html).not.toContain("aria-label=\"Close\"");});});describe("blocked view", () => {- test("is full-screen, shows the server message and both versions, and offers Update now", () => {+ test("is full-screen, shows the server message, both versions and the download progress", () => {const html = renderToStaticMarkup(- <UpdateRequiredView gate={blocked} appName="OmniRush.ai" onUpdateNow={() => undefined} working={false} detail="Downloading the update… 40%" />,+ <UpdateRequiredView gate={blocked} appName="OmniRush.ai" update={fakeUpdate({ label: "Downloading 3.1.1… 40%", working: true })} />,);expect(html).toContain("data-testid=\"update-required-view\"");expect(html).toContain("fixed inset-0");@@ -84,29 +97,68 @@ describe("blocked view", () => {expect(html).toContain(blocked.message!);expect(html).toContain(">3.0.2<");expect(html).toContain(">3.1.0<");- expect(html).toContain("Update now");+ expect(html).toContain("Downloading 3.1.1… 40%");expect(html).toContain("keep uploading in the background");- expect(html).toContain("Downloading the update… 40%");+ expect(html).toContain("Open the download page instead");+ });++ test("shows the install command for a package install", () => {+ const command = "sudo apt install /home/pat/Downloads/omnirush-linux-amd64-3.1.1.deb";+ const html = renderToStaticMarkup(+ <UpdateRequiredView gate={blocked} appName="OmniRush.ai" update={fakeUpdate({ label: "Copy install command", command })} />,+ );+ expect(html).toContain("data-testid=\"update-install-command\"");+ expect(html).toContain(command);+ expect(html).toContain("Copy install command");+ expect(html).toContain("Show the downloaded file");});});describe("Update now", () => {- test("installs a staged update in place (Linux AppImage, Windows, Developer ID macOS)", () => {+ test("installs a staged update in place (Linux AppImage, Windows, macOS signed or not)", () => {expect(requiredUpdateAction({ supported: true, installMode: "in-place", updaterState: "ready" })).toBe("install");expect(requiredUpdateAction({ supported: true, installMode: "in-place", updaterState: "available" })).toBe("download-then-install");expect(requiredUpdateAction({ supported: true, installMode: "in-place", updaterState: null })).toBe("download-then-install");expect(requiredUpdateAction({ supported: true, installMode: "in-place", updaterState: "downloading" })).toBe("wait");});- test("opens download_url where the app cannot replace itself", () => {- // Ad-hoc signed macOS builds: Squirrel cannot swap them.+ test("opens download_url only where the app cannot replace itself, and says so", () => {+ // A translocated macOS copy (run from Downloads) cannot be replaced.expect(requiredUpdateAction({ supported: true, installMode: "manual-dmg", updaterState: "ready" })).toBe("open-download");+ // A tar.gz install: no package in the feed.+ expect(requiredUpdateAction({ supported: true, installMode: "package", packageKind: null, updaterState: "available" })).toBe("open-download");+ expect(updateButtonLabel({ action: "open-download" })).toBe("Open download page");expect(requiredUpdateAction({ supported: false, installMode: null, updaterState: null })).toBe("open-download");expect(requiredUpdateAction({ supported: true, installMode: "in-place", updaterState: "blocked" })).toBe("open-download");});test("tries the download again after a failed check or download", () => {expect(requiredUpdateAction({ supported: true, installMode: "in-place", updaterState: "error" })).toBe("download-then-install");+ expect(updateButtonLabel({ action: "download-then-install", updaterState: "error" })).toBe("Try the update again");+ });++ test("a package install downloads the package and then offers its command", () => {+ const base = { supported: true, installMode: "package" as const, packageKind: "deb" };+ expect(requiredUpdateAction({ ...base, updaterState: "available" })).toBe("download-package");+ expect(requiredUpdateAction({ ...base, updaterState: "downloading" })).toBe("wait");+ expect(requiredUpdateAction({ ...base, updaterState: "ready" })).toBe("copy-command");+ expect(updateButtonLabel({ action: "download-package", version: "3.1.1", packageKind: "deb" })).toBe("Download 3.1.1 (.deb)");+ expect(updateButtonLabel({ action: "copy-command" })).toBe("Copy install command");+ });++ test("the button says what happens: progress while downloading, then restart", () => {+ expect(updateButtonLabel({ action: "wait", updaterState: "downloading", version: "3.1.1", progress: 42 })).toBe("Downloading 3.1.1… 42%");+ expect(updateButtonLabel({ action: "wait", updaterState: "checking" })).toBe("Checking for the update…");+ expect(updateButtonLabel({ action: "install" })).toBe("Restart to update");+ expect(updateButtonLabel({ action: "install", restarting: true })).toBe("Restarting…");+ expect(updateButtonLabel({ action: "download-then-install" })).toBe("Update and restart");+ });++ 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);+ expect(hook).toContain('case "open-download":\n openDownload(gate.downloadUrl);');});test("the download starts in the background as soon as an update is required", () => {@@ -117,6 +169,8 @@ describe("Update now", () => {expect(shouldStartBackgroundDownload({ ...base, gate: required, updaterState: "ready" })).toBe(false);expect(shouldStartBackgroundDownload({ ...base, gate: NO_UPDATE_GATE, updaterState: null })).toBe(false);expect(shouldStartBackgroundDownload({ supported: true, installMode: "manual-dmg", gate: required, updaterState: null })).toBe(false);+ // A package lands in Downloads: it waits for a click.+ expect(shouldStartBackgroundDownload({ supported: true, installMode: "package", gate: required, updaterState: null })).toBe(false);});});diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjsindex a5ca34da..7635f6dd 100644--- a/apps/desktop/electron/preload.mjs+++ b/apps/desktop/electron/preload.mjs@@ -159,6 +159,10 @@ contextBridge.exposeInMainWorld("__OMNIRUSH_ELECTRON__", {installAndRestart() {return ipcRenderer.invoke("omnirush:updater:installAndRestart");},+ /** Reveal a downloaded Linux package in the file manager. */+ showDownloaded() {+ return ipcRenderer.invoke("omnirush:updater:showDownloaded");+ },/** Subscribe to incremental download progress from electron-updater. */onDownloadProgress(callback) {const handler = (_event, data) => callback(data);diff --git a/apps/desktop/electron/self-install.mjs b/apps/desktop/electron/self-install.mjsnew file mode 100644index 00000000..29b0fb49--- /dev/null+++ b/apps/desktop/electron/self-install.mjs@@ -0,0 +1,349 @@+// Installs a downloaded update where electron-updater cannot, or cannot do it+// safely:+//+// - macOS builds without a Developer ID signature: Squirrel.Mac refuses to+// swap them. The release zip is downloaded and checked against the+// manifest's sha512, extracted next to the old app, and a small detached+// helper swaps the .app bundle once this process has exited, clears the+// quarantine flag and opens the new bundle.+// - Linux AppImage: the downloaded AppImage is renamed over the running one+// (the running copy keeps its open inode) and the app relaunches through+// Electron's relauncher, which waits for this process to exit. That keeps+// the file name, so desktop entries and shortcuts stay valid.+// - Linux .deb/.rpm/.pacman: the package manager owns the files, so the+// package is downloaded and the user gets the command to install it.+import { access, chmod, copyFile, mkdir, mkdtemp, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";+import { closeSync, constants as fsConstants, existsSync, mkdirSync, openSync } from "node:fs";+import { execFile, spawn } from "node:child_process";+import os from "node:os";+import path from "node:path";++/** The .app bundle that contains `appPath` (app.getAppPath() or process.execPath). */+export function macBundleFromPath(appPath) {+ const value = typeof appPath === "string" ? appPath : "";+ const marker = ".app/Contents/";+ const index = value.indexOf(marker);+ return index === -1 ? null : value.slice(0, index + ".app".length);+}++/**+ * Gatekeeper runs a quarantined app opened from Downloads from a read-only+ * random mount (App Translocation). Replacing that copy would change nothing.+ */+export function isTranslocatedBundle(bundlePath) {+ return typeof bundlePath === "string" && bundlePath.includes("/AppTranslocation/");+}++export async function isWritable(target) {+ try {+ await access(target, fsConstants.W_OK);+ return true;+ } catch {+ return false;+ }+}++/** Whether this user can rename `target` (a file or a bundle) inside its folder. */+export async function canReplaceInPlace(target) {+ return (await isWritable(path.dirname(target))) && (await isWritable(target));+}++/** The running AppImage from $APPIMAGE, or null outside an AppImage. */+export function linuxAppImagePath(env = process.env) {+ const value = typeof env?.APPIMAGE === "string" ? env.APPIMAGE.trim() : "";+ return value && path.isAbsolute(value) ? path.resolve(value) : null;+}++/** electron-builder writes resources/package-type for deb, rpm and pacman builds. */+export async function linuxPackageType(resourcesPath, read = readFile) {+ if (!resourcesPath) return null;+ try {+ const value = String(await read(path.join(resourcesPath, "package-type"), "utf8")).trim();+ return value === "deb" || value === "rpm" || value === "pacman" ? value : null;+ } catch {+ return null;+ }+}++const PACKAGE_EXTENSIONS = { deb: ".deb", rpm: ".rpm", pacman: ".pacman", appimage: ".AppImage" };++export function packageExtension(kind) {+ return PACKAGE_EXTENSIONS[kind] ?? null;+}++export function shellQuote(value) {+ const text = String(value);+ return /^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`;+}++/**+ * The command that installs a downloaded Linux package. `target` is the+ * AppImage to replace when its folder needs root (an AppImage in /opt).+ */+export function linuxInstallCommand(kind, filePath, target = null) {+ const file = shellQuote(filePath);+ switch (kind) {+ case "deb":+ return `sudo apt install ${file}`;+ case "rpm":+ return `sudo dnf install ${file}`;+ case "pacman":+ return `sudo pacman -U ${file}`;+ case "appimage":+ return target ? `sudo install -m 755 ${file} ${shellQuote(target)}` : null;+ default:+ return null;+ }+}++/**+ * Replaces the AppImage at `target` with `source`. The copy lands next to the+ * target first and is renamed over it, so the running AppImage (mounted from+ * the old inode) keeps working and a failed copy never leaves a broken file.+ */+export async function replaceAppImage({ source, target }) {+ if (!source || !target) throw new Error("No downloaded AppImage to install.");+ const staged = `${target}.update-${process.pid}`;+ try {+ await copyFile(source, staged);+ await chmod(staged, 0o755);+ await rename(staged, target);+ } catch (error) {+ await rm(staged, { force: true }).catch(() => undefined);+ throw error;+ }+ await rm(source, { force: true }).catch(() => undefined);+ return target;+}++/**+ * The environment for a process started outside this AppImage: without the+ * runtime's variables and anything pointing into its mount, which is gone+ * once this process exits.+ */+/** @param {Record<string, string | undefined>} [env] */+export function environmentOutsideAppImage(env = process.env) {+ const appDir = typeof env.APPDIR === "string" && env.APPDIR ? env.APPDIR : null;+ /** @type {Record<string, string | undefined>} */+ const clean = {};+ for (const [key, value] of Object.entries(env)) {+ // The CDP port this copy chose: the new one probes for a free port again.+ if (["APPDIR", "APPIMAGE", "ARGV0", "OWD", "OMNIRUSH_ELECTRON_REMOTE_DEBUG_PORT"].includes(key)) continue;+ if (appDir && typeof value === "string" && value.includes(appDir)) {+ // PATH-like lists keep their other entries.+ const rest = value.split(":").filter((entry) => entry && !entry.includes(appDir));+ if (rest.length) clean[key] = rest.join(":");+ continue;+ }+ clean[key] = value;+ }+ return clean;+}++/**+ * Reopens `appImage` once process `pid` has exited. A small shell outside+ * the AppImage waits, so neither the single-instance lock nor the runtime+ * unmounting this copy can stop the new one (Electron's own relauncher runs+ * from inside the mount that goes away).+ *+ * @param {{+ * appImage: string,+ * pid?: number,+ * runtimePid?: number,+ * args?: string[],+ * env?: Record<string, string | undefined>,+ * logPath?: string | null,+ * spawnProcess?: (command: string, args: string[], options: import("node:child_process").SpawnOptions) => { unref?: () => void },+ * }} options+ */+export function relaunchAppImageAfterExit({+ appImage,+ pid = process.pid,+ runtimePid = process.ppid,+ args = [],+ env = process.env,+ logPath = null,+ spawnProcess = spawn,+}) {+ const bash = existsSync("/bin/bash");+ const script = [+ // Descriptors inherited from this app (the AppImage runtime's keep-alive+ // pipe, listening sockets) would keep the old copy mounted and its ports+ // taken for as long as the new one runs: close all but stdio.+ ...(bash ? ['for fd in /proc/$$/fd/*; do n=${fd##*/}; case "$n" in 0|1|2) ;; *) eval "exec $n>&-" 2>/dev/null ;; esac; done'] : []),+ 'pid="$1"; runtime="$2"; shift 2',+ 'echo "$(date) waiting for $pid to exit, then opening $1"',+ 'i=0; while kill -0 "$pid" 2>/dev/null; do i=$((i + 1)); [ "$i" -gt 1200 ] && { echo "the app did not exit"; exit 1; }; sleep 0.25; done',+ // The AppImage runtime unmounts the old copy and exits; give it a moment.+ 'i=0; while [ "$runtime" -gt 1 ] && kill -0 "$runtime" 2>/dev/null && [ "$i" -lt 40 ]; do i=$((i + 1)); sleep 0.25; done',+ "sleep 0.5",+ 'exec "$@"',+ ].join("\n");+ /** @type {"ignore" | number} */+ let output = "ignore";+ if (logPath) {+ try {+ mkdirSync(path.dirname(logPath), { recursive: true });+ output = openSync(logPath, "a");+ } catch {+ output = "ignore";+ }+ }+ // Never inside the old mount: a cwd there would keep it mounted.+ const appDir = typeof env.APPDIR === "string" && env.APPDIR ? env.APPDIR : null;+ const cwd = typeof env.OWD === "string" && env.OWD && (!appDir || !env.OWD.startsWith(appDir)) && existsSync(env.OWD)+ ? env.OWD+ : os.homedir();+ const child = spawnProcess(bash ? "/bin/bash" : "/bin/sh", ["-c", script, "sh", String(pid), String(runtimePid ?? 0), appImage, ...args], {+ detached: true,+ cwd,+ stdio: ["ignore", output, output],+ env: /** @type {NodeJS.ProcessEnv} */ (environmentOutsideAppImage(env)),+ });+ if (typeof output === "number") closeSync(output);+ child.unref?.();+}++function run(command, args, options = {}) {+ return new Promise((resolve, reject) => {+ execFile(command, args, { encoding: "utf8", maxBuffer: 4 * 1024 * 1024, ...options }, (error, stdout, stderr) => {+ if (error) {+ error.stderr = stderr;+ reject(error);+ return;+ }+ resolve(String(stdout ?? "").trim());+ });+ });+}++async function plistValue(bundle, key, exec = run) {+ return exec("/usr/bin/plutil", ["-extract", key, "raw", "-o", "-", path.join(bundle, "Contents", "Info.plist")]);+}++/**+ * Extracts the verified release zip into a fresh folder and returns the .app+ * in it, after checking it is the expected version of the same app.+ */+export async function stageMacBundle({ zipPath, version, currentBundle, stagingRoot = os.tmpdir(), exec = run }) {+ const directory = await mkdtemp(path.join(stagingRoot, "omnirush-update-"));+ try {+ // ditto keeps the symlinks, modes and extended attributes an .app needs.+ await exec("/usr/bin/ditto", ["-x", "-k", zipPath, directory]);+ const entries = await readdir(directory);+ const bundleName = entries.find((name) => name.endsWith(".app"));+ if (!bundleName) throw new Error("The update zip has no app in it.");+ const bundle = path.join(directory, bundleName);+ const stagedVersion = await plistValue(bundle, "CFBundleShortVersionString", exec);+ if (version && stagedVersion !== version) {+ throw new Error(`The update zip holds version ${stagedVersion}, not ${version}.`);+ }+ if (currentBundle) {+ const [stagedId, currentId] = await Promise.all([+ plistValue(bundle, "CFBundleIdentifier", exec),+ plistValue(currentBundle, "CFBundleIdentifier", exec).catch(() => null),+ ]);+ if (currentId && stagedId !== currentId) throw new Error("The update zip holds a different app.");+ }+ await exec("/usr/bin/xattr", ["-dr", "com.apple.quarantine", bundle]).catch(() => undefined);+ return { directory, bundle, version: stagedVersion };+ } catch (error) {+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);+ throw error;+ }+}++/**+ * The detached helper: waits for the app to exit, moves the old bundle aside,+ * moves the new one in (rolling back if that fails), clears quarantine and+ * opens it. Arguments: pid, new bundle, target bundle, relaunch (1/0), and,+ * when it runs as root, the uid and user name to reopen the app as.+ */+export const MAC_SWAP_SCRIPT = `#!/bin/sh+pid="$1"; new="$2"; target="$3"; relaunch="$4"; uid="$5"; user="$6"+echo "$(date) swap $new -> $target (pid $pid)"+i=0+while kill -0 "$pid" 2>/dev/null; do+ i=$((i + 1))+ if [ "$i" -gt 1200 ]; then echo "the app did not exit; update skipped"; rm -rf "$(dirname "$new")"; exit 1; fi+ sleep 0.25+done+reopen() {+ [ "$relaunch" = 1 ] || return 0+ if [ -n "$uid" ]; then /bin/launchctl asuser "$uid" /usr/bin/sudo -u "$user" /usr/bin/open "$1"+ else /usr/bin/open "$1"; fi+}+backup="$target.previous-$$"+if ! mv "$target" "$backup"; then echo "could not move the old app aside"; reopen "$target"; exit 1; fi+if ! mv "$new" "$target"; then+ echo "could not move the new app in; restoring"+ rm -rf "$target"; mv "$backup" "$target"; reopen "$target"; exit 1+fi+if [ -n "$uid" ]; then chown -R "$(stat -f '%u:%g' "$backup")" "$target" 2>/dev/null || true; fi+/usr/bin/xattr -dr com.apple.quarantine "$target" 2>/dev/null || true+rm -rf "$backup" "$(dirname "$new")"+echo "$(date) installed $(/usr/bin/plutil -extract CFBundleShortVersionString raw -o - "$target/Contents/Info.plist" 2>/dev/null)"+reopen "$target"+`;++function appleScriptString(value) {+ return `"${String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;+}++/**+ * Starts the swap helper. Where this user can replace the bundle it runs+ * detached as the user; otherwise (an /Applications this user cannot write)+ * macOS asks for an administrator, and the helper runs as root and reopens+ * the app as the user. Resolves when the helper is running; rejects when it+ * could not start, including a cancelled password prompt.+ */+export async function launchMacSwap({+ stagedBundle,+ targetBundle,+ pid = process.pid,+ relaunch = true,+ logPath,+ writable,+ uid = process.getuid?.() ?? 0,+ user = os.userInfo().username,+ spawnDetached = defaultSpawnDetached,+ exec = run,+}) {+ const scriptPath = path.join(path.dirname(stagedBundle), "..", `omnirush-swap-${pid}.sh`);+ await writeFile(scriptPath, MAC_SWAP_SCRIPT, { mode: 0o755 });+ if (logPath) await mkdir(path.dirname(logPath), { recursive: true }).catch(() => undefined);+ const log = logPath ?? "/dev/null";+ if (writable) {+ spawnDetached("/bin/sh", [scriptPath, String(pid), stagedBundle, targetBundle, relaunch ? "1" : "0"], log);+ return { elevated: false };+ }+ const command = ["/bin/sh", scriptPath, String(pid), stagedBundle, targetBundle, relaunch ? "1" : "0", String(uid), user]+ .map(shellQuote)+ .join(" ");+ const script = `do shell script ${appleScriptString(`${command} >> ${shellQuote(log)} 2>&1 &`)} with prompt ${appleScriptString("OmniRush.ai needs permission to replace itself with the new version.")} with administrator privileges`;+ await exec("/usr/bin/osascript", ["-e", script]);+ return { elevated: true };+}++function defaultSpawnDetached(command, args, logPath) {+ const child = spawn("/bin/sh", ["-c", `exec "$@" >> ${shellQuote(logPath)} 2>&1`, "sh", command, ...args], {+ detached: true,+ stdio: "ignore",+ });+ child.unref();+}++/** "User canceled" from osascript (-128): the password prompt was dismissed. */+export function isAuthorizationCancelled(error) {+ const text = `${error?.message ?? ""} ${error?.stderr ?? ""}`;+ return /-128|User cancel+ed/i.test(text);+}++export async function fileExists(target) {+ try {+ await stat(target);+ return true;+ } catch {+ return false;+ }+}diff --git a/apps/desktop/electron/updater.mjs b/apps/desktop/electron/updater.mjsindex 1dd841fa..8c713408 100644--- a/apps/desktop/electron/updater.mjs+++ b/apps/desktop/electron/updater.mjs@@ -18,6 +18,21 @@ import {stableVersion,verifyCachedRecoveryArtifact,} from "./recovery.mjs";+import {+ canReplaceInPlace,+ fileExists,+ isAuthorizationCancelled,+ isTranslocatedBundle,+ launchMacSwap,+ linuxAppImagePath,+ linuxInstallCommand,+ linuxPackageType,+ macBundleFromPath,+ packageExtension,+ relaunchAppImageAfterExit,+ replaceAppImage,+ stageMacBundle,+} from "./self-install.mjs";const ELECTRON_UPDATER_CHANNEL_FILENAME = "electron-updater-channel.v1.json";// Where a manually installed update (macOS DMG) is staged before it is opened.@@ -403,29 +418,46 @@ function installerAssetArch(arch) {}/**- * Picks the DMG the update manifest lists for this architecture and resolves- * it against the feed directory, exactly like electron-updater resolves the- * zip it would hand to Squirrel. Returns null when the manifest has no- * matching installer or no checksum to verify it with.+ * The directory a manifest's relative file names resolve against. The public+ * feed is `releases/latest/download`, which follows whichever release is+ * latest at download time; the assets are read from the release the manifest+ * names instead, so a release published mid-download cannot swap the file+ * out from under the checksum.*/-export function selectManualInstallerArtifact(info, feedUrl, arch) {+export function releaseAssetDirectory(feedUrl, version) {+ const base = typeof feedUrl === "string" ? feedUrl.replace(/\/+$/, "") : "";+ if (base === STABLE_UPDATER_FEED_URL && typeof version === "string" && /^\d+\.\d+\.\d+/.test(version)) {+ return `https://github.com/omnirush-ai/omnirush-gui/releases/download/v${version}`;+ }+ return base;+}++/**+ * Picks the file the update manifest lists with `extension` (and, for macOS,+ * this architecture) and resolves it like electron-updater resolves its own+ * download. Returns null when the manifest has no matching file or no+ * checksum to verify it with. Only https is accepted, except from the+ * loopback feed of a local update rig.+ */+export function selectReleaseAsset(info, feedUrl, { extension, arch = null }) {const files = Array.isArray(info?.files) ? info.files : [];- const assetArch = `-${installerAssetArch(arch)}-`;+ const assetArch = arch ? `-${installerAssetArch(arch)}-` : "";const candidate = files.find((file) =>typeof file?.url === "string"- && file.url.endsWith(".dmg")- && file.url.includes(assetArch)+ && file.url.endsWith(extension)+ && (!assetArch || file.url.includes(assetArch))&& typeof file.sha512 === "string"&& file.sha512.trim(),);if (!candidate || typeof feedUrl !== "string" || !feedUrl) return null;let url;try {- url = new URL(candidate.url, `${feedUrl.replace(/\/+$/, "")}/`);+ url = new URL(candidate.url, `${releaseAssetDirectory(feedUrl, info?.version)}/`);} catch {return null;}- if (url.protocol !== "https:" || url.origin !== new URL(feedUrl).origin) return null;+ const secure = url.protocol === "https:" || loopbackDevFeedUrl(feedUrl) !== null;+ if (!secure || url.origin !== new URL(feedUrl).origin) return null;const size = Number(candidate.size);return {version: typeof info?.version === "string" ? info.version : null,@@ -436,6 +468,11 @@ export function selectManualInstallerArtifact(info, feedUrl, arch) {};}+/** The DMG for this architecture (macOS builds that cannot replace themselves). */+export function selectManualInstallerArtifact(info, feedUrl, arch) {+ return selectReleaseAsset(info, feedUrl, { extension: ".dmg", arch });+}+async function fileMatchesSha512(filePath, expected) {return new Promise((resolve) => {const hash = createHash("sha512");@@ -475,6 +512,17 @@ export function registerUpdaterIpc({quitUpdateTimeoutMs = 120_000,// Quits anyway if the updater never quits the app after a quit-time install.quitInstallFallbackMs = 30_000,+ // Self-install (self-install.mjs): the running bundle or AppImage, and the+ // seams tests replace.+ getAppPath = () => app.getAppPath(),+ resourcesPath = process.resourcesPath,+ pid = process.pid,+ canReplace = canReplaceInPlace,+ stageMacUpdate = stageMacBundle,+ startMacSwap = launchMacSwap,+ installAppImage = replaceAppImage,+ relaunchAppImage = relaunchAppImageAfterExit,+ restartDelayMs = 300,}) {const feedOptions = updaterFeedOptions({manifestChannel,@@ -489,6 +537,13 @@ export function registerUpdaterIpc({let checkedUpdateChannel = null;let checkedInstallerArtifact = null;let downloadedInstallerPath = null;+ // mac-swap: the extracted, verified bundle waiting for the swap helper.+ let stagedMacBundle = null;+ // appimage: electron-updater's verified download of the new AppImage.+ let downloadedAppImagePath = null;+ // What the self-install modes replace, and the Linux package kind.+ let installTarget = null;+ let packageKind = 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.@@ -517,33 +572,96 @@ export function registerUpdaterIpc({}}- // "in-place": electron-updater swaps the app (Squirrel.Mac, NSIS, AppImage).- // "manual-dmg": the running macOS app is not Developer ID signed, so the- // update is downloaded as a DMG and opened for the user to drag over.+ // "in-place": electron-updater swaps the app (Squirrel.Mac, NSIS).+ // "mac-swap": a macOS app without a Developer ID signature, which Squirrel+ // refuses; the release zip is swapped in by self-install.mjs.+ // "appimage": the AppImage file is replaced and the app relaunched.+ // "package": a .deb/.rpm/.pacman install (or an AppImage in a folder this+ // user cannot write); the package is downloaded and the user runs the+ // install command the app shows.+ // "manual-dmg": a macOS app that cannot be replaced (App Translocation);+ // the DMG is downloaded and opened.function resolveInstallMode() {if (!installModePromise) {installModePromise = (async () => {- if (platform !== "darwin" || !app.isPackaged) return "in-place";- try {- return (await isDeveloperIdSigned()) ? "in-place" : "manual-dmg";- } catch {- return "manual-dmg";+ if (!app.isPackaged) return "in-place";+ if (platform === "darwin") {+ try {+ if (await isDeveloperIdSigned()) return "in-place";+ } catch {+ // An unknown signature is treated as ad hoc.+ }+ let bundle = null;+ try {+ bundle = macBundleFromPath(getAppPath()) ?? macAppBundlePath(execPath);+ } catch {+ bundle = macAppBundlePath(execPath);+ }+ if (!bundle || isTranslocatedBundle(bundle)) return "manual-dmg";+ installTarget = bundle;+ return "mac-swap";+ }+ if (platform === "linux") {+ const appImage = linuxAppImagePath(env);+ if (appImage) {+ installTarget = appImage;+ if (await canReplace(appImage)) return "appimage";+ packageKind = "appimage";+ return "package";+ }+ packageKind = await linuxPackageType(resourcesPath);+ return "package";}+ return "in-place";})();}return installModePromise;}+ /** What the renderer is told: every mode that restarts into the update is "in-place". */+ function publicInstallMode(mode) {+ return mode === "mac-swap" || mode === "appimage" ? "in-place" : mode;+ }++ async function describeInstall() {+ const mode = await resolveInstallMode();+ return {+ installMode: publicInstallMode(mode),+ ...(mode === "package" ? { packageKind } : {}),+ };+ }+async function describeChannelState(channel, targetVersion = null) {return {...updaterChannelState(app, channel, targetVersion, feedOptions),- installMode: await resolveInstallMode(),+ ...(await describeInstall()),};}+ /** The file a self-install mode downloads itself, from the manifest just read. */+ function selfInstallAsset(info, feedUrl, installMode) {+ switch (installMode) {+ case "manual-dmg":+ return selectManualInstallerArtifact(info, feedUrl, arch);+ case "mac-swap":+ return selectReleaseAsset(info, feedUrl, { extension: ".zip", arch });+ case "package": {+ const extension = packageExtension(packageKind);+ return extension ? selectReleaseAsset(info, feedUrl, { extension }) : null;+ }+ default:+ return null;+ }+ }+function clearDownloadedUpdate() {updateDownloaded = false;downloadedInstallerPath = null;+ downloadedAppImagePath = null;+ if (stagedMacBundle) {+ void rm(path.dirname(stagedMacBundle), { recursive: true, force: true }).catch(() => undefined);+ stagedMacBundle = null;+ }downloadedUpdateVersion = null;downloadedUpdateChannel = null;}@@ -561,9 +679,7 @@ export function registerUpdaterIpc({checkedUpdateVersion = available ? info.version : null;checkedUpdateTargetVersion = available ? targetVersion : null;checkedUpdateChannel = available ? channelState.channel : null;- checkedInstallerArtifact = available && installMode === "manual-dmg"- ? selectManualInstallerArtifact(info, channelState.feedUrl, arch)- : null;+ checkedInstallerArtifact = available ? selfInstallAsset(info, channelState.feedUrl, installMode) : null;return available;}@@ -602,6 +718,7 @@ export function registerUpdaterIpc({autoUpdaterInstance.on("update-downloaded", (info) => {updateDownloaded = true;if (typeof info?.version === "string") downloadedUpdateVersion = info.version;+ if (typeof info?.downloadedFile === "string") downloadedAppImagePath = info.downloadedFile;});// Forward download progress to the renderer so the UI can show// incremental bytes instead of staying stuck at 0.@@ -631,16 +748,18 @@ export function registerUpdaterIpc({* the same progress events electron-updater emits, so the Updates page shows* one download experience regardless of install mode.*/- async function downloadManualInstaller(artifact) {+ async function downloadManualInstaller(artifact, { directory = null } = {}) {if (!electronNet?.fetch) throw new Error("Installer downloads are unavailable in this package.");+ // The cache folder is ours to empty; a user folder (Downloads) is not.+ const target = directory ?? path.join(app.getPath("userData"), INSTALLER_CACHE_DIRECTORY);+ const destination = path.join(target, artifact.fileName);+ if (directory && (await fileMatchesSha512(destination, artifact.sha512))) return destination;const response = await electronNet.fetch(artifact.url, {headers: { Accept: "application/octet-stream, */*" },});if (!response.ok) throw new Error(`Installer download failed with HTTP ${response.status}.`);- const directory = path.join(app.getPath("userData"), INSTALLER_CACHE_DIRECTORY);- await rm(directory, { recursive: true, force: true });- await mkdir(directory, { recursive: true });- const destination = path.join(directory, artifact.fileName);+ if (!directory) await rm(target, { recursive: true, force: true });+ await mkdir(target, { recursive: true });const partialPath = `${destination}.part`;const headerLength = Number(response.headers?.get?.("content-length"));const total = artifact.size ?? (Number.isInteger(headerLength) && headerLength > 0 ? headerLength : 0);@@ -856,7 +975,8 @@ export function registerUpdaterIpc({const updater = await ensureAutoUpdater();// An ad-hoc signed macOS app cannot be swapped by Squirrel, so recovery// there opens the verified installer exactly like a manual update.- if (updater && app.isPackaged && (await resolveInstallMode()) === "in-place") {+ const recoveryMode = await resolveInstallMode();+ if (updater && app.isPackaged && (recoveryMode === "in-place" || recoveryMode === "appimage")) {try {await applyElectronUpdaterFeed(app, updater, release.version, feedOptions, true);const result = await updater.checkForUpdates();@@ -925,7 +1045,7 @@ export function registerUpdaterIpc({// after an organization policy moves the desktop back to Stable.preventPendingUpdaterInstall(updater);const state = await applyElectronUpdaterFeed(app, updater, null, feedOptions, false, channel);- return { ...state, installMode };+ return { ...state, ...(await describeInstall()) };}return describeChannelState(channel);}));@@ -946,7 +1066,7 @@ export function registerUpdaterIpc({throw new Error("Target update version must use the stable x.y.z format.");}const channelState = updater- ? { ...(await applyElectronUpdaterFeed(app, updater, targetVersion, feedOptions, false, channel)), installMode }+ ? { ...(await applyElectronUpdaterFeed(app, updater, targetVersion, feedOptions, false, channel)), ...(await describeInstall()) }: await describeChannelState(channel, targetVersion);if (!updater) return { available: false, reason: "unavailable", ...channelState };@@ -1009,24 +1129,59 @@ export function registerUpdaterIpc({console.warn("[updater] could not cache the current healthy installer", error);});await downloadCheckedUpdate(updater, installMode);- return { ok: true, mode: installMode };+ return { ok: true, mode: publicInstallMode(installMode), ...downloadedPackageDetails(installMode) };} catch (error) {clearDownloadedUpdate();return { ok: false, reason: String(error?.message ?? error) };}}));+ /** The downloaded package and its install command (package mode only). */+ function downloadedPackageDetails(installMode) {+ if (installMode !== "package") return {};+ return {+ packageKind,+ path: downloadedInstallerPath,+ command: downloadedInstallerPath+ ? linuxInstallCommand(packageKind, downloadedInstallerPath, packageKind === "appimage" ? installTarget : null)+ : null,+ };+ }+/** 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 (installMode === "manual-dmg" || installMode === "mac-swap" || installMode === "package") {+ // Squirrel.Mac refuses an ad-hoc signed app and a package manager owns+ // a .deb/.rpm/.pacman install, so the file the manifest lists is+ // fetched directly: 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.");+ throw new Error(installMode === "package"+ ? "The release manifest does not list a package for this installation."+ : "The release manifest does not list a macOS installer for this update.");+ }+ if (installMode === "package") {+ downloadedInstallerPath = await downloadManualInstaller(checkedInstallerArtifact, {+ directory: app.getPath("downloads"),+ });+ } else {+ downloadedInstallerPath = await downloadManualInstaller(checkedInstallerArtifact);+ }+ if (installMode === "mac-swap") {+ if (stagedMacBundle) {+ await rm(path.dirname(stagedMacBundle), { recursive: true, force: true }).catch(() => undefined);+ stagedMacBundle = null;+ }+ // Extracted next to nothing it could clobber; verified to be this+ // app at the expected version before the restart button appears.+ const staged = await stageMacUpdate({+ zipPath: downloadedInstallerPath,+ version,+ currentBundle: installTarget,+ });+ stagedMacBundle = staged.bundle;+ await rm(downloadedInstallerPath, { force: true }).catch(() => undefined);}- downloadedInstallerPath = await downloadManualInstaller(checkedInstallerArtifact);} else {// Clear any stuck ShipIt state from a prior aborted install so this// download applies cleanly.@@ -1110,13 +1265,24 @@ export function registerUpdaterIpc({const updater = autoUpdaterInstance;if (!updater || !updateDownloaded || installTriggered) return null;const installMode = await resolveInstallMode();- if (installMode !== "in-place") return null;+ if (installMode !== "in-place" && installMode !== "appimage" && installMode !== "mac-swap") return null;+ // 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;const newest = await withTimeout(queueUpdaterOperation(() => ensureNewestDownloaded(updater, installMode)),quitUpdateTimeoutMs,"The quit-time update refresh",);if (!newest.ok || !updateDownloaded || installTriggered) return null;+ if (installMode === "appimage" || installMode === "mac-swap") {+ return () => {+ installTriggered = true;+ void selfInstall(installMode, { relaunch: false })+ .catch((error) => console.warn("[updater] install on quit failed", error?.message ?? error))+ .finally(() => app.quit());+ };+ }return () => {installTriggered = true;quitInstallInProgress = true;@@ -1136,6 +1302,52 @@ export function registerUpdaterIpc({}}+ /**+ * mac-swap and appimage installs. Starts the swap (or replaces the+ * AppImage) and, with `relaunch`, arranges for the new version to open+ * once this process exits. Throws when nothing was changed.+ */+ async function selfInstall(installMode, { relaunch }) {+ if (installMode === "mac-swap") {+ if (!stagedMacBundle || !(await fileExists(stagedMacBundle))) throw new Error("update-not-downloaded");+ const writable = await canReplace(installTarget);+ await startMacSwap({+ stagedBundle: stagedMacBundle,+ targetBundle: installTarget,+ pid,+ relaunch,+ writable,+ logPath: path.join(app.getPath("logs"), "update-install.log"),+ });+ // The helper owns the staged bundle now.+ stagedMacBundle = null;+ return;+ }+ const source = downloadedAppImagePath ?? autoUpdaterInstance?.installerPath ?? null;+ if (!source || !(await fileExists(source))) throw new Error("update-not-downloaded");+ await installAppImage({ source, target: installTarget });+ downloadedAppImagePath = null;+ if (relaunch) {+ // Started outside the AppImage and only once this process has exited,+ // so the new copy never meets this instance's single-instance lock.+ relaunchAppImage({+ appImage: installTarget,+ pid,+ args: process.argv.slice(1),+ env,+ logPath: path.join(app.getPath("logs"), "update-install.log"),+ });+ }+ }++ // Package installs: show the downloaded package (the path is the one this+ // process downloaded, never one the renderer names).+ ipcMain.handle("omnirush:updater:showDownloaded", async () => {+ if (!downloadedInstallerPath || !shell?.showItemInFolder) return { ok: false };+ shell.showItemInFolder(downloadedInstallerPath);+ return { ok: true };+ });+ipcMain.handle("omnirush:updater:installAndRestart", async () => queueUpdaterOperation(async () => {if (!updateDownloaded) return { ok: false, reason: "update-not-downloaded" };const updater = await ensureAutoUpdater();@@ -1143,6 +1355,36 @@ export function registerUpdaterIpc({const installMode = await resolveInstallMode();const newest = await ensureNewestDownloaded(updater, installMode);if (!newest.ok) return newest;+ if (installMode === "package") {+ // Nothing to restart into: the package manager installs it.+ return { ok: true, mode: "package", ...downloadedPackageDetails(installMode) };+ }+ if (installMode === "mac-swap" || installMode === "appimage") {+ try {+ await selfInstall(installMode, { relaunch: true });+ } catch (error) {+ const message = String(error?.message ?? error);+ if (message === "update-not-downloaded") {+ clearDownloadedUpdate();+ return { ok: false, reason: "update-not-downloaded" };+ }+ if (installMode === "mac-swap") {+ // Only here does the app send the user to the download page.+ return {+ ok: false,+ fallback: "download-page",+ reason: isAuthorizationCancelled(error)+ ? `Updating needs an administrator to replace ${path.basename(installTarget ?? "the app")} in ${path.dirname(installTarget ?? "/Applications")}, and the request was cancelled. Download the new version and drag it into that folder instead.`+ : `The update could not replace ${path.basename(installTarget ?? "the app")}: ${message}. Download the new version and drag it into ${path.dirname(installTarget ?? "/Applications")} instead.`,+ };+ }+ return { ok: false, reason: `The update could not replace the AppImage: ${message}` };+ }+ installTriggered = true;+ // Let the renderer show "Restarting…" before the window goes away.+ setTimeout(() => app.quit(), restartDelayMs);+ return { ok: true, mode: "in-place" };+ }if (installMode === "manual-dmg") {if (!downloadedInstallerPath || !checkedInstallerArtifact) {return { ok: false, reason: "update-not-downloaded" };diff --git a/apps/desktop/electron/updater.test.mjs b/apps/desktop/electron/updater.test.mjsindex 59f8f5a3..f0d7af45 100644--- a/apps/desktop/electron/updater.test.mjs+++ b/apps/desktop/electron/updater.test.mjs@@ -1,7 +1,7 @@import { describe, it } from "node:test";import assert from "node:assert/strict";import { createHash } from "node:crypto";-import { mkdtempSync, readFileSync } from "node:fs";+import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync } from "node:fs";import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -96,9 +96,10 @@ async function registerFakeUpdaterIpc({ version, files = undefined, ...options }isDestroyed: () => false,}),loadAutoUpdater: async () => ({ autoUpdater: harness.updater }),- // The default harness models a Developer ID signed app (or a non-macOS- // platform): in-place installs through electron-updater.+ // The default harness models a Developer ID signed app (or Windows):+ // in-place installs through electron-updater.isDeveloperIdSigned: async () => true,+ platform: "win32",...options,});return { tempDir, handlers, sent, app, ...registered, ...harness };@@ -673,6 +674,8 @@ describe("macOS code signature detection", () => {});});+const RELEASE_123 = "https://github.com/omnirush-ai/omnirush-gui/releases/download/v1.2.3";+describe("manual installer artifacts", () => {const files = [{ url: "omnirush-mac-arm64-1.2.3.zip", sha512: "zip-checksum", size: 10 },@@ -683,7 +686,8 @@ describe("manual installer artifacts", () => {it("selects the DMG for the running architecture relative to the feed directory", () => {assert.deepEqual(selectManualInstallerArtifact({ version: "1.2.3", files }, STABLE_FEED, "arm64"), {version: "1.2.3",- url: `${STABLE_FEED}/omnirush-mac-arm64-1.2.3.dmg`,+ // From the release the manifest names, not whatever is latest at download time.+ url: `${RELEASE_123}/omnirush-mac-arm64-1.2.3.dmg`,sha512: "arm64-checksum",size: 20,fileName: "omnirush-mac-arm64-1.2.3.dmg",@@ -717,6 +721,9 @@ describe("macOS manual installer fallback", () => {platform: "darwin",arch: "arm64",isDeveloperIdSigned: async () => false,+ // Gatekeeper runs a quarantined app opened from Downloads from a+ // read-only translocated copy: replacing that would change nothing.+ getAppPath: () => "/private/var/folders/x/T/AppTranslocation/ABCD/d/OmniRush.ai.app/Contents/Resources/app.asar",electronNet: { fetch: async (url) => {fetched.push(url);return new Response(bytes);@@ -746,7 +753,7 @@ describe("macOS manual installer fallback", () => {assert.equal(checked.installMode, "manual-dmg");assert.deepEqual(await download(), { ok: true, mode: "manual-dmg" });- assert.deepEqual(fetched, [`${STABLE_FEED}/omnirush-mac-arm64-0.17.1.dmg`]);+ assert.deepEqual(fetched, ["https://github.com/omnirush-ai/omnirush-gui/releases/download/v0.17.1/omnirush-mac-arm64-0.17.1.dmg"]);assert.deepEqual(calls, [], "electron-updater's zip download must not run");const progress = sent.filter((event) => event.channel === "omnirush:updater:download-progress");assert.equal(progress.at(-1)?.data.transferred, bytes.length);@@ -804,7 +811,6 @@ describe("macOS manual installer fallback", () => {it("keeps the Squirrel path for Developer ID signed macOS apps and other platforms", async () => {for (const options of [{ platform: "darwin", arch: "arm64", isDeveloperIdSigned: async () => true },- { platform: "linux", arch: "x64", isDeveloperIdSigned: async () => false },{ platform: "win32", arch: "x64", isDeveloperIdSigned: async () => { throw new Error("not consulted"); } },]) {const { tempDir, handlers, calls } = await registerFakeUpdaterIpc({ version: "0.17.1", ...options });@@ -1156,3 +1162,300 @@ describe("dev update feed override", () => {assert.equal(updaterFeedOptions({ devFeedUrl: "https://evil.example/f" }).stableFeedUrl, STABLE_FEED);});});++const RELEASE_0171 = "https://github.com/omnirush-ai/omnirush-gui/releases/download/v0.17.1";+const sha512Of = (bytes) => createHash("sha512").update(bytes).digest("base64");+const settle = (ms = 20) => new Promise((resolve) => setTimeout(resolve, ms));++describe("macOS self-install without a Developer ID signature", () => {+ const BUNDLE = "/Users/test/Applications/OmniRush.ai.app";+ const macSwapHarness = async ({ writable = true, swap = null } = {}) => {+ const zip = Buffer.from("zip-bytes-of-0.17.1");+ const fetched = [];+ const staged = [];+ const swaps = [];+ const harness = await registerFakeUpdaterIpc({+ version: "0.17.1",+ files: [+ { url: "omnirush-mac-arm64-0.17.1.zip", sha512: sha512Of(zip), size: zip.length },+ { url: "omnirush-mac-arm64-0.17.1.dmg", sha512: "dmg-checksum", size: 1 },+ ],+ platform: "darwin",+ arch: "arm64",+ isDeveloperIdSigned: async () => false,+ getAppPath: () => `${BUNDLE}/Contents/Resources/app.asar`,+ electronNet: { fetch: async (url) => {+ fetched.push(url);+ return new Response(zip);+ } },+ canReplace: async () => writable,+ stageMacUpdate: async ({ zipPath, version, currentBundle }) => {+ staged.push({ bytes: readFileSync(zipPath), version, currentBundle });+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-staged-"));+ await mkdir(path.join(directory, "OmniRush.ai.app"));+ return { directory, bundle: path.join(directory, "OmniRush.ai.app"), version };+ },+ startMacSwap: async (request) => {+ swaps.push(request);+ if (swap) await swap(request);+ return { elevated: !request.writable };+ },+ restartDelayMs: 0,+ });+ return { ...harness, zip, fetched, staged, swaps };+ };++ it("downloads the release zip, stages it and swaps the bundle on restart", async () => {+ const { tempDir, handlers, calls, fetched, staged, swaps, zip } = await macSwapHarness();+ try {+ assert.equal((await handlers.get("omnirush:updater:getChannel")()).installMode, "in-place");+ assert.equal((await handlers.get("omnirush:updater:check")(null, "stable")).available, true);+ assert.deepEqual(await handlers.get("omnirush:updater:download")(), { ok: true, mode: "in-place" });+ assert.deepEqual(fetched, [`${RELEASE_0171}/omnirush-mac-arm64-0.17.1.zip`]);+ assert.deepEqual(staged, [{ bytes: zip, version: "0.17.1", currentBundle: BUNDLE }]);+ assert.deepEqual(calls, [], "Squirrel never runs for an ad-hoc signed app");++ assert.deepEqual(await handlers.get("omnirush:updater:installAndRestart")(), { ok: true, mode: "in-place" });+ assert.equal(swaps.length, 1);+ assert.equal(swaps[0].targetBundle, BUNDLE);+ assert.equal(swaps[0].writable, true);+ assert.equal(swaps[0].relaunch, true);+ assert.match(swaps[0].stagedBundle, /OmniRush\.ai\.app$/);+ await settle();+ assert.deepEqual(calls, ["quit"]);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("asks for an administrator where the folder is not writable, and falls back to the download page only when that is cancelled", async () => {+ const { tempDir, handlers, calls, swaps } = await macSwapHarness({+ writable: false,+ swap: async () => {+ const error = new Error("Command failed: osascript\n0:12: execution error: User canceled. (-128)");+ throw error;+ },+ });+ try {+ await handlers.get("omnirush:updater:check")(null, "stable");+ await handlers.get("omnirush:updater:download")();+ const result = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(result.ok, false);+ assert.equal(result.fallback, "download-page");+ assert.match(result.reason, /administrator/);+ assert.match(result.reason, /cancelled/);+ assert.equal(swaps[0].writable, false);+ await settle();+ assert.deepEqual(calls, [], "the app stays open when nothing was replaced");+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ it("installs on quit without relaunching, and never prompts for a password at quit", async () => {+ for (const writable of [true, false]) {+ const { tempDir, handlers, swaps, prepareInstallOnQuit } = await macSwapHarness({ writable });+ try {+ await handlers.get("omnirush:updater:check")(null, "stable");+ await handlers.get("omnirush:updater:download")();+ const installAndQuit = await prepareInstallOnQuit();+ if (!writable) {+ assert.equal(installAndQuit, null);+ continue;+ }+ installAndQuit();+ await settle();+ assert.equal(swaps.length, 1);+ assert.equal(swaps[0].relaunch, false);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ }+ });+});++describe("the swap helper script", { skip: process.platform === "win32" }, () => {+ it("waits for the app to exit, swaps the bundle and cleans up", async () => {+ const { MAC_SWAP_SCRIPT } = await import("./self-install.mjs");+ const { spawn, execFile } = await import("node:child_process");+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-swap-"));+ try {+ const target = path.join(root, "Applications", "OmniRush.ai.app");+ const staging = path.join(root, "staging");+ const staged = path.join(staging, "OmniRush.ai.app");+ await mkdir(path.join(target, "Contents"), { recursive: true });+ await writeFile(path.join(target, "Contents", "version"), "old");+ await mkdir(path.join(staged, "Contents"), { recursive: true });+ await writeFile(path.join(staged, "Contents", "version"), "new");+ const script = path.join(root, "swap.sh");+ await writeFile(script, MAC_SWAP_SCRIPT, { mode: 0o755 });+ const app = spawn("sleep", ["0.6"]);+ const startedAt = Date.now();+ // Async, so this process reaps the exited "app" (a zombie still answers kill -0).+ await new Promise((resolve, reject) => {+ execFile("/bin/sh", [script, String(app.pid), staged, target, "0"], (error) => (error ? reject(error) : resolve()));+ });+ assert.ok(Date.now() - startedAt >= 400, "the swap waited for the app to exit");+ assert.equal(await readFile(path.join(target, "Contents", "version"), "utf8"), "new");+ assert.equal(existsSync(staging), false, "the staging folder is removed");+ const leftovers = readdirSync(path.dirname(target));+ assert.deepEqual(leftovers, ["OmniRush.ai.app"], "no backup bundle is left behind");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+});++describe("Linux AppImage self-install", () => {+ const appImageHarness = async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-appimage-"));+ const appImage = path.join(root, "Apps", "omnirush-linux-x86_64-0.17.0.AppImage");+ await mkdir(path.dirname(appImage), { recursive: true });+ await writeFile(appImage, "old-appimage", { mode: 0o755 });+ const cache = path.join(root, "cache", "pending");+ await mkdir(cache, { recursive: true });+ const relaunches = [];+ const harness = await registerFakeUpdaterIpc({+ version: "0.17.1",+ platform: "linux",+ arch: "x64",+ env: { APPIMAGE: appImage },+ restartDelayMs: 0,+ relaunchAppImage: (options) => relaunches.push(options),+ });+ harness.updater.downloadUpdate = async () => {+ harness.calls.push("download");+ const downloadedFile = path.join(cache, "omnirush-linux-x86_64-0.17.1.AppImage");+ await writeFile(downloadedFile, "new-appimage");+ harness.listeners.get("update-downloaded")({ version: "0.17.1", downloadedFile });+ };+ return { ...harness, root, appImage, relaunches };+ };++ it("replaces the AppImage file in place and relaunches it once this process exits", async () => {+ const { tempDir, root, handlers, calls, appImage, relaunches } = await appImageHarness();+ try {+ assert.equal((await handlers.get("omnirush:updater:check")(null, "stable")).installMode, "in-place");+ 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.equal(await readFile(appImage, "utf8"), "new-appimage", "same path, new contents");+ assert.equal(statSync(appImage).mode & 0o777, 0o755);+ assert.deepEqual(readdirSync(path.dirname(appImage)), [path.basename(appImage)]);+ assert.equal(relaunches.length, 1);+ assert.equal(relaunches[0].appImage, appImage);+ await settle();+ assert.deepEqual(calls, ["download", "quit"], "electron-updater's quitAndInstall is not used");+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ await rm(root, { recursive: true, force: true });+ }+ });++ it("replaces the AppImage on quit without relaunching", async () => {+ const { tempDir, root, handlers, calls, appImage, relaunches, prepareInstallOnQuit } = await appImageHarness();+ try {+ await handlers.get("omnirush:updater:check")(null, "stable");+ await handlers.get("omnirush:updater:download")();+ (await prepareInstallOnQuit())();+ await settle();+ assert.equal(await readFile(appImage, "utf8"), "new-appimage");+ assert.deepEqual(relaunches, []);+ assert.deepEqual(calls, ["download", "quit"]);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ await rm(root, { recursive: true, force: true });+ }+ });+});++describe("Linux package installs", () => {+ it("downloads the .deb to Downloads and gives the install command instead of restarting", async () => {+ const deb = Buffer.from("deb-bytes");+ const resources = await mkdtemp(path.join(os.tmpdir(), "omnirush-resources-"));+ await writeFile(path.join(resources, "package-type"), "deb\n");+ const fetched = [];+ const { tempDir, handlers, calls } = await registerFakeUpdaterIpc({+ version: "0.17.1",+ files: [+ { url: "omnirush-linux-x86_64-0.17.1.AppImage", sha512: "appimage", size: 1 },+ { url: "omnirush-linux-amd64-0.17.1.deb", sha512: sha512Of(deb), size: deb.length },+ { url: "omnirush-linux-x86_64-0.17.1.rpm", sha512: "rpm", size: 1 },+ ],+ platform: "linux",+ arch: "x64",+ env: {},+ resourcesPath: resources,+ electronNet: { fetch: async (url) => {+ fetched.push(url);+ return new Response(deb);+ } },+ });+ try {+ const checked = await handlers.get("omnirush:updater:check")(null, "stable");+ assert.equal(checked.installMode, "package");+ assert.equal(checked.packageKind, "deb");+ const expectedPath = path.join(tempDir, "downloads", "omnirush-linux-amd64-0.17.1.deb");+ const downloaded = await handlers.get("omnirush:updater:download")();+ assert.deepEqual(downloaded, {+ ok: true,+ mode: "package",+ packageKind: "deb",+ path: expectedPath,+ command: `sudo apt install ${expectedPath}`,+ });+ assert.deepEqual(fetched, [`${RELEASE_0171}/omnirush-linux-amd64-0.17.1.deb`]);+ assert.deepEqual(readFileSync(expectedPath), deb);+ const installed = await handlers.get("omnirush:updater:installAndRestart")();+ assert.equal(installed.ok, true);+ assert.equal(installed.mode, "package");+ await settle();+ assert.deepEqual(calls, [], "nothing quits and electron-updater installs nothing");+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ await rm(resources, { recursive: true, force: true });+ }+ });++ it("reopens the AppImage from outside its mount once the old process exits", async () => {+ const { relaunchAppImageAfterExit, environmentOutsideAppImage } = await import("./self-install.mjs");+ const spawned = [];+ relaunchAppImageAfterExit({+ appImage: "/home/a/Apps/omnirush.AppImage",+ pid: 4242,+ runtimePid: 4241,+ args: ["--no-sandbox"],+ env: {+ APPDIR: "/tmp/.mount_abc",+ APPIMAGE: "/home/a/Apps/omnirush.AppImage",+ LD_LIBRARY_PATH: "/tmp/.mount_abc/usr/lib",+ PATH: "/tmp/.mount_abc:/usr/local/bin:/usr/bin",+ HOME: "/home/a",+ DISPLAY: ":0",+ OMNIRUSH_ELECTRON_REMOTE_DEBUG_PORT: "9223",+ },+ spawnProcess: (command, args, options) => {+ spawned.push({ command, args, options });+ return { unref() {} };+ },+ });+ assert.match(spawned[0].command, /^\/bin\/(ba)?sh$/);+ assert.deepEqual(spawned[0].args.slice(3), ["4242", "4241", "/home/a/Apps/omnirush.AppImage", "--no-sandbox"]);+ assert.equal(spawned[0].options.detached, true);+ // Nothing points into the old mount, which is gone once the app exits.+ assert.deepEqual(spawned[0].options.env, { PATH: "/usr/local/bin:/usr/bin", HOME: "/home/a", DISPLAY: ":0" });+ assert.deepEqual(environmentOutsideAppImage({ PATH: "/usr/bin" }), { PATH: "/usr/bin" });+ });++ it("names the command for each package kind", async () => {+ const { linuxInstallCommand, shellQuote } = await import("./self-install.mjs");+ assert.equal(linuxInstallCommand("deb", "/home/a/Downloads/x.deb"), "sudo apt install /home/a/Downloads/x.deb");+ assert.equal(linuxInstallCommand("rpm", "/home/a/Downloads/x.rpm"), "sudo dnf install /home/a/Downloads/x.rpm");+ assert.equal(linuxInstallCommand("pacman", "/home/a/Downloads/x.pacman"), "sudo pacman -U /home/a/Downloads/x.pacman");+ assert.equal(+ linuxInstallCommand("appimage", "/home/a/Downloads/x.AppImage", "/opt/OmniRush/omnirush.AppImage"),+ "sudo install -m 755 /home/a/Downloads/x.AppImage /opt/OmniRush/omnirush.AppImage",+ );+ assert.equal(linuxInstallCommand(null, "/x"), null);+ assert.equal(shellQuote("/home/o'neil/My Downloads/x.deb"), "'/home/o'\\''neil/My Downloads/x.deb'");+ });+});