Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(update): in-app "Update Now" button for managed desktop installs

Ruben Lütke574a661df07e
diff --git a/.gitignore b/.gitignore
index f503ce3ba9..6fa353cc0a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -46,6 +46,12 @@ node_modules/
dist/
build/
+# Installer-managed-install marker: written by install/installer.py at install
+# time to opt a checkout into in-app self-update. Must NEVER be committed — a
+# manual clone or a dev tree must not look like a managed install (else the
+# in-app updater could git-reset --hard it). See jarvis/ui/web/update_routes.py.
+.jarvis-managed-install
+
# Jarvis Runtime-Daten (nie committen)
data/*
data/**/
diff --git a/install/installer.py b/install/installer.py
index 63d2c1576c..4427ccd205 100644
--- a/install/installer.py
+++ b/install/installer.py
@@ -30,6 +30,7 @@ Exit codes:
from __future__ import annotations
import argparse
+import json
import os
import platform
import shutil
@@ -160,6 +161,29 @@ def step_preflight() -> None:
sys.exit(1)
+def write_managed_marker() -> None:
+ """Mark this checkout as an installer-managed copy.
+
+ The in-app "Update Now" button (jarvis/ui/web/update_routes.py) only appears,
+ and only ever runs ``git reset --hard``, when this marker is present AND the
+ checkout's ``origin`` is the official public repo. A maintainer's dev tree or
+ a manual clone never gets this marker, so neither can be self-reset — this is
+ the load-bearing safety guard for the whole updater. Best-effort: a marker
+ failure must never fail the install (it only disables in-app updates).
+ """
+ marker = repo_root() / ".jarvis-managed-install"
+ payload = {
+ "managed": True,
+ "install_path": str(repo_root()),
+ "created_by": "install/installer.py",
+ }
+ try:
+ marker.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ ok("registered as a managed install (in-app updates enabled)")
+ except OSError as exc:
+ note(f"could not write update marker ({exc}); in-app updates stay disabled")
+
+
def step_pip_install(*, with_desktop: bool, with_voice_local: bool, dry_run: bool) -> None:
step("Installing Personal Jarvis")
pip = [str(venv_python()), "-m", "pip"]
@@ -328,6 +352,8 @@ def main(argv: list[str] | None = None) -> int:
with_desktop = True
step_preflight()
+ if not args.dry_run:
+ write_managed_marker()
if not os.environ.get("JARVIS_INSTALL_NO_PIP"):
step_pip_install(
with_desktop=with_desktop,
diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
index 05af57b012..df30ee2ed4 100644
--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
@@ -1,30 +1,31 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import { RotateCw } from "lucide-react";
+import { Download, RotateCw } from "lucide-react";
import { useEventStore } from "@/store/events";
+import { useUpdate } from "@/hooks/useUpdate";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
/**
- * Global top bar rendered above every view (see App.tsx). Its only job today is
- * to carry a single app-chrome action: a "Restart Jarvis" button that is
- * reachable from *every* screen — not just the Settings → Bar & Overlay panel
- * where the restart control historically lived.
+ * Global top bar rendered above every view (see App.tsx). It carries the app-
+ * chrome actions that must be reachable from *every* screen: a "Restart Jarvis"
+ * button, and — only when a newer version is published — an "Update" button that
+ * pulls the new code and restarts, so an end user never touches a terminal.
*
* Why a global bar and not the per-view ``ViewHeader``: a couple of views
* (DocsView's 3-column layout, SubAgentsView's departure board) don't render a
* ViewHeader at all, and ~13 views already fill the header's ``right`` slot with
- * their own actions. Putting the button in the shell, above MainView, is the
+ * their own actions. Putting the buttons in the shell, above MainView, is the
* only placement that is on every screen and collides with nothing.
*
- * The backend already ships the whole self-restart machinery: this POSTs to the
- * existing ``/api/settings/restart-app`` endpoint, which spawns a detached,
- * cross-platform relauncher (see jarvis/ui/relauncher.py). On a headless host
- * the endpoint returns 503 and we recover the button with an honest toast.
+ * The backend already ships the whole self-restart machinery: both buttons POST
+ * to the existing ``/api/settings/restart-app`` endpoint, which spawns a
+ * detached, cross-platform relauncher (see jarvis/ui/relauncher.py). On a
+ * headless host that endpoint returns 503 and we recover with an honest toast.
*
- * A restart tears down the whole app mid-task, so the button is a two-click
- * confirm (arm → confirm) rather than a fire-on-first-click control. We avoid a
- * native ``window.confirm`` on purpose — it blocks the pywebview event loop.
+ * A restart tears down the whole app mid-task, so both buttons honor the mission
+ * guard (409 → arm a force override) rather than killing live missions silently.
+ * We avoid a native ``window.confirm`` on purpose — it blocks the pywebview loop.
*/
const CONFIRM_TIMEOUT_MS = 4000;
@@ -122,7 +123,8 @@ export function TopBar() {
: t("topbar.restart");
return (
- <div className="flex h-10 shrink-0 items-center justify-end border-b border-border bg-background/70 px-4 backdrop-blur-sm">
+ <div className="flex h-10 shrink-0 items-center justify-end gap-2 border-b border-border bg-background/70 px-4 backdrop-blur-sm">
+ <UpdateButton />
<button
type="button"
onClick={onClick}
@@ -144,3 +146,137 @@ export function TopBar() {
</div>
);
}
+
+/**
+ * Shown ONLY when the backend reports a managed install with a newer published
+ * release (``status.update_available``). One click pulls the new code
+ * (`POST /api/update/apply`) and then restarts to load it, reusing the same
+ * mission-guard (409 → force) flow as the restart button. Hovering reveals the
+ * release notes. On a dev tree / manual clone the status is ``managed: false``,
+ * so this renders nothing and can never trigger a self-update.
+ */
+function UpdateButton() {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const { status } = useUpdate();
+ const [busy, setBusy] = useState(false);
+ const [forceArmed, setForceArmed] = useState(false);
+ const [showNotes, setShowNotes] = useState(false);
+ const resetTimer = useRef<number | null>(null);
+
+ const clearResetTimer = useCallback(() => {
+ if (resetTimer.current !== null) {
+ clearTimeout(resetTimer.current);
+ resetTimer.current = null;
+ }
+ }, []);
+ useEffect(() => clearResetTimer, [clearResetTimer]);
+
+ if (!status?.managed || !status.update_available) return null;
+
+ async function run(force: boolean) {
+ clearResetTimer();
+ setBusy(true);
+ setShowNotes(false);
+ try {
+ // 1. Pull the new code. The server re-verifies the managed-install guard,
+ // so a spoofed client can't force a reset on an unmanaged checkout.
+ const applyRes = await fetch("/api/update/apply", { method: "POST" });
+ const applyBody = await applyRes.json().catch(() => ({}));
+ if (!applyRes.ok) {
+ throw new Error(
+ (applyBody as { detail?: string }).detail ?? `HTTP ${applyRes.status}`,
+ );
+ }
+ if ((applyBody as { deps_warning?: string | null }).deps_warning) {
+ pushToast("warning", t("topbar.update_deps_warning"));
+ }
+ // 2. Restart to load it — reuse the existing route + its mission guard.
+ const url = force
+ ? "/api/settings/restart-app?force=true"
+ : "/api/settings/restart-app";
+ const restartRes = await fetch(url, { method: "POST" });
+ if (restartRes.status === 409) {
+ let count = 0;
+ try {
+ const body = await restartRes.json();
+ count = body?.detail?.missions?.length ?? 0;
+ } catch {
+ /* malformed body — still arm the override */
+ }
+ setBusy(false);
+ setForceArmed(true);
+ clearResetTimer();
+ resetTimer.current = window.setTimeout(() => {
+ setForceArmed(false);
+ resetTimer.current = null;
+ }, CONFIRM_TIMEOUT_MS);
+ pushToast("warning", `${count} ${t("topbar.restart_missions_running")}`);
+ return;
+ }
+ if (!restartRes.ok) throw new Error(`restart-failed:${restartRes.status}`);
+ // Success — the code is pulled and the window goes away shortly; keep the
+ // busy state so the button never flips back before the app dies.
+ pushToast("info", t("topbar.updating"));
+ } catch {
+ // apply failed (403 on an unmanaged host, 502/500 on a git error) or the
+ // restart 503'd on a headless host: recover the control with an honest toast.
+ setBusy(false);
+ setForceArmed(false);
+ pushToast("error", t("topbar.update_failed"));
+ }
+ }
+
+ function onClick() {
+ if (busy) return;
+ void run(forceArmed);
+ }
+
+ const label = busy
+ ? t("topbar.updating")
+ : forceArmed
+ ? t("topbar.restart_force")
+ : t("topbar.update_available");
+
+ return (
+ <div
+ className="relative"
+ onMouseEnter={() => !busy && status.notes && setShowNotes(true)}
+ onMouseLeave={() => setShowNotes(false)}
+ >
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={busy}
+ title={t("topbar.update_hint")}
+ className={cn(
+ "inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-default disabled:opacity-70",
+ forceArmed
+ ? "border-amber-500/60 bg-amber-500/10 text-amber-500 hover:bg-amber-500/20"
+ : "border-primary/50 bg-primary/10 text-primary hover:bg-primary/20",
+ )}
+ >
+ <Download
+ aria-hidden
+ className={cn("h-3.5 w-3.5", busy && "animate-pulse")}
+ />
+ {label}
+ {!busy && !forceArmed && status.latest && (
+ <span className="rounded bg-primary/20 px-1 text-[10px] tabular-nums">
+ v{status.latest}
+ </span>
+ )}
+ </button>
+ {showNotes && status.notes && (
+ <div className="absolute right-0 top-full z-50 mt-1 w-80 rounded-md border border-border bg-background p-3 text-left shadow-lg">
+ <div className="mb-1 text-xs font-semibold text-foreground">
+ {t("topbar.update_available")} · v{status.latest}
+ </div>
+ <div className="max-h-64 overflow-y-auto whitespace-pre-wrap text-[11px] leading-relaxed text-muted-foreground">
+ {status.notes.slice(0, 800)}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useUpdate.ts b/jarvis/ui/web/frontend/src/hooks/useUpdate.ts
new file mode 100644
index 0000000000..97d9c34c42
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useUpdate.ts
@@ -0,0 +1,62 @@
+import { useCallback, useEffect, useState } from "react";
+
+/**
+ * Result of GET /api/update/status. ``managed`` is false on any checkout that is
+ * not an installer-managed install (a dev tree, a manual clone) — the update
+ * button never renders there. ``update_available`` is only ever true on a
+ * managed install with a newer published GitHub Release.
+ */
+export interface UpdateStatus {
+ managed: boolean;
+ current: string;
+ latest: string | null;
+ update_available: boolean;
+ notes: string | null;
+ published_at: string | null;
+ release_url?: string | null;
+ check_failed?: boolean;
+}
+
+// Slow poll: a new release is a rare event, so 6h keeps the button fresh
+// without hammering GitHub. A window focus also triggers a check.
+const POLL_INTERVAL_MS = 6 * 60 * 60 * 1000;
+
+async function fetchStatus(force = false): Promise<UpdateStatus | null> {
+ try {
+ const res = await fetch(`/api/update/status${force ? "?force=true" : ""}`);
+ if (!res.ok) return null;
+ return (await res.json()) as UpdateStatus;
+ } catch {
+ // A failed status check must never disrupt the app — the button just
+ // stays hidden until the next successful poll.
+ return null;
+ }
+}
+
+/**
+ * Polls /api/update/status so the top bar can surface an "Update available"
+ * button on its own, like a native auto-updater. Applying + restarting is done
+ * by the caller (TopBar), which owns the toast + mission-guard (409) UX.
+ */
+export function useUpdate() {
+ const [status, setStatus] = useState<UpdateStatus | null>(null);
+
+ const refresh = useCallback(async (force = false) => {
+ const data = await fetchStatus(force);
+ if (data) setStatus(data);
+ return data;
+ }, []);
+
+ useEffect(() => {
+ void refresh();
+ const id = window.setInterval(() => void refresh(), POLL_INTERVAL_MS);
+ const onFocus = () => void refresh();
+ window.addEventListener("focus", onFocus);
+ return () => {
+ window.clearInterval(id);
+ window.removeEventListener("focus", onFocus);
+ };
+ }, [refresh]);
+
+ return { status, refresh };
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index cac5f8ab8c..e454ea2021 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -20,7 +20,12 @@
"restarting": "{name} startet neu…",
"restart_failed": "Neustart fehlgeschlagen",
"restart_force": "Trotzdem neu starten?",
- "restart_missions_running": "Mission(en) laufen noch — nochmal klicken zum Erzwingen"
+ "restart_missions_running": "Mission(en) laufen noch — nochmal klicken zum Erzwingen",
+ "update_available": "Update verfügbar",
+ "updating": "{name} wird aktualisiert…",
+ "update_failed": "Update fehlgeschlagen",
+ "update_hint": "Neue Version herunterladen und installieren",
+ "update_deps_warning": "Aktualisiert — einige Komponenten brauchen evtl. eine manuelle Neuinstallation"
},
"nav": {
"chats": "Chats",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index f8ad5477cd..b8445189b9 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -20,7 +20,12 @@
"restarting": "Restarting {name}…",
"restart_failed": "Restart failed",
"restart_force": "Restart anyway?",
- "restart_missions_running": "mission(s) still running — click again to restart anyway"
+ "restart_missions_running": "mission(s) still running — click again to restart anyway",
+ "update_available": "Update available",
+ "updating": "Updating {name}…",
+ "update_failed": "Update failed",
+ "update_hint": "Download and install the new version",
+ "update_deps_warning": "Updated — some components may need a manual reinstall"
},
"nav": {
"chats": "Chats",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 27537b34b2..d236002bc9 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -20,7 +20,12 @@
"restarting": "Reiniciando {name}…",
"restart_failed": "Error al reiniciar",
"restart_force": "¿Reiniciar de todos modos?",
- "restart_missions_running": "misión(es) en curso — haz clic de nuevo para reiniciar igualmente"
+ "restart_missions_running": "misión(es) en curso — haz clic de nuevo para reiniciar igualmente",
+ "update_available": "Actualización disponible",
+ "updating": "Actualizando {name}…",
+ "update_failed": "Error al actualizar",
+ "update_hint": "Descargar e instalar la nueva versión",
+ "update_deps_warning": "Actualizado — algunos componentes pueden requerir reinstalación manual"
},
"nav": {
"chats": "Chats",
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 2e63ea37df..db1a960a5c 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -266,6 +266,7 @@ class WebServer:
from .tasks_routes import router as tasks_router
from .telephony_routes import router as telephony_router
from .tools_routes import router as tools_router
+ from .update_routes import router as update_router
from .wiki_routes import router as wiki_router
from .wiki_ws import router as wiki_ws_router
from .workflows_routes import router as workflows_router
@@ -286,6 +287,9 @@ class WebServer:
app.include_router(control_router)
app.include_router(profile_router)
app.include_router(settings_router)
+ # In-app updater (GET status / POST apply). Managed-install only — see
+ # jarvis/ui/web/update_routes.py; refuses to self-reset a dev checkout.
+ app.include_router(update_router)
# Frontier auto-switch modal API (GET pending / POST ack) + Self-Mod
# read/restore API. Both were the last route modules left unmounted; the
# 404 on /api/frontier/pending silently broke the desktop auto-switch
diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.py
new file mode 100644
index 0000000000..b3bddcda1f
--- /dev/null
+++ b/jarvis/ui/web/update_routes.py
@@ -0,0 +1,452 @@
+"""In-app updater for a MANAGED install of Personal Jarvis.
+
+An end user installs Personal Jarvis with the one-line installer, which clones
+the public flagship repo into ``~/.personal-jarvis`` and runs the app from that
+checkout. This module lets the running desktop app offer a one-click "Update
+Now" button so the user never has to re-run the installer from a terminal:
+
+* ``GET /api/update/status`` — compares the running version against the latest
+ published GitHub Release and reports whether an update is available (plus its
+ release notes). It is **fail-open**: any network or parse error reports "no
+ update" rather than erroring, so a flaky connection never breaks the UI.
+* ``POST /api/update/apply`` — pulls the new code (the same ``git fetch`` +
+ ``git reset --hard origin/main`` the installer uses), refreshes dependencies
+ only if the lockfile changed, and reports ``restart_required``. It does NOT
+ restart — the caller then hits the existing ``POST /api/settings/restart-app``
+ which already owns the mission-guard + cross-platform relauncher.
+
+Safety-critical guard (the single most important thing here):
+``git reset --hard`` destroys uncommitted local changes. That is fine for an
+end user's managed checkout but catastrophic in a maintainer's dev tree or any
+manual clone. So the updater is active **only** on a *managed install*, proven
+by BOTH:
+ 1. a marker file (``.jarvis-managed-install``) that the installer writes into
+ the checkout root, and
+ 2. the checkout's ``origin`` remote resolving to the official public repo.
+If either check fails, ``status`` reports ``managed: false`` (the button never
+renders) and ``apply`` refuses with HTTP 403. This makes the dev tree and any
+fork structurally immune to the self-update.
+
+Cross-platform: git runs via ``asyncio`` subprocess with
+``NO_WINDOW_CREATIONFLAGS`` (AP-1, no console flash under ``pythonw.exe``); the
+dependency refresh calls the checkout's venv python; nothing here is Windows-
+specific. On a headless VPS the pull works and the caller's restart step
+degrades honestly (``restart-app`` returns 503).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import logging
+import re
+import sys
+import time
+from pathlib import Path
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/update", tags=["update"])
+
+# The ONE official public repo this updater will ever pull from. The managed
+# guard verifies the installed checkout's ``origin`` resolves here before any
+# ``git reset --hard`` runs, so a dev checkout or a fork can never be self-reset.
+_OFFICIAL_REPO_SLUG = "PersonalJarvis/PersonalJarvis"
+_RELEASES_LATEST_API = (
+ "https://api.github.com/repos/PersonalJarvis/PersonalJarvis/releases/latest"
+)
+# Written by install/installer.py into the checkout root. Its presence is one
+# half of "this copy is safe to self-update".
+_MARKER_NAME = ".jarvis-managed-install"
+
+_NETWORK_TIMEOUT_S = 6.0
+_STATUS_CACHE_TTL_S = 1800.0 # 30 min — don't hit GitHub on every poll.
+_STATUS_RETRY_S = 120.0 # after a failed network check, retry sooner than the TTL.
+
+# In-process cache of the last status result. The managed state is stable for a
+# process lifetime; the network result is what the TTL protects.
+_status_cache: dict[str, Any] | None = None
+_status_cache_until: float = 0.0
+
+
+# --------------------------------------------------------------------------- #
+# Version helpers
+# --------------------------------------------------------------------------- #
+def _running_version() -> str:
+ """The version of the CURRENTLY running process (in-memory module)."""
+ try:
+ import jarvis
+
+ return str(jarvis.__version__)
+ except (ImportError, AttributeError):
+ return "unknown"
+
+
+def _version_on_disk(root: Path) -> str | None:
+ """Parse the version from the freshly-pulled files on disk.
+
+ After ``apply`` the checkout is new but the imported ``jarvis`` module in
+ memory is still the OLD version, so the post-update version must be read
+ from disk, not from ``jarvis.__version__``.
+ """
+ for rel, pattern in (
+ (Path("jarvis") / "__init__.py", r'__version__\s*=\s*"([^"]+)"'),
+ (Path("pyproject.toml"), r'^version\s*=\s*"([^"]+)"'),
+ ):
+ try:
+ text = (root / rel).read_text(encoding="utf-8")
+ except OSError:
+ continue
+ m = re.search(pattern, text, re.MULTILINE)
+ if m:
+ return m.group(1)
+ return None
+
+
+def _naive_version_gt(a: str, b: str) -> bool:
+ """Fallback dotted-int compare when ``packaging`` is unavailable."""
+
+ def parts(v: str) -> list[int]:
+ out: list[int] = []
+ for chunk in v.split("."):
+ m = re.match(r"\d+", chunk)
+ out.append(int(m.group()) if m else 0)
+ return out
+
+ try:
+ return parts(a) > parts(b)
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _is_newer(latest: str, current: str) -> bool:
+ """True iff ``latest`` is a strictly newer version than ``current``.
+
+ Fail-closed on an unknown running version: if we can't tell what we're on,
+ we do NOT offer an update (never blind-update).
+ """
+ if not latest or current in ("", "unknown"):
+ return False
+ try:
+ from packaging.version import Version
+
+ return Version(latest) > Version(current)
+ except ImportError:
+ return _naive_version_gt(latest, current)
+ except Exception: # noqa: BLE001 — InvalidVersion → not newer
+ return False
+
+
+# --------------------------------------------------------------------------- #
+# Subprocess helpers (git + pip), NO_WINDOW_CREATIONFLAGS + clean teardown
+# --------------------------------------------------------------------------- #
+async def _terminate(proc: asyncio.subprocess.Process) -> None:
+ """Guarantee a dead subprocess: terminate -> wait 50 ms -> kill -> wait."""
+ if proc.returncode is not None:
+ return
+ try:
+ proc.terminate()
+ try:
+ await asyncio.wait_for(proc.wait(), timeout=0.05)
+ return
+ except (TimeoutError, asyncio.CancelledError):
+ pass
+ proc.kill()
+ await proc.wait()
+ except (ProcessLookupError, OSError):
+ pass
+
+
+async def _run(
+ cmd: list[str], *, cwd: Path, timeout_s: float
+) -> tuple[int, str, str]:
+ """Run ``cmd`` in ``cwd``. Returns ``(returncode, stdout, stderr)``.
+
+ ``returncode == -1`` signals the process could not run at all (missing
+ binary) or timed out — ``stderr`` then carries a human reason. Cleans up the
+ child on timeout/cancel so no zombie is left behind.
+ """
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ *cmd,
+ cwd=str(cwd),
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (FileNotFoundError, OSError, NotImplementedError) as exc:
+ return -1, "", f"could not run {cmd[0]}: {exc}"
+
+ try:
+ try:
+ raw_out, raw_err = await asyncio.wait_for(
+ proc.communicate(), timeout=timeout_s
+ )
+ except TimeoutError:
+ await _terminate(proc)
+ return -1, "", f"{cmd[0]} timed out after {timeout_s:.0f}s"
+ except asyncio.CancelledError:
+ await _terminate(proc)
+ raise
+ finally:
+ if proc.returncode is None:
+ await _terminate(proc)
+
+ out = raw_out.decode(errors="replace").strip()
+ err = raw_err.decode(errors="replace").strip()
+ return proc.returncode if proc.returncode is not None else -1, out, err
+
+
+async def _git(args: list[str], *, cwd: Path, timeout_s: float = 60.0) -> tuple[int, str, str]:
+ return await _run(["git", *args], cwd=cwd, timeout_s=timeout_s)
+
+
+async def _git_output(args: list[str], *, cwd: Path, timeout_s: float = 15.0) -> str | None:
+ rc, out, _err = await _git(args, cwd=cwd, timeout_s=timeout_s)
+ return out if rc == 0 else None
+
+
+# --------------------------------------------------------------------------- #
+# Managed-install guard
+# --------------------------------------------------------------------------- #
+def _repo_root() -> Path | None:
+ """The checkout root, derived unambiguously from the running package."""
+ try:
+ import jarvis
+
+ # .../repo/jarvis/__init__.py -> .../repo
+ return Path(jarvis.__file__).resolve().parent.parent
+ except Exception: # noqa: BLE001 — never fatal
+ return None
+
+
+def _normalize_remote(url: str) -> str:
+ """Reduce a git remote URL to a comparable ``.../owner/name`` tail.
+
+ Handles https (``https://github.com/Owner/Name.git``), ssh
+ (``[email protected]:Owner/Name.git``), and local file paths on either slash
+ style — so the comparison is robust across platforms and remote forms.
+ """
+ tail = url.strip()
+ if tail.endswith(".git"):
+ tail = tail[:-4]
+ tail = tail.replace("\\", "/").replace(":", "/").rstrip("/")
+ return tail
+
+
+def _remote_is_official(url: str) -> bool:
+ """True only if ``url`` resolves to exactly the official ``owner/name``.
+
+ Must MATCH the last two path segments, not merely contain the slug — so a
+ look-alike fork (``.../PersonalJarvis/PersonalJarvisEvil``) is rejected.
+ """
+ norm = _normalize_remote(url).lower()
+ slug = _OFFICIAL_REPO_SLUG.lower()
+ return norm == slug or norm.endswith("/" + slug)
+
+
+async def _resolve_managed_repo() -> Path | None:
+ """Return the checkout root IFF this is a managed, self-updatable install.
+
+ Requires BOTH the installer marker AND an ``origin`` that resolves to the
+ official public repo. Any doubt returns ``None`` (fail-closed).
+ """
+ root = _repo_root()
+ if root is None or not (root / _MARKER_NAME).exists():
+ return None
+ if not (root / ".git").exists():
+ return None
+ origin = await _git_output(["remote", "get-url", "origin"], cwd=root)
+ if origin is None or not _remote_is_official(origin):
+ return None
+ return root
+
+
+# --------------------------------------------------------------------------- #
+# GitHub release check (fail-open)
+# --------------------------------------------------------------------------- #
+async def _fetch_latest_release() -> dict[str, Any] | None:
+ """GET the latest GitHub Release. Fail-open: any error returns ``None``."""
+ try:
+ import httpx
+
+ async with httpx.AsyncClient(timeout=_NETWORK_TIMEOUT_S) as client:
+ resp = await client.get(
+ _RELEASES_LATEST_API,
+ headers={
+ "Accept": "application/vnd.github+json",
+ "User-Agent": "PersonalJarvis-Updater",
+ },
+ )
+ if resp.status_code != 200:
+ log.debug("update check: releases/latest HTTP %s", resp.status_code)
+ return None
+ data = resp.json()
+ tag = str(data.get("tag_name") or "").strip().lstrip("vV")
+ if not tag:
+ return None
+ return {
+ "version": tag,
+ "notes": (data.get("body") or "").strip(),
+ "published_at": data.get("published_at"),
+ "release_url": data.get("html_url"),
+ }
+ except Exception as exc: # noqa: BLE001 — fail-open on any network/parse error
+ log.debug("update check: latest-release fetch failed: %s", exc)
+ return None
+
+
+# --------------------------------------------------------------------------- #
+# Dependency refresh (best-effort)
+# --------------------------------------------------------------------------- #
+def _venv_python(root: Path) -> Path:
+ """The python inside the checkout's venv, falling back to the running one."""
+ if sys.platform == "win32":
+ cand = root / ".venv" / "Scripts" / "python.exe"
+ else:
+ cand = root / ".venv" / "bin" / "python"
+ return cand if cand.exists() else Path(sys.executable)
+
+
+def _hash_file(path: Path) -> str | None:
+ try:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+ except OSError:
+ return None
+
+
+async def _refresh_dependencies(root: Path) -> tuple[bool, str]:
+ """Best-effort ``pip install -r requirements.txt`` on the venv python.
+
+ Only called when the lockfile actually changed. Never raises; a failure is
+ reported so the UI can warn honestly (the pull still succeeded).
+ """
+ req = root / "requirements.txt"
+ if not req.exists():
+ return True, ""
+ py = _venv_python(root)
+ rc, out, err = await _run(
+ [str(py), "-m", "pip", "install", "--disable-pip-version-check", "-r", str(req)],
+ cwd=root,
+ timeout_s=600.0,
+ )
+ if rc != 0:
+ return False, (err or out or "pip failed")[-400:]
+ return True, ""
+
+
+# --------------------------------------------------------------------------- #
+# Routes
+# --------------------------------------------------------------------------- #
+async def update_status(force: bool = False) -> dict[str, object]:
+ """Report whether a newer published version is available.
+
+ ``force=true`` bypasses the in-process cache (a manual "check now").
+ """
+ global _status_cache, _status_cache_until
+ now = time.monotonic()
+ if not force and _status_cache is not None and now < _status_cache_until:
+ return _status_cache
+
+ current = _running_version()
+ root = await _resolve_managed_repo()
+
+ if root is None:
+ result: dict[str, object] = {
+ "managed": False,
+ "current": current,
+ "latest": None,
+ "update_available": False,
+ "notes": None,
+ "published_at": None,
+ }
+ _status_cache, _status_cache_until = result, now + _STATUS_CACHE_TTL_S
+ return result
+
+ latest = await _fetch_latest_release()
+ if latest is None:
+ # Fail-open: we are managed but couldn't reach GitHub. Offer no update,
+ # and retry sooner than the full TTL.
+ result = {
+ "managed": True,
+ "current": current,
+ "latest": None,
+ "update_available": False,
+ "notes": None,
+ "published_at": None,
+ "check_failed": True,
+ }
+ _status_cache, _status_cache_until = result, now + _STATUS_RETRY_S
+ return result
+
+ available = _is_newer(str(latest["version"]), current)
+ result = {
+ "managed": True,
+ "current": current,
+ "latest": latest["version"],
+ "update_available": available,
+ "notes": latest["notes"] if available else None,
+ "published_at": latest["published_at"],
+ "release_url": latest.get("release_url"),
+ }
+ _status_cache, _status_cache_until = result, now + _STATUS_CACHE_TTL_S
+ return result
+
+
+async def update_apply() -> dict[str, object]:
+ """Pull the latest code for a managed install. Does NOT restart.
+
+ Returns ``{ok, restart_required, version, deps_refreshed, deps_warning}``.
+ The caller applies the update by then calling
+ ``POST /api/settings/restart-app``.
+ """
+ root = await _resolve_managed_repo()
+ if root is None:
+ raise HTTPException(
+ status_code=403,
+ detail="not a managed install — in-app update is disabled here",
+ )
+
+ # Snapshot the lockfile so we can tell whether deps need a refresh.
+ req_before = _hash_file(root / "requirements.txt")
+
+ rc, _out, err = await _git(
+ ["fetch", "--depth", "1", "origin", "main"], cwd=root, timeout_s=120.0
+ )
+ if rc != 0:
+ raise HTTPException(
+ status_code=502, detail=f"git fetch failed: {err[:300] or 'unknown error'}"
+ )
+ rc, _out, err = await _git(["reset", "--hard", "origin/main"], cwd=root, timeout_s=60.0)
+ if rc != 0:
+ raise HTTPException(
+ status_code=500, detail=f"git reset failed: {err[:300] or 'unknown error'}"
+ )
+
+ # The new code refreshes the UI (prebuilt dist/ ships with the pull) and the
+ # Python source (editable install loads it on restart). Refresh deps only if
+ # the lockfile actually moved.
+ deps_refreshed = False
+ deps_warning: str | None = None
+ req_after = _hash_file(root / "requirements.txt")
+ if req_before != req_after:
+ deps_refreshed = True
+ ok, msg = await _refresh_dependencies(root)
+ if not ok:
+ deps_warning = msg
+
+ new_version = _version_on_disk(root) or _running_version()
+ return {
+ "ok": True,
+ "restart_required": True,
+ "version": new_version,
+ "deps_refreshed": deps_refreshed,
+ "deps_warning": deps_warning,
+ }
diff --git a/tests/integration/test_update_apply_real_git.py b/tests/integration/test_update_apply_real_git.py
new file mode 100644
index 0000000000..36cb4ec15e
--- /dev/null
+++ b/tests/integration/test_update_apply_real_git.py
@@ -0,0 +1,88 @@
+"""Integration test: the updater's REAL git operations against a local repo.
+
+No network, no mocks — a real bare "upstream" and a real "installed" clone prove
+that (a) the managed guard passes only with the marker + an official-slug origin
+using real ``git remote get-url``, and (b) the fetch/reset sequence actually
+moves the installed checkout to the new upstream tip. This exercises the one
+destructive operation (``git reset --hard``) end to end.
+"""
+from __future__ import annotations
+
+import asyncio
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+import jarvis.ui.web.update_routes as u
+
+pytestmark = pytest.mark.skipif(
+ shutil.which("git") is None, reason="git binary required"
+)
+
+
+def _git(args: list[str], cwd: Path) -> None:
+ subprocess.run(
+ ["git", *args], cwd=str(cwd), check=True, capture_output=True, text=True
+ )
+
+
+def _make_upstream_and_install(tmp_path: Path) -> tuple[Path, Path, Path]:
+ # The upstream path deliberately contains the official slug so the real
+ # origin-URL guard passes against a purely local remote.
+ upstream = tmp_path / "PersonalJarvis" / "PersonalJarvis.git"
+ upstream.parent.mkdir(parents=True)
+ _git(["init", "--bare", "-b", "main", str(upstream)], tmp_path)
+
+ seed = tmp_path / "seed"
+ _git(["clone", str(upstream), str(seed)], tmp_path)
+ _git(["config", "user.email", "[email protected]"], seed)
+ _git(["config", "user.name", "Tester"], seed)
+ (seed / "jarvis").mkdir()
+ init_py = seed / "jarvis" / "__init__.py"
+ init_py.write_text('__version__ = "9.9.9"\n', encoding="utf-8")
+ (seed / "requirements.txt").write_text("pkg==1\n", encoding="utf-8")
+ _git(["add", "-A"], seed)
+ _git(["commit", "-m", "A"], seed)
+ _git(["push", "origin", "main"], seed)
+
+ install = tmp_path / "install"
+ _git(["clone", str(upstream), str(install)], tmp_path)
+ (install / ".jarvis-managed-install").write_text("{}\n", encoding="utf-8")
+ return upstream, seed, install
+
+
+def test_managed_guard_passes_with_real_git(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _upstream, _seed, install = _make_upstream_and_install(tmp_path)
+ monkeypatch.setattr(u, "_repo_root", lambda: install)
+ resolved = asyncio.run(u._resolve_managed_repo())
+ assert resolved == install
+
+ # Remove the marker → guard must fail-closed even though origin is official.
+ (install / ".jarvis-managed-install").unlink()
+ assert asyncio.run(u._resolve_managed_repo()) is None
+
+
+def test_real_apply_moves_head_to_new_tip(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ _upstream, seed, install = _make_upstream_and_install(tmp_path)
+
+ # Publish a new upstream commit B (bumped version).
+ (seed / "jarvis" / "__init__.py").write_text('__version__ = "9.9.10"\n', encoding="utf-8")
+ _git(["add", "-A"], seed)
+ _git(["commit", "-m", "B"], seed)
+ _git(["push", "origin", "main"], seed)
+
+ # Before: the installed checkout is still on A.
+ assert '9.9.9' in (install / "jarvis" / "__init__.py").read_text(encoding="utf-8")
+
+ monkeypatch.setattr(u, "_repo_root", lambda: install)
+ result = asyncio.run(u.update_apply())
+
+ assert result["ok"] is True
+ assert result["restart_required"] is True
+ assert result["version"] == "9.9.10"
+ # The real reset --hard moved the working tree to B.
+ assert '9.9.10' in (install / "jarvis" / "__init__.py").read_text(encoding="utf-8")
diff --git a/tests/unit/ui/web/test_update_routes.py b/tests/unit/ui/web/test_update_routes.py
new file mode 100644
index 0000000000..e584dbf6e6
--- /dev/null
+++ b/tests/unit/ui/web/test_update_routes.py
@@ -0,0 +1,206 @@
+"""Route + guard tests for the in-app updater (jarvis/ui/web/update_routes.py).
+
+Covers the safety-critical contract: an unmanaged checkout (dev tree / manual
+clone) never sees an update and can never be self-reset, version comparison is
+fail-closed on an unknown running version, and the network check is fail-open.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+import jarvis.ui.web.update_routes as u
+from jarvis.ui.web.update_routes import router as update_router
+
+
[email protected](autouse=True)
+def _reset_cache() -> None:
+ # The status cache is module-global; clear it so each test sees a fresh check.
+ u._status_cache = None
+ u._status_cache_until = 0.0
+
+
+def client() -> TestClient:
+ app = FastAPI()
+ app.include_router(update_router)
+ return TestClient(app)
+
+
+def _patch_managed(monkeypatch: pytest.MonkeyPatch, root: Path | None) -> None:
+ async def _fake() -> Path | None:
+ return root
+
+ monkeypatch.setattr(u, "_resolve_managed_repo", _fake)
+
+
+def _patch_latest(monkeypatch: pytest.MonkeyPatch, result: dict | None) -> None:
+ async def _fake() -> dict | None:
+ return result
+
+ monkeypatch.setattr(u, "_fetch_latest_release", _fake)
+
+
+# --------------------------------------------------------------------------- #
+# Version comparison + remote normalization
+# --------------------------------------------------------------------------- #
+def test_is_newer_basic() -> None:
+ assert u._is_newer("1.0.2", "1.0.1")
+ assert u._is_newer("2.0.0", "1.9.9")
+ assert not u._is_newer("1.0.1", "1.0.1")
+ assert not u._is_newer("1.0.0", "1.0.1")
+
+
+def test_is_newer_fail_closed_on_unknown() -> None:
+ # If we can't tell what we're running, never offer an update.
+ assert not u._is_newer("1.0.2", "unknown")
+ assert not u._is_newer("1.0.2", "")
+ assert not u._is_newer("", "1.0.1")
+
+
+def test_remote_is_official_accepts_only_exact_repo() -> None:
+ # https, ssh, and a local path on either slash style all resolve.
+ assert u._remote_is_official("https://github.com/PersonalJarvis/PersonalJarvis.git")
+ assert u._remote_is_official("[email protected]:PersonalJarvis/PersonalJarvis.git")
+ assert u._remote_is_official("C:\\x\\PersonalJarvis\\PersonalJarvis")
+ # A different repo is rejected...
+ assert not u._remote_is_official("https://github.com/someone/fork.git")
+ # ...and so is a look-alike fork whose name merely starts with the slug...
+ assert not u._remote_is_official(
+ "https://github.com/PersonalJarvis/PersonalJarvisEvil.git"
+ )
+ # ...or one under a different owner with the right repo name.
+ assert not u._remote_is_official("https://github.com/evil/PersonalJarvis.git")
+
+
+# --------------------------------------------------------------------------- #
+# GET /api/update/status
+# --------------------------------------------------------------------------- #
+def test_status_unmanaged_hides_button(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_managed(monkeypatch, None)
+ monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")
+ body = client.get("/api/update/status").json()
+ assert body["managed"] is False
+ assert body["update_available"] is False
+
+
+def test_status_newer_available(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+ monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")
+ _patch_latest(
+ monkeypatch,
+ {
+ "version": "1.0.2",
+ "notes": "New stuff",
+ "published_at": "2026-07-03T00:00:00Z",
+ "release_url": "https://example/releases/v1.0.2",
+ },
+ )
+ body = client.get("/api/update/status").json()
+ assert body["managed"] is True
+ assert body["update_available"] is True
+ assert body["latest"] == "1.0.2"
+ assert body["notes"] == "New stuff"
+
+
+def test_status_same_version_no_update(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+ monkeypatch.setattr(u, "_running_version", lambda: "1.0.2")
+ _patch_latest(
+ monkeypatch,
+ {"version": "1.0.2", "notes": "", "published_at": None, "release_url": None},
+ )
+ body = client.get("/api/update/status").json()
+ assert body["managed"] is True
+ assert body["update_available"] is False
+ assert body["notes"] is None
+
+
+def test_status_network_error_is_fail_open(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+ monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")
+ _patch_latest(monkeypatch, None) # GitHub unreachable
+ body = client.get("/api/update/status").json()
+ assert body["managed"] is True
+ assert body["update_available"] is False
+ assert body.get("check_failed") is True
+
+
+# --------------------------------------------------------------------------- #
+# POST /api/update/apply
+# --------------------------------------------------------------------------- #
+def test_apply_refuses_unmanaged_403(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_managed(monkeypatch, None)
+ # Even a spoofed client can never trigger a self-reset on a dev tree.
+ assert client.post("/api/update/apply").status_code == 403
+
+
+def test_apply_happy_path_pulls_and_signals_restart(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+ calls: list[list[str]] = []
+
+ async def _fake_git(args, *, cwd, timeout_s=60.0):
+ calls.append(args)
+ return 0, "", ""
+
+ monkeypatch.setattr(u, "_git", _fake_git)
+ monkeypatch.setattr(u, "_version_on_disk", lambda root: "1.0.2")
+ body = client.post("/api/update/apply").json()
+ assert body["ok"] is True
+ assert body["restart_required"] is True
+ assert body["version"] == "1.0.2"
+ assert ["fetch", "--depth", "1", "origin", "main"] in calls
+ assert ["reset", "--hard", "origin/main"] in calls
+
+
+def test_apply_git_fetch_failure_is_502(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+
+ async def _fake_git(args, *, cwd, timeout_s=60.0):
+ return 1, "", "network down"
+
+ monkeypatch.setattr(u, "_git", _fake_git)
+ assert client.post("/api/update/apply").status_code == 502
+
+
+def test_apply_refreshes_deps_only_when_lockfile_changes(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+ # _hash_file is called before and after the reset; return distinct values
+ # to simulate a changed requirements.txt.
+ states = iter(["hash-before", "hash-after"])
+ monkeypatch.setattr(u, "_hash_file", lambda path: next(states))
+
+ async def _fake_git(args, *, cwd, timeout_s=60.0):
+ return 0, "", ""
+
+ monkeypatch.setattr(u, "_git", _fake_git)
+ monkeypatch.setattr(u, "_version_on_disk", lambda root: "1.0.2")
+ refreshed: dict[str, bool] = {}
+
+ async def _fake_refresh(root):
+ refreshed["called"] = True
+ return True, ""
+
+ monkeypatch.setattr(u, "_refresh_dependencies", _fake_refresh)
+ body = client.post("/api/update/apply").json()
+ assert body["deps_refreshed"] is True
+ assert refreshed.get("called") is True