A desktop coding agent with free access to frontier models.
TypeScript
feat(desktop): mandatory client update banner and blocked view
ogsamrat6fb56b0005ec
diff --git a/apps/app/src/app/index.css b/apps/app/src/app/index.cssindex 5e549528..f6f9f9df 100644--- a/apps/app/src/app/index.css+++ b/apps/app/src/app/index.css@@ -811,3 +811,16 @@ select:disabled {min-height: 100dvh;}}++/* The required-update banner (react-app/shell/update-gate.tsx) shifts the app+ down by its height: viewport-sized boxes inside it take the shifted box. */+[data-update-gate-shifted] .h-dvh,+[data-update-gate-shifted] .h-svh,+[data-update-gate-shifted] .h-screen {+ height: 100%;+}+[data-update-gate-shifted] .min-h-dvh,+[data-update-gate-shifted] .min-h-svh,+[data-update-gate-shifted] .min-h-screen {+ min-height: 100%;+}diff --git a/apps/app/src/app/lib/update-gate.ts b/apps/app/src/app/lib/update-gate.tsnew file mode 100644index 00000000..613ec7c6--- /dev/null+++ b/apps/app/src/app/lib/update-gate.ts@@ -0,0 +1,170 @@+// Mandatory client update, renderer side. The Electron main process derives+// the state (apps/desktop/electron/update-gate.mjs) from /device/me+// `client_update`, the gateway's x-omnirush-update-required header and 426+// `update_required` refusals; these helpers decide what the banner and the+// blocked view say and what "Update now" does.++import { create } from "zustand";++import type { OmniRushUpdateGateState } from "@omnirush/types/desktop-ipc";++export type UpdateGateState = OmniRushUpdateGateState;++export const NO_UPDATE_GATE: UpdateGateState = {+ status: "none",+ current: "",+ minimum: null,+ deadline: null,+ message: null,+ downloadUrl: "https://omnirush.ai/download",+ source: null,+};++type UpdateGateBridge = {+ get?: () => Promise<UpdateGateState>;+ refresh?: () => Promise<UpdateGateState>;+ onChange?: (callback: (state: UpdateGateState) => void) => () => void;+};++declare global {+ interface Window {+ /** Lets evals and screenshots drive the gate without a gateway. */+ __omnirushUpdateGateEval?: (state: Partial<UpdateGateState> | null) => void;+ }+}++function bridge(): UpdateGateBridge | null {+ if (typeof window === "undefined") return null;+ return (window.__OMNIRUSH_ELECTRON__ as { updateGate?: UpdateGateBridge } | undefined)?.updateGate ?? null;+}++/** A state from the bridge, or NO_UPDATE_GATE for anything malformed. */+export function normalizeUpdateGateState(value: unknown): UpdateGateState {+ if (!value || typeof value !== "object") return NO_UPDATE_GATE;+ const raw = value as Partial<UpdateGateState>;+ const status = raw.status === "required" || raw.status === "blocked" ? raw.status : "none";+ const str = (field: unknown) => (typeof field === "string" && field.trim() ? field.trim() : null);+ return {+ status,+ current: str(raw.current) ?? "",+ minimum: str(raw.minimum),+ deadline: str(raw.deadline) && Number.isFinite(Date.parse(String(raw.deadline))) ? String(raw.deadline) : null,+ message: str(raw.message),+ downloadUrl: str(raw.downloadUrl) ?? NO_UPDATE_GATE.downloadUrl,+ source: raw.source === "profile" || raw.source === "header" || raw.source === "rejection" ? raw.source : null,+ };+}++/** "2d 4h", "5h 12m", "12m", or "less than a minute"; null without a deadline. */+export function formatUpdateCountdown(deadline: string | null, now: number): string | null {+ if (!deadline) return null;+ const at = Date.parse(deadline);+ if (!Number.isFinite(at)) return null;+ const left = at - now;+ if (left < 60_000) return "less than a minute";+ const minutes = Math.floor(left / 60_000);+ const days = Math.floor(minutes / 1_440);+ const hours = Math.floor((minutes % 1_440) / 60);+ const rest = minutes % 60;+ if (days > 0) return `${days}d ${hours}h`;+ if (hours > 0) return `${hours}h ${rest}m`;+ return `${rest}m`;+}++/** The banner line: "OmniRush.ai 3.1.0 is required in 5h 12m". */+export function updateBannerText(state: UpdateGateState, appName: string, now: number): string {+ const version = state.minimum ? `${appName} ${state.minimum}` : `A newer ${appName}`;+ const countdown = formatUpdateCountdown(state.deadline, now);+ return countdown ? `${version} is required in ${countdown}` : `${version} is required`;+}++/** The chat input stays disabled while the gate blocks model requests. */+export function chatBlockedByUpdate(state: UpdateGateState): boolean {+ return state.status === "blocked";+}++export type RequiredUpdateAction =+ /** A staged update is ready: install it (Linux AppImage, Windows, Developer ID macOS). */+ | "install"+ /** The updater cannot install this build (ad-hoc macOS, no updater): open the download page. */+ | "open-download"+ /** Start (or keep) the download and install as soon as it is ready. */+ | "download-then-install"+ /** A check or download is running: install when it is ready. */+ | "wait";++/**+ * 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`; a failed check or download does too.+ */+export function requiredUpdateAction(input: {+ supported: boolean;+ installMode: "in-place" | "manual-dmg" | null;+ updaterState: string | null | undefined;+}): RequiredUpdateAction {+ if (!input.supported || input.installMode === "manual-dmg") return "open-download";+ switch (input.updaterState) {+ case "ready":+ return "install";+ case "checking":+ case "downloading":+ return "wait";+ case "error":+ case "blocked":+ case "installer-opened":+ return "open-download";+ default:+ return "download-then-install";+ }+}++/** Whether the background download should start now (in-place updaters only, once per gate). */+export function shouldStartBackgroundDownload(input: {+ gate: UpdateGateState;+ supported: boolean;+ installMode: "in-place" | "manual-dmg" | null;+ updaterState: string | null | undefined;+}): boolean {+ if (input.gate.status === "none" || !input.supported || input.installMode === "manual-dmg") return false;+ return !["checking", "downloading", "ready", "installer-opened"].includes(input.updaterState ?? "");+}++type UpdateGateStore = {+ state: UpdateGateState;+ set: (state: UpdateGateState) => void;+};++export const useUpdateGateStore = create<UpdateGateStore>((set) => ({+ state: NO_UPDATE_GATE,+ set: (state) => set({ state }),+}));++let subscribed = false;++/** Subscribes the store to the desktop bridge once; safe to call from every mount. */+export function connectUpdateGate(): void {+ if (subscribed || typeof window === "undefined") return;+ subscribed = true;+ const apply = (value: unknown) => useUpdateGateStore.getState().set(normalizeUpdateGateState(value));+ window.__omnirushUpdateGateEval = (state) => apply(state ? { ...NO_UPDATE_GATE, ...state } : NO_UPDATE_GATE);+ const desktop = bridge();+ if (!desktop) return;+ desktop.onChange?.(apply);+ void desktop.get?.().then(apply).catch(() => undefined);+}++/** Reads /device/me again through the shell (client_update there is authoritative). */+export function refreshUpdateGate(): void {+ void bridge()?.refresh?.().then((value) => useUpdateGateStore.getState().set(normalizeUpdateGateState(value))).catch(() => undefined);+}++export function useUpdateGateState(): UpdateGateState {+ return useUpdateGateStore((store) => store.state);+}++/** True while model requests are refused for this version: the composer is disabled. */+export function useUpdateGateBlocked(): boolean {+ return useUpdateGateStore((store) => chatBlockedByUpdate(store.state));+}diff --git a/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx b/apps/app/src/react-app/domains/session/chat/new-task-composer.tsxindex 5fa7b24f..bc4878eb 100644--- a/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx+++ b/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx@@ -4,6 +4,7 @@ import type { Agent } from "@opencode-ai/sdk/v2/client";import type { CloudImportedPlugin } from "@/app/cloud/import-state";import { createDenClient, readDenSettings } from "@/app/lib/den";+import { useUpdateGateBlocked } from "@/app/lib/update-gate";import type { OmniRushServerClient } from "@/app/lib/omnirush-server";import type { ComposerAttachment, McpServerEntry, McpStatusMap, ModelOption, ModelRef, SkillCard, SlashCommandOption } from "@/app/types";import { t } from "@/i18n";@@ -120,6 +121,8 @@ const FALLBACK_MODEL: ModelRef = DEFAULT_MODEL;* created session, where the normal send path uploads them into the workspace.*/export function NewTaskComposer(props: NewTaskComposerProps) {+ // Model requests are refused for this app version until it is updated.+ const updateBlocked = useUpdateGateBlocked();const context = props.context;const draftOwnerKey = context?.draftOwnerKey ?? "legacy";const [mentions, setMentions] = useState<Record<string, ComposerMentionKind>>({});@@ -444,7 +447,7 @@ export function NewTaskComposer(props: NewTaskComposerProps) {steering={false}submissionPreparing={props.busy || pendingPrompt !== null || preparingAttachments || failedSubmission !== null}queuedCount={0}- disabled={Boolean(context?.modelUnavailable)}+ disabled={Boolean(context?.modelUnavailable) || updateBlocked}modelUnavailable={context?.modelUnavailable}modelUnavailableMessage={context?.modelUnavailableMessage}organizationModelsEmpty={context?.organizationModelsEmpty}diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsxindex 6b41d454..7adfeb11 100644--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx@@ -7,6 +7,7 @@ import { Check, CirclePause, LoaderCircle, Minimize2 } from "lucide-react";import { toast } from "@/components/ui/sonner";import { captureAnalyticsEvent } from "@/app/lib/analytics";+import { useUpdateGateBlocked } from "@/app/lib/update-gate";import { interruptSessionTurn, sessionNeedsStop, submitAfterInterruption, subscribeSessionInterruption } from "@/app/lib/opencode-interruption";import { createClient, createPromptMessageID, hasAcceptedPromptMessage, isPromptAdmissionUnknown, unwrap } from "@/app/lib/opencode";import { compactSession } from "@/app/lib/opencode-session";@@ -1161,6 +1162,8 @@ export function SessionSurface(props: SessionSurfaceProps) {// global default must not disable a conversation that remembers a valid// model, and a pending catalog (loading or superseded by a workspace// switch) never renders "Model no longer available".+ // Model requests are refused for this app version until it is updated.+ const updateBlocked = useUpdateGateBlocked();const sessionModelUnavailable = props.resolveModelAvailability? props.resolveModelAvailability(sessionModel.selectedModel).status === "unavailable": Boolean(props.modelUnavailable);@@ -3310,7 +3313,7 @@ export function SessionSurface(props: SessionSurfaceProps) {steering={steering}submissionPreparing={preparingCloudTools || sending || autoSending}queuedCount={queuedItems.length}- disabled={model.transitionState !== "idle" || sessionModelUnavailable || queuedDrainState.phase.kind === "admission_unknown"}+ disabled={model.transitionState !== "idle" || sessionModelUnavailable || queuedDrainState.phase.kind === "admission_unknown" || updateBlocked}modelUnavailable={sessionModelUnavailable}modelUnavailableMessage={sessionModelUnavailable ? props.modelUnavailableMessage : null}organizationModelsEmpty={props.organizationModelsEmpty}diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsxindex 7c2c2bbf..efe2c6e8 100644--- a/apps/app/src/react-app/shell/app-root.tsx+++ b/apps/app/src/react-app/shell/app-root.tsx@@ -45,6 +45,7 @@ import {import { OmniRushContextPublisher } from "./omnirush-context-publisher";import { SessionRoute } from "./session-route";import { DesktopUpdaterProvider } from "../domains/settings/state/desktop-updater-provider";+import { UpdateGate } from "./update-gate";import { SettingsRoute } from "./settings-route";import { ShellConfigProvider } from "./shell-config";import { WelcomeRoute } from "./welcome-route";@@ -380,6 +381,7 @@ export function AppRoot() {<><DevProfiler id="AppRoot"><DesktopUpdaterProvider>+ <UpdateGate><ShellConfigProvider><AppMenuProvider><OmniRushControlProvider>@@ -515,6 +517,7 @@ export function AppRoot() {</OmniRushControlProvider></AppMenuProvider></ShellConfigProvider>+ </UpdateGate></DesktopUpdaterProvider></DevProfiler>{/*diff --git a/apps/app/src/react-app/shell/update-gate.tsx b/apps/app/src/react-app/shell/update-gate.tsxnew file mode 100644index 00000000..9b795c11--- /dev/null+++ b/apps/app/src/react-app/shell/update-gate.tsx@@ -0,0 +1,253 @@+/** @jsxImportSource react */+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";+import { ArrowUpCircle, Download, Loader2 } from "lucide-react";++import {+ connectUpdateGate,+ refreshUpdateGate,+ requiredUpdateAction,+ shouldStartBackgroundDownload,+ updateBannerText,+ useUpdateGateState,+ type UpdateGateState,+} from "../../app/lib/update-gate";+import { useBrandAppName } from "../domains/cloud/brand-theme";+import { useDesktopUpdater } from "../domains/settings/state/desktop-updater-provider";++/** Height of the required-update banner; the app below it is shifted by this much. */+const BANNER_HEIGHT_PX = 36;++function useNow(active: boolean, intervalMs = 15_000): number {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!active) return;+ setNow(Date.now());+ const timer = window.setInterval(() => setNow(Date.now()), intervalMs);+ return () => window.clearInterval(timer);+ }, [active, intervalMs]);+ return now;+}++function openDownload(url: string) {+ void window.__OMNIRUSH_ELECTRON__?.shell?.openExternal?.(url);+}++/**+ * 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).+ */+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 [installRequested, setInstallRequested] = useState(false);+ const backgroundStarted = useRef(false);+ const downloadRequested = useRef(false);++ useEffect(() => {+ if (gate.status === "none") {+ backgroundStarted.current = false;+ downloadRequested.current = false;+ return;+ }+ if (backgroundStarted.current) return;+ if (!shouldStartBackgroundDownload({ gate, supported, installMode, updaterState })) return;+ backgroundStarted.current = true;+ // A check downloads by itself when automatic downloads are on; the+ // effect below starts the download when they are off.+ void updater.checkForUpdates();+ }, [gate, installMode, supported, updater, updaterState]);++ useEffect(() => {+ if (gate.status === "none" || installMode === "manual-dmg") return;+ if (updaterState === "available" && !downloadRequested.current) {+ downloadRequested.current = true;+ void updater.downloadUpdate();+ }+ }, [gate.status, installMode, updater, updaterState]);++ const previousState = useRef(updaterState);+ useEffect(() => {+ const previous = previousState.current;+ previousState.current = updaterState;+ if (!installRequested) return;+ // A check that ended without an update (the feed is behind the+ // required version): the download page is the way forward.+ if (previous === "checking" && (updaterState === "idle" || updaterState === null)) {+ setInstallRequested(false);+ openDownload(gate.downloadUrl);+ return;+ }+ const action = requiredUpdateAction({ supported, installMode, updaterState });+ if (action === "install") {+ setInstallRequested(false);+ void updater.installUpdateAndRestart();+ } else if (action === "open-download") {+ setInstallRequested(false);+ openDownload(gate.downloadUrl);+ }+ }, [gate.downloadUrl, installMode, installRequested, supported, updater, updaterState]);++ const updateNow = useCallback(() => {+ const action = requiredUpdateAction({ supported, installMode, updaterState });+ if (action === "open-download") {+ openDownload(gate.downloadUrl);+ return;+ }+ if (action === "install") {+ void updater.installUpdateAndRestart();+ return;+ }+ setInstallRequested(true);+ if (action === "download-then-install") {+ if (updaterState === "available") void updater.downloadUpdate();+ else void updater.checkForUpdates();+ }+ }, [gate.downloadUrl, installMode, supported, updater, updaterState]);++ const progress = updater.updateStatus?.state === "downloading" && updater.updateStatus.totalBytes+ ? Math.min(100, Math.round(((updater.updateStatus.downloadedBytes ?? 0) / updater.updateStatus.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 };+}++function UpdateNowButton(props: { onClick: () => void; working: boolean; large?: boolean; testId: string }) {+ return (+ <button+ type="button"+ data-testid={props.testId}+ onClick={props.onClick}+ disabled={props.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+ </button>+ );+}++export function RequiredUpdateBanner(props: { gate: UpdateGateState; appName: string; onUpdateNow: () => void; working: boolean; detail: string | null }) {+ const now = useNow(true);+ const text = updateBannerText(props.gate, props.appName, now);+ return (+ <div+ role="alert"+ aria-live="polite"+ data-testid="update-required-banner"+ data-update-deadline={props.gate.deadline ?? undefined}+ className="fixed inset-x-0 top-0 z-[70] flex items-center justify-center gap-3 border-b border-amber-700/30 bg-amber-300 px-4 text-[12px] font-medium text-amber-950 mac:titlebar-drag mac:ps-20"+ style={{ height: BANNER_HEIGHT_PX }}+ >+ <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" />+ </div>+ );+}++export function UpdateRequiredView(props: { gate: UpdateGateState; appName: string; onUpdateNow: () => void; working: boolean; detail: string | null }) {+ const { gate, appName } = props;+ return (+ <main+ role="alertdialog"+ aria-modal="true"+ aria-labelledby="update-required-title"+ data-testid="update-required-view"+ className="fixed inset-0 z-[80] flex items-center justify-center overflow-y-auto bg-[#05070c] px-6 py-12 text-white mac:titlebar-drag"+ >+ <section className="w-full max-w-xl rounded-[28px] border border-white/10 bg-white/[0.04] p-8 shadow-2xl shadow-black/40 sm:p-10">+ <div className="inline-flex rounded-full border border-amber-300/30 bg-amber-300/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.24em] text-amber-100">+ Update required+ </div>+ <h1 id="update-required-title" className="mt-6 text-3xl font-semibold tracking-[-0.03em] sm:text-4xl">+ Update {appName} to keep working+ </h1>+ <p className="mt-4 text-base leading-7 text-white/72" data-testid="update-required-message">+ {gate.message ?? `This version of ${appName} is no longer supported. Install ${gate.minimum ? `version ${gate.minimum} or newer` : "the latest version"} to keep using models.`}+ </p>+ <p className="mt-3 text-sm leading-6 text-white/55">+ Your sessions and settings stay on this computer, and sessions you already ran keep uploading in the background. After the update, open the same session and continue where you left off.+ </p>+ <div className="mt-6 grid grid-cols-2 gap-3 text-sm">+ <div className="rounded-2xl border border-white/10 bg-black/20 p-4">+ <div className="text-xs uppercase tracking-[0.2em] text-white/40">This version</div>+ <div className="mt-1 font-mono text-lg text-white" data-testid="update-required-current">{gate.current || "unknown"}</div>+ </div>+ <div className="rounded-2xl border border-emerald-300/20 bg-emerald-300/10 p-4">+ <div className="text-xs uppercase tracking-[0.2em] text-emerald-100/70">Required</div>+ <div className="mt-1 font-mono text-lg text-emerald-50" data-testid="update-required-minimum">{gate.minimum ?? "latest"}</div>+ </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" />+ <button+ type="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+ </button>+ </div>+ {props.detail ? <p className="mt-4 text-sm text-white/60" data-testid="update-required-detail">{props.detail}</p> : null}+ </section>+ </main>+ );+}++/**+ * Mandatory client update. Required: a banner that cannot be dismissed, with+ * a countdown to the deadline, above the app (shifted down beneath it).+ * Blocked: a full-screen "Update required" view over the app, which stays+ * mounted underneath; the chat input is disabled (useUpdateGateBlocked).+ * Session uploads run in the Electron main process and are not touched.+ */+export function UpdateGate({ children }: { children: ReactNode }) {+ const gate = useUpdateGateState();+ // 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);++ useEffect(() => {+ connectUpdateGate();+ }, []);++ // client_update on /device/me is authoritative: look again when the+ // window comes back, so a gate the server lifted goes away.+ useEffect(() => {+ if (gate.status === "none") return;+ window.addEventListener("focus", refreshUpdateGate);+ return () => window.removeEventListener("focus", refreshUpdateGate);+ }, [gate.status]);++ const banner = gate.status === "required";+ return (+ <>+ {banner ? <RequiredUpdateBanner gate={gate} appName={appName} onUpdateNow={updateNow} working={working} detail={detail} /> : null}+ <div+ data-update-gate-shifted={banner ? "" : undefined}+ style={banner+ ? { position: "fixed", inset: `${BANNER_HEIGHT_PX}px 0 0 0`, transform: "translateZ(0)", overflow: "hidden" }+ : { display: "contents" }}+ >+ {children}+ </div>+ {gate.status === "blocked" ? <UpdateRequiredView gate={gate} appName={appName} onUpdateNow={updateNow} working={working} detail={detail} /> : null}+ </>+ );+}diff --git a/apps/app/tests/update-gate.test.tsx b/apps/app/tests/update-gate.test.tsxnew file mode 100644index 00000000..084c642c--- /dev/null+++ b/apps/app/tests/update-gate.test.tsx@@ -0,0 +1,137 @@+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, test } from "bun:test";+import { renderToStaticMarkup } from "react-dom/server";++import {+ NO_UPDATE_GATE,+ chatBlockedByUpdate,+ formatUpdateCountdown,+ normalizeUpdateGateState,+ requiredUpdateAction,+ shouldStartBackgroundDownload,+ updateBannerText,+ useUpdateGateStore,+ type UpdateGateState,+} from "../src/app/lib/update-gate";+import { RequiredUpdateBanner, UpdateRequiredView } from "../src/react-app/shell/update-gate";++const read = (relative: string) => readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");++const NOW = Date.parse("2026-10-04T12:00:00Z");+const required: UpdateGateState = {+ status: "required",+ current: "3.0.2",+ minimum: "3.1.0",+ deadline: "2026-10-04T17:12:00.000Z",+ message: null,+ downloadUrl: "https://omnirush.ai/download",+ source: "header",+};+const blocked: UpdateGateState = { ...required, status: "blocked", message: "Update OmniRush.ai to 3.1.0 to keep using models.", source: "rejection" };++describe("update gate state from the desktop bridge", () => {+ test("normalizes the main-process state and rejects anything malformed", () => {+ expect(normalizeUpdateGateState(required)).toEqual(required);+ expect(normalizeUpdateGateState(null)).toEqual(NO_UPDATE_GATE);+ expect(normalizeUpdateGateState({ status: "panic", deadline: "soon", downloadUrl: "" })).toEqual({+ ...NO_UPDATE_GATE,+ status: "none",+ });+ });++ test("only the blocked state disables the chat input", () => {+ expect(chatBlockedByUpdate(blocked)).toBe(true);+ expect(chatBlockedByUpdate(required)).toBe(false);+ expect(chatBlockedByUpdate(NO_UPDATE_GATE)).toBe(false);+ });+});++describe("required-update banner", () => {+ test("counts down to the deadline", () => {+ expect(formatUpdateCountdown(required.deadline, NOW)).toBe("5h 12m");+ expect(formatUpdateCountdown(required.deadline, NOW + 5 * 3_600_000)).toBe("12m");+ expect(formatUpdateCountdown("2026-10-06T16:00:00Z", NOW)).toBe("2d 4h");+ expect(formatUpdateCountdown(required.deadline, Date.parse(required.deadline!) - 10_000)).toBe("less than a minute");+ expect(formatUpdateCountdown(null, NOW)).toBeNull();+ });++ test("names the required version", () => {+ expect(updateBannerText(required, "OmniRush.ai", NOW)).toBe("OmniRush.ai 3.1.0 is required in 5h 12m");+ 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", () => {+ const html = renderToStaticMarkup(+ <RequiredUpdateBanner gate={required} appName="OmniRush.ai" onUpdateNow={() => undefined} working={false} detail={null} />,+ );+ 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.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", () => {+ const html = renderToStaticMarkup(+ <UpdateRequiredView gate={blocked} appName="OmniRush.ai" onUpdateNow={() => undefined} working={false} detail="Downloading the update… 40%" />,+ );+ expect(html).toContain("data-testid=\"update-required-view\"");+ expect(html).toContain("fixed inset-0");+ expect(html).toContain("Update required");+ 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("keep uploading in the background");+ expect(html).toContain("Downloading the update… 40%");+ });+});++describe("Update now", () => {+ test("installs a staged update in place (Linux AppImage, Windows, Developer ID macOS)", () => {+ 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.+ expect(requiredUpdateAction({ supported: true, installMode: "manual-dmg", updaterState: "ready" })).toBe("open-download");+ expect(requiredUpdateAction({ supported: false, installMode: null, updaterState: null })).toBe("open-download");+ expect(requiredUpdateAction({ supported: true, installMode: "in-place", updaterState: "error" })).toBe("open-download");+ expect(requiredUpdateAction({ supported: true, installMode: "in-place", updaterState: "blocked" })).toBe("open-download");+ });++ test("the download starts in the background as soon as an update is required", () => {+ const base = { supported: true, installMode: "in-place" as const };+ expect(shouldStartBackgroundDownload({ ...base, gate: required, updaterState: null })).toBe(true);+ expect(shouldStartBackgroundDownload({ ...base, gate: blocked, updaterState: "idle" })).toBe(true);+ expect(shouldStartBackgroundDownload({ ...base, gate: required, updaterState: "downloading" })).toBe(false);+ 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);+ });+});++describe("wiring", () => {+ test("both composers are disabled while the gate blocks", () => {+ expect(read("../src/react-app/domains/session/surface/session-surface.tsx")).toMatch(/disabled=\{[^}]*\|\| updateBlocked\}/);+ expect(read("../src/react-app/domains/session/chat/new-task-composer.tsx")).toMatch(/disabled=\{[^}]*\|\| updateBlocked\}/);+ useUpdateGateStore.getState().set(blocked);+ expect(chatBlockedByUpdate(useUpdateGateStore.getState().state)).toBe(true);+ useUpdateGateStore.getState().set(NO_UPDATE_GATE);+ });++ test("the gate only covers the UI: it never stops the session uploader or signs out", () => {+ const gate = read("../src/react-app/shell/update-gate.tsx") + read("../src/app/lib/update-gate.ts");+ for (const forbidden of ["signOut", "omnirushAccountSignOut", "omnirushServerRestart", "capture", "uploader", "nuke"]) {+ expect(gate).not.toContain(forbidden);+ }+ // The blocked view overlays the app instead of unmounting it.+ expect(read("../src/react-app/shell/update-gate.tsx")).toContain("{children}");+ });+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 2406e8b3..b0bcc3e9 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -85,6 +85,7 @@ import { readSkillFolder } from "./skill-folder.mjs";import { createDesktopVaultKeyProvider } from "./secure-vault-key.mjs";import { applyLinuxPasswordStore, recordLinuxPasswordStore } from "./linux-password-store.mjs";import { createDesktopOmniRushAccountStore, legacyKeychainAllowed } from "./omnirush-account.mjs";+import { UPDATE_GATE_CHANNEL, createUpdateGate } from "./update-gate.mjs";import { createExternalFetch, createExternalFileUpload } from "./external-fetch.mjs";import {clearOmniRushSentrySession,@@ -1332,6 +1333,21 @@ function validateSkillName(raw) {return trimmed;}+// Mandatory client update (update-gate.mjs): the banner and the blocked view+// in the renderer follow this state. It never stops the capture service, so+// session uploads keep flushing while the app waits to be updated.+const updateGate = createUpdateGate({+ appVersion: app.getVersion(),+ log: (message) => console.info(message),+ onChange: (state) => {+ try {+ if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send(UPDATE_GATE_CHANNEL, state);+ } catch {+ // The window may be closing; the renderer reads the state again on load.+ }+ },+});+const omnirushAccountStore = createDesktopOmniRushAccountStore({filePath: path.join(app.getPath("userData"), "omnirush-account.bin"),// Sign-in, device code, token refresh, profile and sign-out.@@ -1340,6 +1356,7 @@ const omnirushAccountStore = createDesktopOmniRushAccountStore({// Linux without a usable keyring only; unencrypted at rest, owner-only.fallbackFilePath: path.join(app.getPath("userData"), "private-credentials", "omnirush-account.json"),onKeyringSealed: recordKeyringSealed("omnirush-account.bin"),+ onClientUpdate: (clientUpdate) => updateGate.signal({ kind: "profile", clientUpdate }),legacyKeychain: legacyKeychainAllowed({appIdentifier: APP_IDENTIFIER,productionAppIdentifier: TAURI_APP_IDENTIFIER,@@ -1385,6 +1402,8 @@ const runtimeManager = createRuntimeManager({onKeyringSealed: recordKeyringSealed("local-managed-mcp-vault-key.bin"),}),omnirushGatewayCredentials: omnirushAccountStore,+ // The gateway's x-omnirush-update-required header and 426 refusals.+ onUpdateSignal: (signal) => updateGate.signal(signal),// Session upload envelopes report environment.app_version from the desktop build, not the server package.appVersion: app.getVersion(),});@@ -2774,6 +2793,21 @@ ipcMain.handle("omnirush:shell:openExternal", async (_event, url) => {}return openExternalUrl(url.trim());});+ipcMain.handle("omnirush:update-gate:get", async () => updateGate.state());+// Asks /device/me again (the renderer does on focus too): client_update there+// is authoritative, so an update the server stopped requiring clears the gate.+ipcMain.handle("omnirush:update-gate:refresh", async () => {+ await omnirushAccountStore.status().catch(() => null);+ return updateGate.state();+});+{+ // The profile is read at launch and every 30 minutes even when no+ // account view is open, so a required update is known before the+ // deadline, not only from the first refused model request.+ const readProfile = () => { void omnirushAccountStore.status().catch(() => null); };+ setTimeout(readProfile, 15_000).unref?.();+ setInterval(readProfile, 30 * 60_000).unref?.();+}ipcMain.handle("omnirush:shell:relaunch", async () => {app.relaunch();app.quit();diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex c7822f61..2c6dc893 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -12,6 +12,7 @@ import {usableSafeStorage,writePlaintextCredentialFile,} from "./plaintext-credential-file.mjs";+import { parseClientUpdate } from "./update-gate.mjs";const execFileAsync = promisify(execFile);@@ -236,6 +237,7 @@ function accountProfile(value) {displayName: normalizeCredential(value.display_name) ?? displayNameFromEmail(email),status: normalizeCredential(value.status),usage,+ clientUpdate: parseClientUpdate(value.client_update),};}@@ -308,7 +310,20 @@ export function createDesktopOmniRushAccountStore({now = () => Date.now(),// First pause before a failed save of a rotated pair is tried again; tests shrink it.persistRetryBaseMs = 1_000,+ // Hears `client_update` from /device/me, sign-in and refresh answers+ // (update-gate.mjs); null when an answer carried none.+ onClientUpdate = null,}) {+ /** A `client_update` this account server sent; never lets the gate break sign-in. */+ function reportClientUpdate(payload) {+ if (typeof onClientUpdate !== "function" || !payload || typeof payload !== "object") return;+ try {+ onClientUpdate(parseClientUpdate(payload.client_update));+ } catch {+ // The gate is advisory here; the account flow goes on.+ }+ }+// This store is the one owner of the device session's refresh token: its// own profile check and the embedded broker (runtime.mjs wires the// broker's `refresh` to refresh() below) both come here, and only here is@@ -812,6 +827,7 @@ export function createDesktopOmniRushAccountStore({}try {const payload = await response.json();+ if (payload && typeof payload === "object" && "client_update" in payload) reportClientUpdate(payload);const rotated = validCredentials({gatewayUrl: payload.gateway_url ?? credentials.gatewayUrl,accessToken: payload.access_token,@@ -914,7 +930,10 @@ export function createDesktopOmniRushAccountStore({throw new InvalidAccountCredentialsError("Device session expired");}if (!response.ok) return null;- return accountProfile(await response.json());+ const payload = await response.json();+ // /device/me is authoritative: no client_update there clears the gate.+ reportClientUpdate(payload && typeof payload === "object" ? payload : {});+ return accountProfile(payload);}async function authorize({ gatewayUrl, deviceName, openVerification }) {@@ -950,6 +969,7 @@ export function createDesktopOmniRushAccountStore({if (tokenResponse.status === 428) continue;if (!tokenResponse.ok) throw new Error(`Account link failed (${tokenResponse.status})`);const payload = await tokenResponse.json();+ if (payload && typeof payload === "object" && "client_update" in payload) reportClientUpdate(payload);const credentials = validCredentials({gatewayUrl: payload.gateway_url ?? configured,accessToken: payload.access_token,@@ -1017,6 +1037,7 @@ export function createDesktopOmniRushAccountStore({displayName: profile?.displayName ?? null,accountStatus: profile?.status ?? null,usage: profile?.usage ?? null,+ clientUpdate: profile?.clientUpdate ?? null,};} catch (error) {if (error instanceof InvalidAccountCredentialsError) {diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjsindex d66e0525..028f33a7 100644--- a/apps/desktop/electron/omnirush-account.test.mjs+++ b/apps/desktop/electron/omnirush-account.test.mjs@@ -1295,3 +1295,43 @@ test("a session the server ended in file mode is not reported as a missing keyriassert.equal(status.reauthorizationRequired, true);assert.equal(status.keyringUnavailable, undefined);});++test("client_update on /device/me reaches the update gate and the account status", async () => {+ const heard = [];+ let clientUpdate = {+ required: true,+ product: "gui",+ current: "3.0.2",+ minimum: "3.1.0",+ deadline: "2026-10-04T17:12:00Z",+ blocked: false,+ message: "Update to 3.1.0",+ download_url: "https://omnirush.ai/download",+ };+ const options = await storeOptions({+ env: LEGACY_ENV,+ onClientUpdate: (value) => heard.push(value),+ fetchImpl: async () => Response.json({ email: "[email protected]", status: "active", ...(clientUpdate ? { client_update: clientUpdate } : {}) }),+ });+ const store = createDesktopOmniRushAccountStore(options);+ const status = await store.status();+ assert.equal(status.connected, true);+ assert.deepEqual(status.clientUpdate, {+ required: true,+ blocked: false,+ current: "3.0.2",+ minimum: "3.1.0",+ deadline: "2026-10-04T17:12:00.000Z",+ message: "Update to 3.1.0",+ downloadUrl: "https://omnirush.ai/download",+ });+ assert.equal(heard.length, 1);+ assert.equal(heard[0].minimum, "3.1.0");+ // A profile without client_update is heard as null: the server lifted it.+ clientUpdate = null;+ assert.equal((await store.status()).clientUpdate, null);+ assert.deepEqual(heard.slice(1), [null]);+ // A listener that throws never breaks the account status.+ const throwing = createDesktopOmniRushAccountStore({ ...options, onClientUpdate: () => { throw new Error("listener"); } });+ assert.equal((await throwing.status()).connected, true);+});diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjsindex 4999a418..a5ca34da 100644--- a/apps/desktop/electron/preload.mjs+++ b/apps/desktop/electron/preload.mjs@@ -168,6 +168,23 @@ contextBridge.exposeInMainWorld("__OMNIRUSH_ELECTRON__", {};},},+ updateGate: {+ /** The mandatory-update state (update-gate.mjs): "none", "required" or "blocked". */+ get() {+ return ipcRenderer.invoke("omnirush:update-gate:get");+ },+ /** Reads /device/me again and resolves the state it leaves. */+ refresh() {+ return ipcRenderer.invoke("omnirush:update-gate:refresh");+ },+ onChange(callback) {+ const handler = (_event, state) => callback(state);+ ipcRenderer.on("omnirush:update-gate:changed", handler);+ return () => {+ ipcRenderer.removeListener("omnirush:update-gate:changed", handler);+ };+ },+ },recovery: {recordHealthy() {return ipcRenderer.invoke("omnirush:recovery:recordHealthy");diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjsindex 76a4adce..be784125 100644--- a/apps/desktop/electron/runtime.mjs+++ b/apps/desktop/electron/runtime.mjs@@ -1419,6 +1419,8 @@ export function createRuntimeManager({// Chromium-backed fetch for requests off the machine (see external-fetch.mjs).externalFetch = null,captureFileUpload = null,+ // Hears the gateway's mandatory-update header and 426 refusals (update-gate.mjs).+ onUpdateSignal = null,}) {const inheritedProcessEnv = { ...process.env };let injectedUserEnvKeys = new Set();@@ -2235,6 +2237,7 @@ export function createRuntimeManager({refresh: (rejectedAccessToken) => omnirushGatewayCredentials.refresh(rejectedAccessToken),invalidate: () => omnirushGatewayCredentials.clear({ revokeRemote: false }),latest: () => omnirushGatewayCredentials.load(),+ ...(typeof onUpdateSignal === "function" ? { onUpdateSignal } : {}),// Name and email for the git commit identity default; the account// store owns the profile lookup and its token refresh.profile: async () => {diff --git a/apps/desktop/electron/update-gate.mjs b/apps/desktop/electron/update-gate.mjsnew file mode 100644index 00000000..cda4af77--- /dev/null+++ b/apps/desktop/electron/update-gate.mjs@@ -0,0 +1,232 @@+/**+ * Mandatory client update: what omnirush.ai says about this app's version.+ *+ * Three signals, newest wins:+ * - `client_update` on /device/me (and on the sign-in and refresh JSON):+ * `{required, product, current, minimum, deadline, blocked, message,+ * download_url}`. Only `product: "gui"` (or none) applies to this app.+ * - `x-omnirush-update-required: <minimum>; deadline=<iso>` on gateway+ * responses before the deadline.+ * - HTTP 426 `{"error":{"code":"update_required",...}}` on model requests+ * after it.+ *+ * Required: a banner with a countdown, the update downloads in the+ * background. Blocked (the server says so, a 426 came back, or the deadline+ * passed): a full-screen "Update required" view. Neither ever stops session+ * uploads or project archives: those routes are never blocked, and the+ * capture service keeps flushing whatever this version recorded.+ */++export const UPDATE_GATE_CHANNEL = "omnirush:update-gate:changed";+export const DEFAULT_DOWNLOAD_URL = "https://omnirush.ai/download";++/**+ * @typedef {{+ * required: boolean,+ * blocked: boolean,+ * current: string | null,+ * minimum: string | null,+ * deadline: string | null,+ * message: string | null,+ * downloadUrl: string | null,+ * }} ClientUpdate+ *+ * @typedef {{+ * status: "none" | "required" | "blocked",+ * current: string,+ * minimum: string | null,+ * deadline: string | null,+ * message: string | null,+ * downloadUrl: string,+ * source: "profile" | "header" | "rejection" | null,+ * }} UpdateGateState+ */++function text(value) {+ return typeof value === "string" && value.trim() ? value.trim() : null;+}++function isoTime(value) {+ const raw = text(value);+ return raw && Number.isFinite(Date.parse(raw)) ? new Date(Date.parse(raw)).toISOString() : null;+}++function httpsUrl(value) {+ const raw = text(value);+ if (!raw) return null;+ try {+ const url = new URL(raw);+ return url.protocol === "https:" || url.protocol === "http:" ? url.toString() : null;+ } catch {+ return null;+ }+}++function versionParts(value) {+ const raw = text(value)?.replace(/^v/i, "");+ if (!raw) return null;+ const [core, prerelease = ""] = raw.split("+", 1)[0].split("-", 2);+ const release = core.split(".").map((part) => Number(part));+ if (!release.length || release.some((part) => !Number.isInteger(part) || part < 0)) return null;+ return { release, prerelease };+}++/** -1, 0 or 1; null when either side is not a version. A prerelease ranks below its release. */+export function compareVersions(left, right) {+ const a = versionParts(left);+ const b = versionParts(right);+ if (!a || !b) return null;+ for (let index = 0; index < Math.max(a.release.length, b.release.length); index += 1) {+ const difference = (a.release[index] ?? 0) - (b.release[index] ?? 0);+ if (difference) return difference < 0 ? -1 : 1;+ }+ if (a.prerelease === b.prerelease) return 0;+ if (!a.prerelease) return 1;+ if (!b.prerelease) return -1;+ return a.prerelease < b.prerelease ? -1 : 1;+}++/**+ * `client_update` from a /device/me, sign-in or refresh payload. Null when+ * absent, malformed, or addressed to another product (the CLI).+ * @returns {ClientUpdate | null}+ */+export function parseClientUpdate(value) {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const product = text(value.product)?.toLowerCase() ?? null;+ if (product && product !== "gui") return null;+ return {+ required: value.required === true,+ blocked: value.blocked === true,+ current: text(value.current),+ minimum: text(value.minimum),+ deadline: isoTime(value.deadline),+ message: text(value.message),+ downloadUrl: httpsUrl(value.download_url),+ };+}++/**+ * `x-omnirush-update-required: 3.1.0; deadline=2026-10-05T12:00:00Z`.+ * @returns {{ minimum: string, deadline: string | null } | null}+ */+export function parseUpdateRequiredHeader(value) {+ const raw = text(value);+ if (!raw) return null;+ const [first, ...params] = raw.split(";").map((part) => part.trim());+ if (!first || !versionParts(first)) return null;+ let deadline = null;+ for (const param of params) {+ const [name, ...rest] = param.split("=");+ if (name?.trim().toLowerCase() === "deadline") deadline = isoTime(rest.join("=").replace(/^"|"$/g, ""));+ }+ return { minimum: first.replace(/^v/i, ""), deadline };+}++/**+ * The app's view of the update requirement. `signal()` takes any of the+ * three inputs; `onChange` hears every change in the derived state.+ * @param {{ appVersion: string, onChange?: (state: UpdateGateState) => void, now?: () => number, log?: (message: string) => void }} options+ */+export function createUpdateGate({ appVersion, onChange = () => {}, now = () => Date.now(), log = () => {} }) {+ /** @type {{ required: boolean, blocked: boolean, minimum: string | null, deadline: string | null, message: string | null, downloadUrl: string | null, source: UpdateGateState["source"] }} */+ let facts = { required: false, blocked: false, minimum: null, deadline: null, message: null, downloadUrl: null, source: null };+ let last = "";+ let timer = null;++ /** A minimum this version already meets never gates it (a stale header, a server mistake). */+ function satisfied(minimum) {+ const order = minimum ? compareVersions(appVersion, minimum) : null;+ return order !== null && order >= 0;+ }++ /** @returns {UpdateGateState} */+ function state() {+ const pastDeadline = facts.deadline !== null && Date.parse(facts.deadline) <= now();+ const active = (facts.required || facts.blocked) && !satisfied(facts.minimum);+ const status = !active ? "none" : facts.blocked || pastDeadline ? "blocked" : "required";+ return {+ status,+ current: appVersion,+ minimum: active ? facts.minimum : null,+ deadline: active ? facts.deadline : null,+ message: active ? facts.message : null,+ downloadUrl: facts.downloadUrl ?? DEFAULT_DOWNLOAD_URL,+ source: active ? facts.source : null,+ };+ }++ function publish() {+ const next = state();+ const key = JSON.stringify(next);+ if (key !== last) {+ last = key;+ log(`[update-gate] ${next.status}${next.minimum ? ` (minimum ${next.minimum}, deadline ${next.deadline ?? "none"}, via ${next.source})` : ""}`);+ onChange(next);+ }+ // Flip to blocked when the deadline passes while the app is open.+ if (timer) clearTimeout(timer);+ timer = null;+ if (next.status === "required" && next.deadline) {+ const wait = Math.min(Math.max(Date.parse(next.deadline) - now(), 0) + 500, 2 ** 31 - 1);+ timer = setTimeout(publish, wait);+ timer.unref?.();+ }+ }++ /**+ * @param {{ kind: "profile", clientUpdate: ClientUpdate | null }+ * | { kind: "header", value: string | null | undefined }+ * | { kind: "rejection", message?: string | null }} input+ */+ function signal(input) {+ if (input.kind === "profile") {+ const update = input.clientUpdate;+ // The account server's own answer is authoritative, in both directions.+ if (!update || (!update.required && !update.blocked)) {+ facts = { ...facts, required: false, blocked: false, minimum: null, deadline: null, message: null, source: null,+ downloadUrl: update?.downloadUrl ?? facts.downloadUrl };+ } else {+ facts = {+ required: true,+ blocked: update.blocked,+ minimum: update.minimum ?? facts.minimum,+ deadline: update.deadline ?? facts.deadline,+ message: update.message,+ downloadUrl: update.downloadUrl ?? facts.downloadUrl,+ source: "profile",+ };+ }+ } else if (input.kind === "header") {+ const parsed = parseUpdateRequiredHeader(input.value);+ if (!parsed || satisfied(parsed.minimum)) return state();+ facts = {+ ...facts,+ required: true,+ minimum: parsed.minimum,+ deadline: parsed.deadline ?? facts.deadline,+ source: facts.blocked ? facts.source : "header",+ };+ } else if (input.kind === "rejection") {+ facts = {+ ...facts,+ required: true,+ blocked: true,+ message: text(input.message) ?? facts.message,+ source: "rejection",+ };+ }+ publish();+ return state();+ }++ // Only changes are published: the launch state ("none") is not one.+ last = JSON.stringify(state());++ function dispose() {+ if (timer) clearTimeout(timer);+ timer = null;+ }++ return { state, signal, dispose };+}diff --git a/apps/desktop/electron/update-gate.test.mjs b/apps/desktop/electron/update-gate.test.mjsnew file mode 100644index 00000000..f7ef0e69--- /dev/null+++ b/apps/desktop/electron/update-gate.test.mjs@@ -0,0 +1,124 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ DEFAULT_DOWNLOAD_URL,+ compareVersions,+ createUpdateGate,+ parseClientUpdate,+ parseUpdateRequiredHeader,+} from "./update-gate.mjs";++const NOW = Date.parse("2026-10-04T12:00:00Z");+const DEADLINE = "2026-10-04T17:12:00.000Z";++function gate(appVersion = "3.0.2", now = () => NOW) {+ const changes = [];+ const subject = createUpdateGate({ appVersion, now, onChange: (state) => changes.push(state) });+ return { subject, changes };+}++test("client_update for the GUI is parsed; the CLI's is ignored", () => {+ assert.deepEqual(parseClientUpdate({+ required: true,+ product: "gui",+ current: "3.0.2",+ minimum: "3.1.0",+ deadline: "2026-10-04T17:12:00Z",+ blocked: false,+ message: "Update to 3.1.0",+ download_url: "https://omnirush.ai/download",+ }), {+ required: true,+ blocked: false,+ current: "3.0.2",+ minimum: "3.1.0",+ deadline: DEADLINE,+ message: "Update to 3.1.0",+ downloadUrl: "https://omnirush.ai/download",+ });+ assert.equal(parseClientUpdate({ required: true, product: "cli", minimum: "1.0.0" }), null);+ assert.equal(parseClientUpdate(null), null);+ assert.equal(parseClientUpdate("required"), null);+ const loose = parseClientUpdate({ required: "yes", deadline: "soon", download_url: "javascript:alert(1)" });+ assert.equal(loose.required, false);+ assert.equal(loose.deadline, null);+ assert.equal(loose.downloadUrl, null);+});++test("the update-required header gives the minimum and the deadline", () => {+ assert.deepEqual(parseUpdateRequiredHeader("3.1.0; deadline=2026-10-04T17:12:00Z"), { minimum: "3.1.0", deadline: DEADLINE });+ assert.deepEqual(parseUpdateRequiredHeader("v3.1.0"), { minimum: "3.1.0", deadline: null });+ assert.deepEqual(parseUpdateRequiredHeader("3.1.0;Deadline=\"2026-10-04T17:12:00Z\""), { minimum: "3.1.0", deadline: DEADLINE });+ assert.equal(parseUpdateRequiredHeader(""), null);+ assert.equal(parseUpdateRequiredHeader("soon; deadline=2026-10-04T17:12:00Z"), null);+});++test("versions compare numerically, a prerelease below its release", () => {+ assert.equal(compareVersions("3.0.2", "3.1.0"), -1);+ assert.equal(compareVersions("3.10.0", "3.9.9"), 1);+ assert.equal(compareVersions("v3.1.0", "3.1"), 0);+ assert.equal(compareVersions("3.1.0-rc.1", "3.1.0"), -1);+ assert.equal(compareVersions("dev", "3.1.0"), null);+});++test("required before the deadline shows the banner state; the deadline passing blocks", () => {+ let now = NOW;+ const { subject, changes } = gate("3.0.2", () => now);+ const state = subject.signal({ kind: "profile", clientUpdate: parseClientUpdate({+ required: true, product: "gui", minimum: "3.1.0", deadline: DEADLINE, download_url: "https://omnirush.ai/dl",+ }) });+ assert.equal(state.status, "required");+ assert.equal(state.minimum, "3.1.0");+ assert.equal(state.deadline, DEADLINE);+ assert.equal(state.downloadUrl, "https://omnirush.ai/dl");+ assert.equal(state.source, "profile");+ now = Date.parse(DEADLINE) + 1;+ assert.equal(subject.state().status, "blocked");+ assert.equal(changes.length, 1);+ subject.dispose();+});++test("client_update.blocked, or a 426 seen, blocks; the server lifting it clears the gate", () => {+ const { subject, changes } = gate();+ assert.equal(subject.signal({ kind: "profile", clientUpdate: parseClientUpdate({ required: true, blocked: true, minimum: "3.1.0" }) }).status, "blocked");+ assert.equal(subject.signal({ kind: "profile", clientUpdate: parseClientUpdate({ required: false }) }).status, "none");+ const rejected = subject.signal({ kind: "rejection", message: "Update OmniRush.ai" });+ assert.equal(rejected.status, "blocked");+ assert.equal(rejected.message, "Update OmniRush.ai");+ assert.equal(rejected.source, "rejection");+ // /device/me without client_update is authoritative too.+ assert.equal(subject.signal({ kind: "profile", clientUpdate: null }).status, "none");+ assert.deepEqual(changes.map((state) => state.status), ["blocked", "none", "blocked", "none"]);+ subject.dispose();+});++test("the header alone makes the update required, and never unblocks", () => {+ const { subject } = gate();+ const required = subject.signal({ kind: "header", value: `3.1.0; deadline=${DEADLINE}` });+ assert.equal(required.status, "required");+ assert.equal(required.source, "header");+ subject.signal({ kind: "rejection", message: null });+ assert.equal(subject.signal({ kind: "header", value: `3.1.0; deadline=${DEADLINE}` }).status, "blocked");+ assert.equal(subject.signal({ kind: "header", value: "garbage" }).status, "blocked");+ subject.dispose();+});++test("a minimum this version already meets never gates it", () => {+ const { subject, changes } = gate("3.1.0");+ assert.equal(subject.signal({ kind: "header", value: `3.1.0; deadline=${DEADLINE}` }).status, "none");+ assert.equal(subject.signal({ kind: "profile", clientUpdate: parseClientUpdate({ required: true, blocked: true, minimum: "3.0.9" }) }).status, "none");+ assert.equal(changes.length, 0);+ assert.equal(subject.state().downloadUrl, DEFAULT_DOWNLOAD_URL);+ subject.dispose();+});++test("the state flips to blocked by itself when the deadline passes while the app is open", async () => {+ const deadline = new Date(Date.now() + 30).toISOString();+ const changes = [];+ const subject = createUpdateGate({ appVersion: "3.0.2", onChange: (state) => changes.push(state.status) });+ subject.signal({ kind: "header", value: `3.1.0; deadline=${deadline}` });+ await new Promise((resolve) => setTimeout(resolve, 700));+ assert.deepEqual(changes, ["required", "blocked"]);+ subject.dispose();+});diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex f59da19b..3de0947c 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,7 +27,7 @@"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build","test:omnirush-account": "node --test electron/omnirush-account.test.mjs",- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs","test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"},diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex c0ec98d1..deb4f9f0 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -53,8 +53,24 @@ type BrokerOptions = {subagentRetryDelayMs?: number;/** Whether a picked sub-agent model is in its refusal cooldown (sent straight to the main model). */subagentModelRefused?: (model: string) => boolean;+ /** Hears the gateway's mandatory-update signals (see GatewayUpdateSignal). */+ onUpdateSignal?: (signal: GatewayUpdateSignal) => void;};+/**+ * omnirush.ai asking this app to update: before the deadline every gateway+ * answer carries `x-omnirush-update-required: <minimum>; deadline=<iso>`;+ * after it, model requests from an outdated app get HTTP 426+ * `update_required`. Session uploads, project archives, sign-in, refresh and+ * the profile are never refused, so nothing here stops them.+ */+export type GatewayUpdateSignal =+ | { kind: "header"; value: string }+ | { kind: "rejection"; message: string | null };++export const UPDATE_REQUIRED_HEADER = "x-omnirush-update-required";+export const UPDATE_REQUIRED_CODE = "update_required";+/*** Upstream model streams have been observed to end mid-response (the proxy* closes the connection while a function call is still streaming). Without a@@ -141,6 +157,7 @@ const GATEWAY_ERROR_COPY: Record<string, string> = {voice_unavailable: "voice input is not available on this account yet.",transcription_unavailable: "the transcription service did not answer. Try again in a moment.",audio_unreadable: "the recording could not be read. Try again.",+ update_required: "this version of OmniRush.ai is no longer supported. Update the app to keep using models; your sessions are kept.",};/** Readable copy for a gateway error code, or null for a code it does not know. */@@ -463,6 +480,8 @@ function readableErrorBody(text: string, grant: string | null): { body: string;const code = bareCode ?? stringField(nested?.code);if (!code) return null;const message = (grant && code === "daily_grant_exhausted" ? `omnirush.ai: ${grant.charAt(0).toLowerCase()}${grant.slice(1)}` : null)+ // The server names the version to install; keep its words.+ ?? (code === UPDATE_REQUIRED_CODE ? stringField(nested?.message) ?? stringField(payload.message) : null)?? gatewayErrorMessage(code, stringField(nested?.message))?? (bareCode ? `omnirush.ai could not complete the model request (${code}).` : null);if (!message) return null;@@ -481,7 +500,10 @@ async function readableErrorResponse(response: Response, consoleUrl: string | nuconst headers = responseHeaders(response.headers);// A spent grant stays spent until its reset: the engine would otherwise// resend the request ten times, each after the 429's Retry-After (60 s).- if (readable?.code === "daily_grant_exhausted") headers.set("x-should-retry", "false");+ // An outdated app stays refused until it is updated.+ if (readable?.code === "daily_grant_exhausted" || readable?.code === UPDATE_REQUIRED_CODE || response.status === 426) {+ headers.set("x-should-retry", "false");+ }return new Response(readable?.body ?? text, {status: response.status,statusText: response.statusText,@@ -733,6 +755,7 @@ const ACCOUNT_REFUSED = new Set(["consent_version_outdated","omnirush_account_required","model_request_too_large",+ "update_required",]);const SUBAGENT_BUSY_STATUSES = new Set([429, 502, 503, 504]);@@ -856,6 +879,7 @@ export class OmniRushGatewayBroker {private readonly onSubagentFallback?: BrokerOptions["onSubagentFallback"];private readonly subagentRetryDelayMs: number;private readonly subagentModelRefused?: (model: string) => boolean;+ private readonly onUpdateSignal?: (signal: GatewayUpdateSignal) => void;private refreshInFlight: Promise<boolean> | null = null;/** Whether the last failed refresh left the session as it was (unreachable, 5xx, contended). */private lastRefreshTransient = false;@@ -881,6 +905,43 @@ export class OmniRushGatewayBroker {this.onSubagentFallback = options.onSubagentFallback;this.subagentRetryDelayMs = options.subagentRetryDelayMs ?? SUBAGENT_RETRY_DELAY_MS;this.subagentModelRefused = options.subagentModelRefused;+ this.onUpdateSignal = options.onUpdateSignal;+ }++ /**+ * Passes the gateway's update signals on: the header from any answer, and+ * a 426 / `update_required` refusal of a model request. Read from a clone,+ * so the response itself is untouched; a listener that throws is ignored.+ */+ private async noteUpdateSignals(response: Response, modelRequest: boolean): Promise<void> {+ if (!this.onUpdateSignal) return;+ try {+ const header = response.headers.get(UPDATE_REQUIRED_HEADER)?.trim();+ if (header) this.onUpdateSignal({ kind: "header", value: header });+ if (!modelRequest || response.ok) return;+ let code = response.status === 426 ? UPDATE_REQUIRED_CODE : null;+ let message: string | null = null;+ if ((response.headers.get("content-type") ?? "").includes("application/json")) {+ const text = await response.clone().text().catch(() => "");+ try {+ const payload: unknown = JSON.parse(text);+ if (isRecord(payload)) {+ const nested = isRecord(payload.error) ? payload.error : null;+ const bodyCode = stringField(nested?.code) ?? stringField(payload.detail) ?? stringField(payload.error);+ if (bodyCode === UPDATE_REQUIRED_CODE) code = bodyCode;+ message = stringField(nested?.message) ?? stringField(payload.message);+ }+ } catch {+ // Not JSON: the status alone decides.+ }+ }+ if (code === UPDATE_REQUIRED_CODE) {+ this.log?.("warn", "omnirush.ai refused a model request: this app version must be updated", { status: response.status });+ this.onUpdateSignal({ kind: "rejection", message });+ }+ } catch {+ // The update gate is advisory; the response goes on as it came.+ }}get enabled(): boolean {@@ -949,6 +1010,7 @@ export class OmniRushGatewayBroker {} else if (!response.ok && response.status !== 401 && body !== undefined) {response = await this.subagentFallback(request, normalizedPath, body, response);}+ await this.noteUpdateSignals(response, true);const contentType = response.headers.get("content-type") ?? "";// Sign-in failures keep their own answer above; every other gateway// refusal reaches the user as readable copy instead of a bare code.@@ -1154,6 +1216,8 @@ export class OmniRushGatewayBroker {spent = this.state.accessToken;response = await send(this.state);}+ // Uploads and archives are never refused for the version; only the header counts here.+ await this.noteUpdateSignals(response, false);return response;}diff --git a/apps/server/src/omnirush-gateway-update-gate.test.ts b/apps/server/src/omnirush-gateway-update-gate.test.tsnew file mode 100644index 00000000..59941622--- /dev/null+++ b/apps/server/src/omnirush-gateway-update-gate.test.ts@@ -0,0 +1,152 @@+import { describe, expect, test } from "bun:test";++import { OmniRushGatewayBroker, type GatewayUpdateSignal } from "./omnirush-gateway-broker.js";++const HEADER = "3.1.0; deadline=2026-10-05T12:00:00Z";+const REFUSAL = {+ error: { type: "update_required", code: "update_required", message: "Update OmniRush.ai to 3.1.0 to keep using models." },+};++type Fetcher = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;++type Call = { path: string; method: string; sessionId: string | null };++/** A gateway that refuses model requests with 426 once `blocked` is set, and always accepts uploads and archives. */+function gateway(options: { blocked: () => boolean; header?: string | null }) {+ const calls: Call[] = [];+ const fetcher = async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(String(input));+ const headers = new Headers(init?.headers);+ calls.push({ path: url.pathname, method: init?.method ?? "GET", sessionId: headers.get("x-omnirush-session-id") });+ const extra: Record<string, string> = options.header ? { "x-omnirush-update-required": options.header } : {};+ if (url.pathname.endsWith("/collect")) return Response.json({ ok: true }, { headers: extra });+ if (url.pathname.includes("/archives")) return Response.json({ key: "k" }, { headers: extra });+ if (url.pathname.endsWith("/responses")) {+ if (options.blocked()) return Response.json(REFUSAL, { status: 426, headers: extra });+ return new Response("data: {\"type\":\"response.completed\",\"response\":{}}\n\ndata: [DONE]\n\n", {+ headers: { "content-type": "text/event-stream", ...extra },+ });+ }+ return Response.json({ detail: "not_mocked" }, { status: 404 });+ };+ return { calls, fetcher };+}++function broker(fetcher: Fetcher, signals: GatewayUpdateSignal[], invalidated: { count: number }) {+ return new OmniRushGatewayBroker({+ credentials: {+ gatewayUrl: "https://gateway.example/omnirush/v1",+ accessToken: "access-token",+ refreshToken: "refresh-token",+ invalidate: async () => {+ invalidated.count += 1;+ },+ },+ engineToken: "local-engine-token",+ fetch: fetcher,+ onUpdateSignal: (signal) => signals.push(signal),+ });+}++function modelRequest(sessionId = "ses_gate") {+ return new Request("http://127.0.0.1/omnirush-gateway/v1/responses", {+ method: "POST",+ headers: {+ Authorization: "Bearer local-engine-token",+ "Content-Type": "application/json",+ "x-omnirush-session-id": sessionId,+ },+ body: JSON.stringify({ model: "gpt-6-astra", input: "hi", stream: true }),+ });+}++describe("mandatory update signals in the gateway broker", () => {+ test("passes the x-omnirush-update-required header on and leaves the stream intact", async () => {+ const signals: GatewayUpdateSignal[] = [];+ const { fetcher } = gateway({ blocked: () => false, header: HEADER });+ const response = await broker(fetcher, signals, { count: 0 }).handle(modelRequest(), "responses");+ expect(response.status).toBe(200);+ expect(response.headers.get("x-omnirush-update-required")).toBe(HEADER);+ expect(await response.text()).toContain("response.completed");+ expect(signals).toEqual([{ kind: "header", value: HEADER }]);+ });++ test("a 426 update_required is a rejection signal and a readable, non-retried refusal", async () => {+ const signals: GatewayUpdateSignal[] = [];+ const invalidated = { count: 0 };+ const { fetcher } = gateway({ blocked: () => true });+ const response = await broker(fetcher, signals, invalidated).handle(modelRequest(), "responses");+ expect(response.status).toBe(426);+ expect(response.headers.get("x-should-retry")).toBe("false");+ const body = await response.json() as { error: { code: string; message: string } };+ expect(body.error.code).toBe("update_required");+ // The server's own words name the version to install.+ expect(body.error.message).toBe(REFUSAL.error.message);+ expect(signals).toEqual([{ kind: "rejection", message: REFUSAL.error.message }]);+ // A refused version is not a revoked session: nothing is signed out or discarded.+ expect(invalidated.count).toBe(0);+ });++ test("a bare 426 update_required gets readable copy", async () => {+ const signals: GatewayUpdateSignal[] = [];+ const fetcher = async () => Response.json({ detail: "update_required" }, { status: 426 });+ const response = await broker(fetcher, signals, { count: 0 }).handle(modelRequest(), "responses");+ expect(response.status).toBe(426);+ const body = await response.json() as { error: { code: string; message: string } };+ expect(body.error.code).toBe("update_required");+ expect(body.error.message).toContain("no longer supported");+ expect(signals).toEqual([{ kind: "rejection", message: null }]);+ });++ test("an update_required body without 426 still counts; other refusals do not", async () => {+ const signals: GatewayUpdateSignal[] = [];+ let status = 403;+ let payload: unknown = REFUSAL;+ const fetcher = async () => Response.json(payload, { status });+ const subject = broker(fetcher, signals, { count: 0 });+ await subject.handle(modelRequest(), "responses");+ status = 429;+ payload = { detail: "daily_grant_exhausted" };+ await subject.handle(modelRequest(), "responses");+ expect(signals).toEqual([{ kind: "rejection", message: REFUSAL.error.message }]);+ });++ test("session uploads and project archives keep flowing after the version is blocked", async () => {+ const signals: GatewayUpdateSignal[] = [];+ let blocked = false;+ const { calls, fetcher } = gateway({ blocked: () => blocked, header: HEADER });+ const subject = broker(fetcher, signals, { count: 0 });++ expect((await subject.handle(modelRequest("ses_one"), "responses")).status).toBe(200);+ expect((await subject.uploadSession("ses_one", new Uint8Array([1, 2, 3]))).status).toBe(200);++ blocked = true;+ expect((await subject.handle(modelRequest("ses_one"), "responses")).status).toBe(426);+ // The uploader's queue is not stopped by the refusal: later envelopes of+ // the same session, and archive calls, still reach the gateway.+ expect((await subject.uploadSession("ses_one", new Uint8Array([4, 5, 6]))).status).toBe(200);+ expect((await subject.uploadSession("ses_two", new Uint8Array([7]))).status).toBe(200);+ expect((await subject.archiveRequest("archives/key", { method: "GET" })).status).toBe(200);+ expect(subject.enabled).toBe(true);++ const uploads = calls.filter((call) => call.path.endsWith("/collect"));+ expect(uploads.map((call) => call.sessionId)).toEqual(["ses_one", "ses_one", "ses_two"]);+ expect(signals.some((signal) => signal.kind === "rejection")).toBe(true);+ // The header on upload answers is heard too (uploads, not only model calls).+ expect(signals.filter((signal) => signal.kind === "header").length).toBeGreaterThanOrEqual(4);+ });++ test("a listener that throws never breaks a model request or an upload", async () => {+ const { fetcher } = gateway({ blocked: () => true, header: HEADER });+ const subject = new OmniRushGatewayBroker({+ credentials: { gatewayUrl: "https://gateway.example/omnirush/v1", accessToken: "a", refreshToken: "r" },+ engineToken: "local-engine-token",+ fetch: fetcher,+ onUpdateSignal: () => {+ throw new Error("listener failed");+ },+ });+ expect((await subject.handle(modelRequest(), "responses")).status).toBe(426);+ expect((await subject.uploadSession("ses_gate", new Uint8Array([1]))).status).toBe(200);+ });+});diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 1a0c0584..106bece3 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -988,6 +988,9 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {// the refused model for a while, and the session uploader records the model the// sub-agent's messages really ran on.subagentModelRefused: (model) => subagentModelRefusals(config).isRefused(model),+ // The desktop's update gate (banner, blocked view); session uploads and+ // project archives go on whatever it says.+ ...(config.omnirushGatewayCredentials?.onUpdateSignal ? { onUpdateSignal: config.omnirushGatewayCredentials.onUpdateSignal } : {}),onSubagentFallback: (event) => {if (event.reason !== "refused_recently") subagentModelRefusals(config).mark(event.requested, event.reason);recordSubagentModelFallback(config, event.rootSessionId, {diff --git a/apps/server/src/types.ts b/apps/server/src/types.tsindex 205f095a..647f7445 100644--- a/apps/server/src/types.ts+++ b/apps/server/src/types.ts@@ -121,6 +121,12 @@ export type OmniRushGatewayCredentials = OmniRushGatewayCredentialBundle & {latest?: () => Promise<OmniRushGatewayCredentialBundle | null>;/** Connected account's profile (name and email for the git commit identity default); null when signed out or offline. */profile?: () => Promise<{ email: string | null; displayName: string | null } | null>;+ /**+ * Hears the gateway's mandatory-update signals: the+ * `x-omnirush-update-required` header and 426 `update_required` refusals+ * of model requests (the desktop shows its update banner or blocked view).+ */+ onUpdateSignal?: (signal: { kind: "header"; value: string } | { kind: "rejection"; message: string | null }) => void;};export interface ServerConfig {diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 7bbeeedf..e29d7696 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -170,6 +170,37 @@ export type OmniRushAccountUsage = {pot?: number;};+/**+ * The account server's word on this app's version (/device/me+ * `client_update`, product "gui"). Required: update before `deadline`;+ * blocked: model requests are refused until the app is updated.+ */+export type OmniRushClientUpdate = {+ required: boolean;+ blocked: boolean;+ current: string | null;+ minimum: string | null;+ /** UTC ISO 8601. */+ deadline: string | null;+ message: string | null;+ downloadUrl: string | null;+};++/**+ * What the app shows for a mandatory update, derived in the Electron main+ * process from `client_update`, the gateway's `x-omnirush-update-required`+ * header and HTTP 426 `update_required` refusals.+ */+export type OmniRushUpdateGateState = {+ status: "none" | "required" | "blocked";+ current: string;+ minimum: string | null;+ deadline: string | null;+ message: string | null;+ downloadUrl: string;+ source: "profile" | "header" | "rejection" | null;+};+export type OmniRushAccountStatus = {connected: boolean;gatewayConfigured: boolean;@@ -193,6 +224,8 @@ export type OmniRushAccountStatus = {* session the server ended (reauthorizationRequired alone).*/keyringUnavailable?: boolean;+ /** /device/me `client_update` for this app; absent from an older desktop bridge. */+ clientUpdate?: OmniRushClientUpdate | null;};export type EngineDoctorResult = {