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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(install): transactional self-update — relauncher update contract, installer flow hardening
Ruben Lütkeb680a3370b40
diff --git a/install/README.md b/install/README.mdindex 61b9295517..55f980a123 100644--- a/install/README.md+++ b/install/README.md@@ -35,13 +35,26 @@ or the Linux application menu. The in-app updater and first desktop launchrepair these artifacts, and uninstall removes them again. Developer checkoutsand headless Linux hosts are deliberately not registered.+On macOS, every launch path enters through the same app bundle so privacy+grants stay attached to one identity. The source installer builds a native+py2app alias launcher, ad-hoc signs it for that machine, verifies the identity+from inside a LaunchServices process, and preserves the bundle unchanged across+ordinary updates. A separately distributed binary still requires the release+pipeline's Developer-ID signing and notarization. Apple does not permit an installer to+silently grant Microphone, Screen Recording, Accessibility, Input Monitoring,+or input-control access. The app therefore presents one explicit button per+permission during first launch, uses only Apple's native prompt/System Settings+flows, and remains fully usable for text when the user declines. The installer+stops instead of claiming success if the full profile or app-bundle registration+fails.+## File layout| File | Stage | Responsibility ||-------------------|-------|----------------|| `install.ps1` | 1 | Windows bootstrap: Python+Git detect/install/re-check, clone, venv, install `rich`, exec `installer.py`. || `install.sh` | 1 | macOS/Linux bootstrap: same flow through native package managers, POSIX bash. |-| `installer.py` | 2 | Python orchestrator: pip install, optional extras, model prefetch, worker CLI, desktop registration, launch (last). |+| `installer.py` | 2 | Python orchestrator: full-profile install, model prefetch, worker CLI, desktop registration, launch (last). || `README.md` | docs | This file. |## Why two stages?diff --git a/install/installer.py b/install/installer.pyindex ca23e77668..cff1a272d5 100644--- a/install/installer.py+++ b/install/installer.py@@ -32,7 +32,8 @@ Exit codes:0 success1 pre-flight failure (Python version, missing files)2 pip install failure- 4 launch failure+ 4 desktop registration or launch failure+ 5 shipped UI bundle missing or incomplete"""from __future__ import annotations@@ -40,8 +41,11 @@ import argparseimport jsonimport osimport platform+import shutil+import statimport subprocessimport sys+import sysconfigfrom pathlib import Path# CLAUDE.md: new CLI modules must use UTF-8 stdout or stick to ASCII. Without@@ -178,7 +182,7 @@ def step_preflight() -> None:sys.exit(1)-def write_managed_marker() -> None:+def write_managed_marker(*, with_desktop: bool) -> None:"""Mark this checkout as an installer-managed copy.The in-app "Update Now" button (jarvis/ui/web/update_routes.py) only appears,@@ -193,6 +197,8 @@ def write_managed_marker() -> None:"managed": True,"install_path": str(repo_root()),"created_by": "install/installer.py",+ "profile": "full" if with_desktop else "headless",+ "desktop": with_desktop,}try:marker.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")@@ -201,6 +207,59 @@ def write_managed_marker() -> None:note(f"could not write update marker ({exc}); in-app updates stay disabled")+def repair_distribution_metadata(+ *, site_packages: Path | None = None, dry_run: bool = False+) -> bool:+ """Remove torn ``dist-info`` records left by an interrupted old update.++ The legacy updater could run while Python still had the environment open.+ On Windows that sometimes left empty or RECORD-only metadata directories;+ pip then treated the environment as corrupt and could not prove that the+ next update was complete. Removing only invalid metadata is safe: the+ normal install plan immediately restores every distribution still required+ by the selected profile, while obsolete packages remain unregistered.+ """+ if dry_run:+ note("(dry-run) repair interrupted package metadata")+ return True++ root = site_packages or Path(sysconfig.get_path("purelib"))+ try:+ candidates = sorted(root.glob("*.dist-info"))+ except OSError as exc:+ note(f"could not inspect package metadata ({exc})")+ return False++ broken: list[Path] = []+ for candidate in candidates:+ metadata = candidate / "METADATA"+ try:+ content = metadata.read_text(encoding="utf-8", errors="replace")+ except OSError:+ broken.append(candidate)+ continue+ if "Metadata-Version:" not in content or "\nName:" not in f"\n{content}":+ broken.append(candidate)++ for candidate in broken:+ try:+ if candidate.is_symlink():+ candidate.unlink()+ else:+ def _retry_readonly(func, path, _exc_info):+ os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)+ func(path)++ shutil.rmtree(candidate, onerror=_retry_readonly)+ except OSError as exc:+ note(f"could not repair package metadata at {candidate.name} ({exc})")+ return False++ if broken:+ ok(f"repaired {len(broken)} interrupted package metadata record(s)")+ return True++def step_pip_install(*, with_desktop: bool, with_voice_local: bool, dry_run: bool) -> None:phase("4/6", "Dependencies")pip = [str(venv_python()), "-m", "pip"]@@ -237,9 +296,14 @@ def step_pip_install(*, with_desktop: bool, with_voice_local: bool, dry_run: boo# ``with_voice_local`` is a deprecated no-op: [full] already carries it.plans.append(("full profile extras (desktop, telephony, channels, local voice)",pip + ["install", "-e", ".[full]"]))+ plans.append(("dependency consistency check", pip + ["check"]))note("this can take a minute — grabbing dependencies")+ if not repair_distribution_metadata(dry_run=dry_run):+ console.print("[bad] ✗ package metadata repair failed — installation stopped.[/]")+ sys.exit(2)+if dry_run:for label, cmd in plans:# rich would swallow literal command text like ``.[full]`` as@@ -250,10 +314,10 @@ def step_pip_install(*, with_desktop: bool, with_voice_local: bool, dry_run: boofor label, cmd in plans:rc = run_quiet(cmd, label=label, cwd=repo_root())if rc != 0:- # Desktop / voice-local extras are best-effort — never fatal.- if "extras" in label:- console.print(f"[bad] ✗ {label} failed — continuing without it.[/]")- continue+ # The advertised desktop install is the [full] profile. Continuing+ # after that profile fails would advertise a ready app without the+ # microphone, macOS bridge, or local-voice dependencies it needs.+ console.print(f"[bad] ✗ {label} failed — installation stopped.[/]")sys.exit(2)ok(label)@@ -367,13 +431,13 @@ def step_worker_cli(*, dry_run: bool) -> None:note("Jarvis-Agent worker CLI install failed - it can be added later in-app")-def step_desktop_integration(*, enabled: bool, dry_run: bool) -> None:+def step_desktop_integration(*, enabled: bool, dry_run: bool) -> bool:"""Register the managed install with the current desktop shell."""if not enabled:- return+ return Trueif dry_run:console.print("[muted] (dry-run) repair desktop-shell registration[/]")- return+ return Truetry:result = subprocess.run([@@ -386,7 +450,9 @@ def step_desktop_integration(*, enabled: bool, dry_run: bool) -> None:],cwd=repo_root(),capture_output=True, text=True, encoding="utf-8", errors="replace",- timeout=120,+ # py2app build + icon conversion + signing + LaunchServices import+ # probe can legitimately exceed two minutes on Intel macOS.+ timeout=600,)output = (result.stdout or "").strip().splitlines()report = json.loads(output[-1]) if output else {}@@ -402,11 +468,15 @@ def step_desktop_integration(*, enabled: bool, dry_run: bool) -> None:and report.get("attempted")):ok("desktop app registered with the operating system")- else:- note("desktop registration is incomplete - the app will retry after first paint")+ return True+ console.print(+ "[bad] ✗ desktop app registration failed — installation stopped. "+ "The app must have a stable launcher identity.[/]"+ )+ return False-def step_ui_bundle_check() -> None:+def step_ui_bundle_check() -> bool:"""Honest packaging check: the shipped UI build must be present + intact.The public snapshot ships a prebuilt ``jarvis/ui/web/dist``; a dev clone@@ -418,19 +488,32 @@ def step_ui_bundle_check() -> None:if not index.is_file():note("no prebuilt UI found (dev clone?) - the app will serve a minimal page")note("public installs always ship the UI; if you used the one-liner, please report this")- return+ return Falseimport re- html = index.read_text(encoding="utf-8", errors="replace")+ try:+ html = index.read_text(encoding="utf-8", errors="replace")+ except OSError:+ console.print("[bad] UI build index is unreadable.[/]")+ return False+ refs = [+ ref.split("?", 1)[0]+ for ref in re.findall(r'(?:src|href)="/?(assets/[^"]+)"', html)+ ]+ if not any(ref.endswith(".js") for ref in refs):+ console.print("[bad] UI build has no JavaScript entry bundle.[/]")+ return Falsemissing = [- ref for ref in re.findall(r'(?:src|href)="/?(assets/[^"]+)"', html)+ ref for ref in refsif not (dist / ref.replace("/", os.sep)).is_file()]if missing:console.print(f"[bad] UI build is incomplete ({missing[0]} missing) - ""please report this; the app may look broken.[/]")+ return Falseelse:ok("UI build present and intact")+ return Truedef _resolved_admin_port() -> int:@@ -462,6 +545,22 @@ def step_launch(*, headless: bool, dry_run: bool) -> None:elif sys.platform == "win32":cmd = [str(repo_root() / "run.bat")]msg = "the Desktop App"+ elif sys.platform == "darwin":+ from jarvis.setup.macos_app_bundle import (+ macos_app_bundle_is_launchable,+ macos_app_bundle_path,+ macos_launch_services_command,+ )++ bundle = macos_app_bundle_path()+ if not macos_app_bundle_is_launchable(bundle):+ console.print(+ "[bad] Could not launch: the installed macOS app bundle is missing "+ "or invalid.[/]"+ )+ sys.exit(4)+ cmd = macos_launch_services_command(bundle)+ msg = "the Desktop App"else:cmd = [str(venv_python()), "-m", "jarvis.ui.web.launcher"]msg = "the Desktop App"@@ -499,6 +598,10 @@ def step_summary(*, no_launch: bool, update: bool, headless: bool) -> None:" [muted]Start again[/] [brand]Spotlight → \"Personal Jarvis\"[/] ""[muted](app in ~/Applications)[/]")+ console.print(+ " [muted]Permissions[/] [muted]macOS asks on first launch; approve each "+ "item in the guided setup[/]"+ )elif sys.platform.startswith("linux") and not (headless or is_headless_linux()):console.print(" [muted]Start again[/] [brand]app menu -> \"Personal Jarvis\"[/]"@@ -581,7 +684,7 @@ def main(argv: list[str] | None = None) -> int:step_preflight()if not args.dry_run:- write_managed_marker()+ write_managed_marker(with_desktop=with_desktop)if not os.environ.get("JARVIS_INSTALL_NO_PIP"):step_pip_install(with_desktop=with_desktop,@@ -593,8 +696,10 @@ def main(argv: list[str] | None = None) -> int:phase("6/6", "Finish & launch")step_worker_cli(dry_run=args.dry_run)- step_desktop_integration(enabled=with_desktop, dry_run=args.dry_run)- step_ui_bundle_check()+ if not step_desktop_integration(enabled=with_desktop, dry_run=args.dry_run):+ sys.exit(4)+ if not step_ui_bundle_check() and not args.dry_run:+ sys.exit(5)# Summary FIRST, launch LAST: when the app window appears, the terminal# story is already told — and everything the first launch needs is on disk.diff --git a/jarvis.spec b/jarvis.specindex 3ec8dfe1fe..5da64e8029 100644--- a/jarvis.spec+++ b/jarvis.spec@@ -41,6 +41,7 @@ if FRONTEND_DIST.exists():# Include the default configuration loaded by a fresh desktop installation.datas.append((str(PROJECT_ROOT / "jarvis.toml"), "."))+datas.append((str(PROJECT_ROOT / "docs" / "product"), "docs/product"))# Include build-time desktop assets such as icons and chimes when present.assets_dir = PROJECT_ROOT / "assets"diff --git a/jarvis/ui/relauncher.py b/jarvis/ui/relauncher.pyindex 95b1419140..654dde8cc8 100644--- a/jarvis/ui/relauncher.py+++ b/jarvis/ui/relauncher.py@@ -19,18 +19,53 @@ start fast and never pull the heavy ``jarvis`` runtime into a throwaway process."""from __future__ import annotations+import json+import loggingimport os+import reimport subprocessimport sysimport threadingimport time+from pathlib import PathLAUNCHER_MODULE = "jarvis.ui.web.launcher"+MANAGED_MARKER = ".jarvis-managed-install"+PENDING_UPDATE_FILENAME = ".jarvis-update-pending.json"+UPDATE_RESULT_FILENAME = ".jarvis-update-result.json"+_REVISION_RE = re.compile(r"^[0-9a-fA-F]{7,64}$")def build_launch_command(executable: str) -> list[str]:- """Argv that boots a fresh desktop app with the same interpreter."""- return [executable, "-m", LAUNCHER_MODULE]+ """Argv that boots a fresh desktop app through its stable OS identity.++ A macOS desktop restart always re-enters through LaunchServices so it can+ never attach TCC access to a raw Python interpreter. A missing or invalid+ bundle therefore fails closed; the managed installer/repair path owns+ recreating it.+ """+ fallback = [executable, "-m", LAUNCHER_MODULE]+ if sys.platform == "darwin":+ bundle = Path.home() / "Applications" / "Personal Jarvis.app"+ try:+ from jarvis.setup.macos_app_bundle import (+ macos_app_bundle_is_launchable,+ macos_app_bundle_path,+ macos_launch_services_command,+ )++ bundle = macos_app_bundle_path()+ if not macos_app_bundle_is_launchable(bundle):+ logging.getLogger(__name__).error(+ "macOS restart target is missing or invalid: %s", bundle+ )+ return macos_launch_services_command(bundle, wait_for_exit=True)+ except Exception: # noqa: BLE001 - preserve stable identity fail-closed+ logging.getLogger(__name__).exception(+ "Could not validate the macOS restart bundle; using its canonical path"+ )+ return ["/usr/bin/open", "-W", "-a", str(bundle)]+ return fallbackdef detached_creationflags() -> int:@@ -179,6 +214,215 @@ def _new_instance_settled(return True+def _read_pending_update(root: Path) -> dict[str, object] | None:+ """Read and strictly validate a relaunch-time update transaction."""++ try:+ payload = json.loads(+ (root / PENDING_UPDATE_FILENAME).read_text(encoding="utf-8")+ )+ except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError):+ return None+ if not isinstance(payload, dict) or payload.get("schema") != 1:+ return None+ previous = payload.get("previous_revision")+ target = payload.get("target_revision")+ profile = payload.get("profile")+ if not isinstance(previous, str) or not _REVISION_RE.fullmatch(previous):+ return None+ if not isinstance(target, str) or not _REVISION_RE.fullmatch(target):+ return None+ if profile not in {"full", "headless"}:+ return None+ return payload+++def _managed_python(root: Path) -> str:+ """Use only the checkout venv for installer work when it is available."""++ if sys.platform == "win32":+ candidate = root / ".venv" / "Scripts" / "python.exe"+ else:+ candidate = root / ".venv" / "bin" / "python"+ return str(candidate if candidate.is_file() else Path(sys.executable))+++def _run_update_command(+ cmd: list[str], *, root: Path, timeout: float+) -> int:+ """Run a windowless update child and collapse every launch failure to -1."""++ kwargs: dict[str, object] = {+ "cwd": str(root),+ "env": {+ key: value+ for key, value in os.environ.items()+ if key != "JARVIS_INSTALL_NO_PIP"+ },+ "stdin": subprocess.DEVNULL,+ "stdout": subprocess.DEVNULL,+ "stderr": subprocess.DEVNULL,+ "timeout": timeout,+ "check": False,+ }+ if sys.platform == "win32":+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)+ try:+ return subprocess.run(cmd, **kwargs).returncode+ except (OSError, subprocess.SubprocessError):+ return -1+++def _installer_command(root: Path, profile: str) -> list[str]:+ """Build the full, no-relaunch installer command for an update profile."""++ cmd = [+ _managed_python(root),+ str(root / "install" / "installer.py"),+ "--no-launch",+ ]+ cmd.append("--with-desktop" if profile == "full" else "--headless")+ return cmd+++def _ui_bundle_ready(root: Path) -> bool:+ """Verify that the checked-out release owns a loadable JS/CSS entry set."""++ dist = root / "jarvis" / "ui" / "web" / "dist"+ index = dist / "index.html"+ try:+ html = index.read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError):+ return False+ refs = {+ match.group(1).split("?", 1)[0]+ for match in re.finditer(r'(?:src|href)=["\']/?(assets/[^"\']+)', html)+ }+ if not any(ref.endswith(".js") for ref in refs):+ return False++ required = {"jarvis/ui/web/dist/index.html"}+ for ref in refs:+ asset = dist / Path(ref)+ try:+ if not asset.is_file() or asset.stat().st_size <= 0:+ return False+ except OSError:+ return False+ required.add(f"jarvis/ui/web/dist/{ref}")++ for rel in required:+ if _run_update_command(+ ["git", "ls-files", "--error-unmatch", "--", rel],+ root=root,+ timeout=30.0,+ ) != 0:+ return False+ return True+++def _write_update_result(+ root: Path,+ *,+ ok: bool,+ rolled_back: bool,+ previous_revision: str,+ target_revision: str,+) -> None:+ """Persist a non-sensitive result for diagnostics after the new launch."""++ path = root / UPDATE_RESULT_FILENAME+ temp = path.with_suffix(path.suffix + ".tmp")+ payload = {+ "schema": 1,+ "ok": ok,+ "rolled_back": rolled_back,+ "previous_revision": previous_revision,+ "target_revision": target_revision,+ "completed_at": int(time.time()),+ }+ try:+ temp.write_text(json.dumps(payload, sort_keys=True) + "\n", encoding="utf-8")+ os.replace(temp, path)+ except OSError:+ pass+++def finalize_pending_update(cwd: str | Path) -> bool:+ """Apply a fetched update while the old app is fully stopped.++ Success requires the complete installer and a tracked JavaScript bundle.+ Any failure resets the checkout to the exact previous revision and runs its+ installer once more before launch, so an incomplete update is never treated+ as installed.+ """++ root = Path(cwd).resolve()+ pending_path = root / PENDING_UPDATE_FILENAME+ payload = _read_pending_update(root)+ if payload is None:+ return True+ if not (root / MANAGED_MARKER).is_file() or not (root / ".git").exists():+ pending_path.unlink(missing_ok=True)+ return False++ previous = str(payload["previous_revision"])+ target = str(payload["target_revision"])+ profile = str(payload["profile"])++ target_reset_ok = (+ _run_update_command(+ ["git", "reset", "--hard", target], root=root, timeout=120.0+ )+ == 0+ )+ target_install_ok = False+ if target_reset_ok:+ target_install_ok = (+ _run_update_command(+ _installer_command(root, profile), root=root, timeout=3600.0+ )+ == 0+ and _ui_bundle_ready(root)+ )+ if target_install_ok:+ pending_path.unlink(missing_ok=True)+ _write_update_result(+ root,+ ok=True,+ rolled_back=False,+ previous_revision=previous,+ target_revision=target,+ )+ return True++ rollback_reset_ok = (+ _run_update_command(+ ["git", "reset", "--hard", previous], root=root, timeout=120.0+ )+ == 0+ )+ rollback_install_ok = False+ if rollback_reset_ok:+ rollback_install_ok = (+ _run_update_command(+ _installer_command(root, profile), root=root, timeout=3600.0+ )+ == 0+ and _ui_bundle_ready(root)+ )+ pending_path.unlink(missing_ok=True)+ rolled_back = rollback_reset_ok and rollback_install_ok+ _write_update_result(+ root,+ ok=False,+ rolled_back=rolled_back,+ previous_revision=previous,+ target_revision=target,+ )+ return False++def main(argv: list[str] | None = None,*,@@ -187,6 +431,7 @@ def main(_sleep=time.sleep,_alive=pid_alive,_settled=_new_instance_settled,+ _finalize_update=finalize_pending_update,attempts: int = 3,) -> int:"""Wait for the old app to exit, then start a fresh launcher — verified.@@ -214,15 +459,25 @@ def main(else:kwargs["start_new_session"] = True+ update_finalized = Falsefor attempt in range(attempts):# Never launch into a still-held lock: the old process must be gone.if _alive(pid):- _wait(pid, timeout=45.0 if attempt == 0 else 15.0)+ parent_exited = _wait(pid, timeout=45.0 if attempt == 0 else 15.0)+ if not parent_exited:+ continue# Extra grace so the kernel finishes releasing the mutex + the TCP port# before the new launcher tries to claim them. Short — the kernel frees# both the instant the old PID is gone; this only covers the tail._sleep(0.2)+ # Update only after the old interpreter has released imported native+ # modules. The finalizer runs the complete installer and rolls back on+ # any incomplete dependency, UI, or desktop-registration result.+ if not update_finalized:+ _finalize_update(cwd)+ update_finalized = True+proc = _spawn(build_launch_command(sys.executable), **kwargs)new_pid = getattr(proc, "pid", None)if _settled(new_pid, _alive=_alive, _sleep=_sleep):diff --git a/jarvis/ui/shell/single_instance.py b/jarvis/ui/shell/single_instance.pyindex f5ed0293b1..bd1c6d81d1 100644--- a/jarvis/ui/shell/single_instance.py+++ b/jarvis/ui/shell/single_instance.py@@ -128,8 +128,8 @@ class SingleInstance:def write_session(self, *, port: int, token: str) -> None:data = {"port": port, "token": token, "pid": os.getpid()}path = self.session_file- # The token authorizes the full control API, so the file must be- # owner-only. O_CREAT's mode keeps a NEW file at 0600 from the first+ # The token can bootstrap an authenticated UI session, so the file must+ # be owner-only. O_CREAT's mode keeps a NEW file at 0600 from the first# byte; the explicit chmod repairs a pre-existing file from older# builds that wrote with the default umask. Windows relies on the# per-user profile ACL instead of POSIX bits.diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.pyindex 40a6d92710..0df890034b 100644--- a/jarvis/ui/web/update_routes.py+++ b/jarvis/ui/web/update_routes.py@@ -9,12 +9,11 @@ Now" button so the user never has to re-run the installer from a terminal:published GitHub Release and reports whether an update is available (plus itsrelease notes). It is **fail-open**: any network or parse error reports "noupdate" 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 repairs the platform's desktop registration- before reporting ``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.+* ``POST /api/update/apply`` — fetches and pins the exact target revision, then+ writes a pending-update manifest without changing the running checkout. The+ caller hits ``POST /api/settings/restart-app``; after the old process exits,+ the detached relauncher applies the revision and re-runs the full installer+ before it starts the new app.Safety-critical guard (the single most important thing here):``git reset --hard`` destroys uncommitted local changes. That is fine for an@@ -29,23 +28,24 @@ renders) and ``apply`` refuses with HTTP 403. This makes the dev tree and anyfork 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).+``NO_WINDOW_CREATIONFLAGS`` (AP-1, no console flash under ``pythonw.exe``).+Dependency and desktop files are changed only by the detached relauncher after+the live process has released imported modules. On a headless VPS the fetch+works and the caller's restart step degrades honestly (``restart-app`` returns+503)."""from __future__ import annotationsimport asyncio-import hashlibimport jsonimport logging+import osimport reimport sysimport timefrom pathlib import Path-from typing import Any+from typing import Any, Literalfrom fastapi import APIRouter, HTTPException@@ -65,10 +65,15 @@ _RELEASES_LATEST_API = (# 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"+_PENDING_UPDATE_NAME = ".jarvis-update-pending.json"+_UPDATE_RESULT_NAME = ".jarvis-update-result.json"_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.+_RELEASE_TAG_RE = re.compile(+ r"^v?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$"+)# 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.@@ -140,7 +145,22 @@ def _is_newer(latest: str, current: str) -> bool:return Version(latest) > Version(current)except ImportError:return _naive_version_gt(latest, current)- except Exception: # noqa: BLE001 — InvalidVersion → not newer+ except Exception: # noqa: BLE001 - malformed versions are never newer+ return False+++def _versions_equal(left: str, right: str) -> bool:+ """Compare release versions and fail closed on malformed metadata."""+ if not left or not right:+ return False+ try:+ from packaging.version import Version++ return Version(left) == Version(right)+ except ImportError:+ dotted = re.compile(r"^\d+(?:\.\d+){2,3}$")+ return bool(dotted.fullmatch(left) and left == right)+ except Exception: # noqa: BLE001 - malformed versions never compare equalreturn False@@ -289,11 +309,12 @@ async def _fetch_latest_release() -> dict[str, Any] | None:log.debug("update check: releases/latest HTTP %s", resp.status_code)return Nonedata = resp.json()- tag = str(data.get("tag_name") or "").strip().lstrip("vV")- if not tag:+ release_tag = str(data.get("tag_name") or "").strip()+ if not _RELEASE_TAG_RE.fullmatch(release_tag):return Nonereturn {- "version": tag,+ "version": release_tag.lstrip("vV"),+ "tag": release_tag,"notes": (data.get("body") or "").strip(),"published_at": data.get("published_at"),"release_url": data.get("html_url"),@@ -304,77 +325,80 @@ async def _fetch_latest_release() -> dict[str, Any] | None:# --------------------------------------------------------------------------- #-# Dependency refresh (best-effort)+# Managed install profile + deferred transaction manifest# --------------------------------------------------------------------------- #-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+InstallProfile = Literal["full", "headless"]-async def _refresh_dependencies(root: Path) -> tuple[bool, str]:- """Best-effort ``pip install -r requirements.txt`` on the venv python.+def _managed_install_profile(root: Path) -> InstallProfile:+ """Resolve the installer profile, including pre-profile marker fallback.- Only called when the lockfile actually changed. Never raises; a failure is- reported so the UI can warn honestly (the pull still succeeded).+ New installers persist the decision in the managed marker. Older markers+ predate that field, so desktop sessions retain the advertised ``[full]``+ profile while a display-less Linux host keeps the torch-free base floor."""- 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, ""+ try:+ payload = json.loads((root / _MARKER_NAME).read_text(encoding="utf-8"))+ except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError):+ payload = {}+ if isinstance(payload, dict):+ profile = payload.get("profile")+ if profile in {"full", "headless"}:+ return profile+ desktop = payload.get("desktop")+ if isinstance(desktop, bool):+ return "full" if desktop else "headless"++ if sys.platform in {"win32", "darwin"}:+ return "full"+ if sys.platform.startswith("linux") and (+ os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")+ ):+ return "full"+ return "headless"+++def _write_pending_update(+ root: Path,+ *,+ previous_revision: str,+ target_revision: str,+ profile: InstallProfile,+) -> None:+ """Atomically stage the post-exit update transaction for the relauncher."""++ path = root / _PENDING_UPDATE_NAME+ temp = path.with_suffix(path.suffix + ".tmp")+ payload = {+ "schema": 1,+ "previous_revision": previous_revision,+ "target_revision": target_revision,+ "profile": profile,+ "created_at": int(time.time()),+ }+ temp.write_text(json.dumps(payload, sort_keys=True) + "\n", encoding="utf-8")+ os.replace(temp, path)+ try:+ (root / _UPDATE_RESULT_NAME).unlink(missing_ok=True)+ except OSError:+ pass-async def _refresh_desktop_integration(root: Path) -> tuple[bool, str]:- """Run the freshly pulled desktop-registration code in the install venv.- The updater process still has the old modules in memory after ``git reset``.- A subprocess is therefore intentional: it imports the new checkout and can- create a Windows Installed Apps entry, a macOS bundle, or a Linux desktop- entry before the current process exits. Headless Linux reports a clean skip.- """+async def _version_at_revision(root: Path, revision: str) -> str | None:+ """Read a target version without checking that target out over the live app."""- py = _venv_python(root)- rc, out, err = await _run(- [- str(py),- "-m",- "jarvis.setup.desktop_integration",- "--install-dir",- str(root),- "--json",- ],- cwd=root,- timeout_s=120.0,- )- if rc != 0:- return False, (err or out or "desktop registration failed")[-400:]- try:- payload = json.loads(out.splitlines()[-1])- except (IndexError, json.JSONDecodeError, TypeError):- return False, "desktop registration returned an unreadable result"- if not payload.get("ok"):- warnings = payload.get("warnings") or []- detail = "; ".join(str(item) for item in warnings)- return False, (detail or "desktop registration is incomplete")[-400:]- return True, ""+ for rel, pattern in (+ ("jarvis/__init__.py", r'__version__\s*=\s*"([^"]+)"'),+ ("pyproject.toml", r'^version\s*=\s*"([^"]+)"'),+ ):+ raw = await _git_output(["show", f"{revision}:{rel}"], cwd=root)+ if raw is None:+ continue+ match = re.search(pattern, raw, re.MULTILINE)+ if match:+ return match.group(1)+ return None# --------------------------------------------------------------------------- #@@ -436,14 +460,13 @@ async def update_status(force: bool = False) -> dict[str, object]:return result[email protected]("/apply")[email protected]("/apply", openapi_extra={"x-jarvis-dangerous": True})async def update_apply() -> dict[str, object]:- """Pull the latest code for a managed install. Does NOT restart.+ """Prepare the latest code for a managed install. Does NOT restart.- Returns update, dependency, and desktop-registration status plus- ``restart_required``.- The caller applies the update by then calling- ``POST /api/settings/restart-app``.+ The live checkout remains untouched. The caller then invokes+ ``POST /api/settings/restart-app``; its detached relauncher applies the+ pinned revision and completes installation after this process exits."""root = await _resolve_managed_repo()if root is None:@@ -452,45 +475,82 @@ async def update_apply() -> dict[str, object]: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")+ latest = await _fetch_latest_release()+ if latest is None:+ raise HTTPException(+ status_code=502,+ detail="could not resolve the latest published release",+ )+ release_version = str(latest.get("version") or "")+ release_tag = str(latest.get("tag") or "")+ if not _RELEASE_TAG_RE.fullmatch(release_tag):+ raise HTTPException(status_code=502, detail="latest release tag is invalid")+ if not _is_newer(release_version, _running_version()):+ raise HTTPException(status_code=409, detail="no newer published release exists")++ previous_revision = await _git_output(["rev-parse", "HEAD"], cwd=root)+ if not previous_revision:+ raise HTTPException(+ status_code=500,+ detail="could not identify the currently installed revision",+ )+ # Fetch the published tag, never the moving main branch. The update button+ # promises a specific GitHub Release; applying an unreleased main commit+ # would make the displayed version and installed bytes disagree.rc, _out, err = await _git(- ["fetch", "--depth", "1", "origin", "main"], cwd=root, timeout_s=120.0+ ["fetch", "--depth", "1", "origin", f"refs/tags/{release_tag}"],+ 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:++ target_revision = await _git_output(+ ["rev-parse", "FETCH_HEAD^{commit}"], cwd=root+ )+ if not target_revision:raise HTTPException(- status_code=500, detail=f"git reset failed: {err[:300] or 'unknown error'}"+ status_code=500,+ detail="could not identify the fetched update revision",)- # 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-- desktop_integration_ok, desktop_integration_warning = (- await _refresh_desktop_integration(root)- )+ new_version = await _version_at_revision(root, target_revision)+ if new_version is None or not _versions_equal(new_version, release_version):+ raise HTTPException(+ status_code=502,+ detail="published tag version does not match its release metadata",+ )++ profile = _managed_install_profile(root)+ try:+ _write_pending_update(+ root,+ previous_revision=previous_revision,+ target_revision=target_revision,+ profile=profile,+ )+ except OSError as exc:+ log.warning("Could not stage the pending update manifest: %s", type(exc).__name__)+ raise HTTPException(+ status_code=500,+ detail="could not stage the update transaction",+ ) from exc- new_version = _version_on_disk(root) or _running_version()return {"ok": True,+ "prepared": True,"restart_required": True,"version": new_version,- "deps_refreshed": deps_refreshed,- "deps_warning": deps_warning,- "desktop_integration_ok": desktop_integration_ok,- "desktop_integration_warning": desktop_integration_warning or None,+ "release_tag": release_tag,+ "install_profile": profile,+ "deps_refreshed": False,+ "deps_pending": True,+ "deps_warning": None,+ "ui_bundle_pending": True,+ "desktop_integration_ok": None,+ "desktop_integration_pending": profile == "full",+ "desktop_integration_warning": None,}diff --git a/tests/integration/test_update_apply_real_git.py b/tests/integration/test_update_apply_real_git.pyindex 8889315a84..b93b9d358a 100644--- a/tests/integration/test_update_apply_real_git.py+++ b/tests/integration/test_update_apply_real_git.py@@ -1,10 +1,8 @@-"""Integration test: the updater's REAL git operations against a local repo.+"""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.+A real bare upstream and installed clone prove that the managed guard requires+the marker plus official-slug origin, and that apply fetches the exact published+tag without mutating the running checkout. Only the release-API edge is mocked."""from __future__ import annotations@@ -28,6 +26,16 @@ def _git(args: list[str], cwd: Path) -> None:)+def _git_output(args: list[str], cwd: Path) -> str:+ return subprocess.run(+ ["git", *args],+ cwd=str(cwd),+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()++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.@@ -66,29 +74,37 @@ def test_managed_guard_passes_with_real_git(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:+def test_real_apply_fetches_and_pins_without_mutating_live_head(+ 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(["tag", "v9.9.10"], seed)_git(["push", "origin", "main"], seed)+ _git(["push", "origin", "v9.9.10"], 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)+ monkeypatch.setattr(u, "_running_version", lambda: "9.9.9")- async def _desktop_ok(_root: Path) -> tuple[bool, None]:- return True, None+ async def _latest() -> dict[str, object]:+ return {"version": "9.9.10", "tag": "v9.9.10"}- monkeypatch.setattr(u, "_refresh_desktop_integration", _desktop_ok)+ monkeypatch.setattr(u, "_fetch_latest_release", _latest)result = asyncio.run(u.update_apply())assert result["ok"] is True+ assert result["prepared"] is Trueassert result["restart_required"] is Trueassert result["version"] == "9.9.10"- assert result["desktop_integration_ok"] is True- # The real reset --hard moved the working tree to B.- assert '9.9.10' in (install / "jarvis" / "__init__.py").read_text(encoding="utf-8")+ # The running checkout stays on A until the old process has exited.+ assert '9.9.9' in (install / "jarvis" / "__init__.py").read_text(encoding="utf-8")+ pending = (install / u._PENDING_UPDATE_NAME).read_text(encoding="utf-8")+ assert _git_output(["rev-parse", "HEAD"], install) in pending+ assert _git_output(["rev-parse", "FETCH_HEAD^{commit}"], install) in pendingdiff --git a/tests/unit/install/test_installer_flow.py b/tests/unit/install/test_installer_flow.pyindex 230dc4d04e..6a494c0ed1 100644--- a/tests/unit/install/test_installer_flow.py+++ b/tests/unit/install/test_installer_flow.py@@ -2,6 +2,8 @@import importlib.utilfrom pathlib import Path+import pytest+REPO = Path(__file__).resolve().parents[3]_spec = importlib.util.spec_from_file_location("installer", REPO / "install" / "installer.py")installer = importlib.util.module_from_spec(_spec)@@ -101,6 +103,43 @@ def test_headless_pip_plan_stays_base_floor(capsys) -> None:assert ".[desktop]" not in out+def test_full_profile_failure_stops_desktop_install(monkeypatch) -> None:+ results = iter([0, 0, 1])+ monkeypatch.setattr(installer, "run_quiet", lambda *args, **kwargs: next(results))++ with pytest.raises(SystemExit, match="2"):+ installer.step_pip_install(+ with_desktop=True,+ with_voice_local=False,+ dry_run=False,+ )+++def test_macos_launch_enters_through_application_bundle(monkeypatch, tmp_path) -> None:+ launched: dict[str, object] = {}+ bundle = tmp_path / "Personal Jarvis.app"+ monkeypatch.setattr(installer.sys, "platform", "darwin")+ monkeypatch.setattr(+ "jarvis.setup.macos_app_bundle.macos_app_bundle_path", lambda: bundle+ )+ monkeypatch.setattr(+ "jarvis.setup.macos_app_bundle.macos_app_bundle_is_launchable", lambda _p: True+ )+ monkeypatch.setattr(+ "jarvis.setup.macos_app_bundle.macos_launch_services_command",+ lambda _p: ["/usr/bin/open", "-a", str(bundle)],+ )+ monkeypatch.setattr(+ installer.subprocess,+ "Popen",+ lambda cmd, **kwargs: launched.update(cmd=cmd, kwargs=kwargs),+ )++ installer.step_launch(headless=False, dry_run=False)++ assert launched["cmd"] == ["/usr/bin/open", "-a", str(bundle)]++def test_linux_gui_gets_full_profile_and_app_menu_registration(monkeypatch, capsys) -> None:diff --git a/tests/unit/install/test_installer_update_contract.py b/tests/unit/install/test_installer_update_contract.pynew file mode 100644index 0000000000..cbb324a8f3--- /dev/null+++ b/tests/unit/install/test_installer_update_contract.py@@ -0,0 +1,128 @@+"""Installer contracts reused by the post-exit in-app updater."""++from __future__ import annotations++import importlib.util+import json+import os+import stat+from pathlib import Path+from types import SimpleNamespace++import pytest++REPO = Path(__file__).resolve().parents[3]+_SPEC = importlib.util.spec_from_file_location(+ "installer_update_contract", REPO / "install" / "installer.py"+)+assert _SPEC is not None and _SPEC.loader is not None+installer = importlib.util.module_from_spec(_SPEC)+_SPEC.loader.exec_module(installer)+++ ("with_desktop", "profile"),+ ((True, "full"), (False, "headless")),+)+def test_managed_marker_persists_install_profile(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ with_desktop: bool,+ profile: str,+) -> None:+ monkeypatch.setattr(installer, "repo_root", lambda: tmp_path)+ installer.write_managed_marker(with_desktop=with_desktop)++ payload = json.loads(+ (tmp_path / ".jarvis-managed-install").read_text(encoding="utf-8")+ )+ assert payload["profile"] == profile+ assert payload["desktop"] is with_desktop+++def test_desktop_dependency_plan_is_complete_and_verified(capsys) -> None:+ installer.step_pip_install(+ with_desktop=True,+ with_voice_local=False,+ dry_run=True,+ )+ output = capsys.readouterr().out+ assert "--require-hashes" in output+ assert ".[full]" in output+ assert "dependency consistency check" in output+++def test_metadata_repair_removes_only_incomplete_records(tmp_path: Path) -> None:+ valid = tmp_path / "example-1.0.dist-info"+ valid.mkdir()+ (valid / "METADATA").write_text(+ "Metadata-Version: 2.4\nName: example\nVersion: 1.0\n",+ encoding="utf-8",+ )+ broken = tmp_path / "old_update-0.9.dist-info"+ broken.mkdir()+ (broken / "RECORD").write_text("", encoding="utf-8")+ licenses = broken / "licenses"+ licenses.mkdir()+ os.chmod(licenses, stat.S_IREAD)+ os.chmod(broken, stat.S_IREAD)++ assert installer.repair_distribution_metadata(site_packages=tmp_path) is True+ assert valid.is_dir()+ assert not broken.exists()+++def test_metadata_repair_dry_run_does_not_remove_records(tmp_path: Path) -> None:+ broken = tmp_path / "old_update-0.9.dist-info"+ broken.mkdir()++ assert installer.repair_distribution_metadata(+ site_packages=tmp_path, dry_run=True+ ) is True+ assert broken.is_dir()+++def test_ui_bundle_check_rejects_missing_javascript(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ dist = tmp_path / "jarvis" / "ui" / "web" / "dist"+ dist.mkdir(parents=True)+ (dist / "index.html").write_text("<html></html>\n", encoding="utf-8")+ monkeypatch.setattr(installer, "repo_root", lambda: tmp_path)++ assert installer.step_ui_bundle_check() is False+++def test_ui_bundle_check_accepts_complete_entry_set(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ dist = tmp_path / "jarvis" / "ui" / "web" / "dist"+ assets = dist / "assets"+ assets.mkdir(parents=True)+ (dist / "index.html").write_text(+ '<script type="module" src="/assets/app.js"></script>'+ '<link rel="stylesheet" href="/assets/app.css">',+ encoding="utf-8",+ )+ (assets / "app.js").write_text("export {};\n", encoding="utf-8")+ (assets / "app.css").write_text("body {}\n", encoding="utf-8")+ monkeypatch.setattr(installer, "repo_root", lambda: tmp_path)++ assert installer.step_ui_bundle_check() is True+++def test_desktop_registration_failure_is_install_failure(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ monkeypatch.setattr(installer, "repo_root", lambda: tmp_path)+ monkeypatch.setattr(installer, "venv_python", lambda: tmp_path / "python")+ monkeypatch.setattr(+ installer.subprocess,+ "run",+ lambda *args, **kwargs: SimpleNamespace(+ returncode=1,+ stdout='{"ok": false, "attempted": true}',+ ),+ )++ assert installer.step_desktop_integration(enabled=True, dry_run=False) is Falsediff --git a/tests/unit/ui/test_relauncher.py b/tests/unit/ui/test_relauncher.pyindex 2b59a5b286..81eef96bfc 100644--- a/tests/unit/ui/test_relauncher.py+++ b/tests/unit/ui/test_relauncher.py@@ -12,7 +12,8 @@ from types import SimpleNamespacefrom jarvis.ui import relauncher-def test_build_launch_command():+def test_build_launch_command(monkeypatch):+ monkeypatch.setattr(relauncher.sys, "platform", "linux")assert relauncher.build_launch_command("py.exe") == ["py.exe","-m",@@ -20,6 +21,41 @@ def test_build_launch_command():]+def test_build_launch_command_uses_macos_bundle(monkeypatch, tmp_path):+ import jarvis.setup.macos_app_bundle as bundle_module++ bundle = tmp_path / "Personal Jarvis.app"+ monkeypatch.setattr(relauncher.sys, "platform", "darwin")+ monkeypatch.setattr(bundle_module, "macos_app_bundle_path", lambda: bundle)+ monkeypatch.setattr(+ bundle_module, "macos_app_bundle_is_launchable", lambda _bundle: True+ )++ assert relauncher.build_launch_command("python3") == [+ "/usr/bin/open",+ "-W",+ "-a",+ str(bundle),+ ]+++def test_build_launch_command_fails_closed_without_macos_bundle(monkeypatch, tmp_path):+ import jarvis.setup.macos_app_bundle as bundle_module++ monkeypatch.setattr(relauncher.sys, "platform", "darwin")+ monkeypatch.setattr(+ bundle_module,+ "macos_app_bundle_path",+ lambda: tmp_path / "missing.app",+ )+ assert relauncher.build_launch_command("python3") == [+ "/usr/bin/open",+ "-W",+ "-a",+ str(tmp_path / "missing.app"),+ ]++def test_wait_returns_true_once_pid_gone():# alive for the first 2 polls, gone on the 3rd.calls = {"n": 0}diff --git a/tests/unit/ui/test_relauncher_update_transaction.py b/tests/unit/ui/test_relauncher_update_transaction.pynew file mode 100644index 0000000000..189c710f22--- /dev/null+++ b/tests/unit/ui/test_relauncher_update_transaction.py@@ -0,0 +1,177 @@+"""Post-exit update transaction coverage for the detached relauncher."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.ui import relauncher+++def _write_pending(root: Path) -> tuple[str, str]:+ previous = "a" * 40+ target = "b" * 40+ (root / relauncher.PENDING_UPDATE_FILENAME).write_text(+ json.dumps(+ {+ "schema": 1,+ "previous_revision": previous,+ "target_revision": target,+ "profile": "full",+ }+ )+ + "\n",+ encoding="utf-8",+ )+ return previous, target+++def _managed_root(root: Path) -> tuple[str, str]:+ (root / ".git").mkdir()+ (root / relauncher.MANAGED_MARKER).write_text("{}\n", encoding="utf-8")+ return _write_pending(root)+++def test_pending_manifest_validation_is_fail_closed(tmp_path: Path) -> None:+ path = tmp_path / relauncher.PENDING_UPDATE_FILENAME+ path.write_text('{"schema": 1, "target_revision": "main"}\n', encoding="utf-8")+ assert relauncher._read_pending_update(tmp_path) is None++ previous, target = _write_pending(tmp_path)+ payload = relauncher._read_pending_update(tmp_path)+ assert payload is not None+ assert payload["previous_revision"] == previous+ assert payload["target_revision"] == target+++ ("profile", "flag"),+ (("full", "--with-desktop"), ("headless", "--headless")),+)+def test_installer_command_preserves_managed_profile(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ profile: str,+ flag: str,+) -> None:+ monkeypatch.setattr(relauncher, "_managed_python", lambda _root: "python")+ command = relauncher._installer_command(tmp_path, profile)+ assert command[-1] == flag+ assert "--no-launch" in command+++def test_ui_bundle_requires_a_tracked_javascript_entry(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ dist = tmp_path / "jarvis" / "ui" / "web" / "dist"+ assets = dist / "assets"+ assets.mkdir(parents=True)+ (dist / "index.html").write_text(+ '<script type="module" src="/assets/app.js"></script>'+ '<link rel="stylesheet" href="/assets/app.css">',+ encoding="utf-8",+ )+ (assets / "app.js").write_text("export {};\n", encoding="utf-8")+ (assets / "app.css").write_text("body {}\n", encoding="utf-8")+ tracked: list[list[str]] = []++ def _tracked(cmd, *, root, timeout):+ tracked.append(cmd)+ return 0++ monkeypatch.setattr(relauncher, "_run_update_command", _tracked)+ assert relauncher._ui_bundle_ready(tmp_path) is True+ assert len(tracked) == 3++ (assets / "app.js").unlink()+ assert relauncher._ui_bundle_ready(tmp_path) is False+++def test_successful_update_runs_full_installer_after_target_reset(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ previous, target = _managed_root(tmp_path)+ calls: list[list[str]] = []++ def _run(cmd, *, root, timeout):+ calls.append(cmd)+ return 0++ monkeypatch.setattr(relauncher, "_run_update_command", _run)+ monkeypatch.setattr(relauncher, "_ui_bundle_ready", lambda _root: True)+ monkeypatch.setattr(+ relauncher,+ "_installer_command",+ lambda _root, profile: ["installer", profile],+ )++ assert relauncher.finalize_pending_update(tmp_path) is True+ assert calls == [+ ["git", "reset", "--hard", target],+ ["installer", "full"],+ ]+ assert not (tmp_path / relauncher.PENDING_UPDATE_FILENAME).exists()+ result = json.loads(+ (tmp_path / relauncher.UPDATE_RESULT_FILENAME).read_text(encoding="utf-8")+ )+ assert result["ok"] is True+ assert result["rolled_back"] is False+ assert result["previous_revision"] == previous+++def test_failed_target_install_rolls_back_and_repairs_previous_environment(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ previous, target = _managed_root(tmp_path)+ calls: list[list[str]] = []++ def _run(cmd, *, root, timeout):+ calls.append(cmd)+ if cmd == ["installer", "full"] and calls.count(cmd) == 1:+ return 1+ return 0++ monkeypatch.setattr(relauncher, "_run_update_command", _run)+ monkeypatch.setattr(relauncher, "_ui_bundle_ready", lambda _root: True)+ monkeypatch.setattr(+ relauncher,+ "_installer_command",+ lambda _root, profile: ["installer", profile],+ )++ assert relauncher.finalize_pending_update(tmp_path) is False+ assert calls == [+ ["git", "reset", "--hard", target],+ ["installer", "full"],+ ["git", "reset", "--hard", previous],+ ["installer", "full"],+ ]+ result = json.loads(+ (tmp_path / relauncher.UPDATE_RESULT_FILENAME).read_text(encoding="utf-8")+ )+ assert result["ok"] is False+ assert result["rolled_back"] is True+++def test_relauncher_finalizes_before_spawning_new_app(tmp_path: Path) -> None:+ order: list[str] = []++ def _spawn(_cmd, **_kwargs):+ order.append("spawn")+ return SimpleNamespace(pid=99)++ rc = relauncher.main(+ ["42", str(tmp_path)],+ _wait=lambda _pid, **_kwargs: True,+ _spawn=_spawn,+ _sleep=lambda _seconds: None,+ _alive=lambda pid: pid == 42,+ _settled=lambda *_args, **_kwargs: True,+ _finalize_update=lambda _cwd: order.append("finalize") or True,+ )++ assert rc == 0+ assert order == ["finalize", "spawn"]diff --git a/tests/unit/ui/web/test_update_routes.py b/tests/unit/ui/web/test_update_routes.pyindex 309125fc41..bcd4da4209 100644--- a/tests/unit/ui/web/test_update_routes.py+++ b/tests/unit/ui/web/test_update_routes.py@@ -6,7 +6,7 @@ fail-closed on an unknown running version, and the network check is fail-open."""from __future__ import annotations-import asyncio+import jsonfrom pathlib import Pathimport pytest@@ -16,20 +16,13 @@ from fastapi.testclient import TestClientimport jarvis.ui.web.update_routes as ufrom jarvis.ui.web.update_routes import router as update_router-_REAL_REFRESH_DESKTOP_INTEGRATION = u._refresh_desktop_integration-@pytest.fixture(autouse=True)-def _reset_cache(monkeypatch: pytest.MonkeyPatch) -> None:+def _reset_cache() -> None:# The status cache is module-global; clear it so each test sees a fresh check.u._status_cache = Noneu._status_cache_until = 0.0- async def _desktop_ok(_root: Path) -> tuple[bool, str]:- return True, ""-- monkeypatch.setattr(u, "_refresh_desktop_integration", _desktop_ok)-@pytest.fixturedef client() -> TestClient:@@ -69,6 +62,12 @@ def test_is_newer_fail_closed_on_unknown() -> None:assert not u._is_newer("", "1.0.1")+def test_versions_equal_is_normalized_and_fail_closed() -> None:+ assert u._versions_equal("1.0.2", "1.0.2")+ assert u._versions_equal("1.0.2", "1.0.2+build.1") is False+ assert not u._versions_equal("invalid", "invalid")++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")@@ -160,110 +159,168 @@ def test_apply_happy_path_pulls_and_signals_restart(client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:_patch_managed(monkeypatch, tmp_path)+ (tmp_path / ".jarvis-managed-install").write_text(+ '{"profile": "full"}\n', encoding="utf-8"+ )+ sentinel = tmp_path / "running-checkout.txt"+ sentinel.write_text("old", encoding="utf-8")calls: list[list[str]] = []+ monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")+ _patch_latest(+ monkeypatch,+ {+ "version": "1.0.2",+ "tag": "v1.0.2",+ "notes": "",+ "published_at": None,+ "release_url": None,+ },+ )async def _fake_git(args, *, cwd, timeout_s=60.0):calls.append(args)return 0, "", ""+ async def _fake_git_output(args, *, cwd, timeout_s=15.0):+ calls.append(args)+ if args == ["rev-parse", "HEAD"]:+ return "a" * 40+ if args == ["rev-parse", "FETCH_HEAD^{commit}"]:+ return "b" * 40+ if args == ["show", f"{'b' * 40}:jarvis/__init__.py"]:+ return '__version__ = "1.0.2"'+ return None+monkeypatch.setattr(u, "_git", _fake_git)- monkeypatch.setattr(u, "_version_on_disk", lambda root: "1.0.2")+ monkeypatch.setattr(u, "_git_output", _fake_git_output)body = client.post("/api/update/apply").json()assert body["ok"] is True+ assert body["prepared"] is Trueassert body["restart_required"] is Trueassert body["version"] == "1.0.2"- assert body["desktop_integration_ok"] is True+ assert body["release_tag"] == "v1.0.2"+ assert body["deps_pending"] is True+ assert body["ui_bundle_pending"] is True+ assert body["desktop_integration_pending"] is True+ assert body["desktop_integration_ok"] is Noneassert body["desktop_integration_warning"] is None- assert ["fetch", "--depth", "1", "origin", "main"] in calls- assert ["reset", "--hard", "origin/main"] in calls+ assert [+ "fetch",+ "--depth",+ "1",+ "origin",+ "refs/tags/v1.0.2",+ ] in calls+ assert not any(call[:2] == ["reset", "--hard"] for call in calls)+ assert sentinel.read_text(encoding="utf-8") == "old"++ pending = json.loads(+ (tmp_path / u._PENDING_UPDATE_NAME).read_text(encoding="utf-8")+ )+ assert pending["previous_revision"] == "a" * 40+ assert pending["target_revision"] == "b" * 40+ assert pending["profile"] == "full"def test_apply_git_fetch_failure_is_502(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", "tag": "v1.0.2"})async def _fake_git(args, *, cwd, timeout_s=60.0):return 1, "", "network down"+ async def _fake_git_output(args, *, cwd, timeout_s=15.0):+ return "a" * 40+monkeypatch.setattr(u, "_git", _fake_git)+ monkeypatch.setattr(u, "_git_output", _fake_git_output)assert client.post("/api/update/apply").status_code == 502-def test_apply_refreshes_deps_only_when_lockfile_changes(+def test_apply_preserves_headless_profile_for_deferred_installer(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))+ (tmp_path / ".jarvis-managed-install").write_text(+ '{"profile": "headless"}\n', encoding="utf-8"+ )+ monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")+ _patch_latest(monkeypatch, {"version": "1.0.2", "tag": "v1.0.2"})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_git_output(args, *, cwd, timeout_s=15.0):+ if args == ["rev-parse", "HEAD"]:+ return "1" * 40+ if args == ["rev-parse", "FETCH_HEAD^{commit}"]:+ return "2" * 40+ if args == ["show", f"{'2' * 40}:jarvis/__init__.py"]:+ return '__version__ = "1.0.2"'+ return None- async def _fake_refresh(root):- refreshed["called"] = True- return True, ""-- monkeypatch.setattr(u, "_refresh_dependencies", _fake_refresh)+ monkeypatch.setattr(u, "_git", _fake_git)+ monkeypatch.setattr(u, "_git_output", _fake_git_output)body = client.post("/api/update/apply").json()- assert body["deps_refreshed"] is True- assert refreshed.get("called") is True+ assert body["install_profile"] == "headless"+ assert body["desktop_integration_pending"] is False+ pending = json.loads(+ (tmp_path / u._PENDING_UPDATE_NAME).read_text(encoding="utf-8")+ )+ assert pending["profile"] == "headless"-def test_apply_reports_desktop_registration_failure_without_rolling_back_code(+def test_apply_refuses_when_no_new_release(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", "tag": "v1.0.2"})- async def _fake_git(args, *, cwd, timeout_s=60.0):- return 0, "", ""+ response = client.post("/api/update/apply")- async def _desktop_failed(_root: Path) -> tuple[bool, str]:- return False, "could not register the app launcher"+ assert response.status_code == 409+ assert not (tmp_path / u._PENDING_UPDATE_NAME).exists()- monkeypatch.setattr(u, "_git", _fake_git)- monkeypatch.setattr(u, "_version_on_disk", lambda root: "1.0.2")- monkeypatch.setattr(u, "_refresh_desktop_integration", _desktop_failed)- body = client.post("/api/update/apply").json()+def test_pending_update_write_replaces_old_result(tmp_path: Path) -> None:+ result = tmp_path / u._UPDATE_RESULT_NAME+ result.write_text('{"ok": false}\n', encoding="utf-8")- assert body["ok"] is True- assert body["desktop_integration_ok"] is False- assert body["desktop_integration_warning"] == "could not register the app launcher"+ u._write_pending_update(+ tmp_path,+ previous_revision="a" * 40,+ target_revision="b" * 40,+ profile="full",+ )++ assert not result.exists()+ assert not (tmp_path / f"{u._PENDING_UPDATE_NAME}.tmp").exists()+ payload = json.loads(+ (tmp_path / u._PENDING_UPDATE_NAME).read_text(encoding="utf-8")+ )+ assert payload["schema"] == 1-def test_desktop_refresh_imports_the_new_checkout_in_a_subprocess(+def test_legacy_marker_falls_back_to_desktop_profile(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:- calls: list[list[str]] = []-- async def _fake_run(cmd, *, cwd, timeout_s):- calls.append(cmd)- return 0, '{"ok": true, "attempted": false}', ""-- monkeypatch.setattr(u, "_run", _fake_run)+ (tmp_path / ".jarvis-managed-install").write_text("{}\n", encoding="utf-8")+ monkeypatch.setattr(u.sys, "platform", "win32")+ assert u._managed_install_profile(tmp_path) == "full"- result = asyncio.run(_REAL_REFRESH_DESKTOP_INTEGRATION(tmp_path))- assert result == (True, "")- assert calls[0][1:3] == ["-m", "jarvis.setup.desktop_integration"]---def test_desktop_refresh_reports_an_unreadable_subprocess_result(+def test_legacy_linux_marker_distinguishes_desktop_from_headless(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:- async def _fake_run(cmd, *, cwd, timeout_s):- return 0, "not-json", ""-- monkeypatch.setattr(u, "_run", _fake_run)-- ok, warning = asyncio.run(_REAL_REFRESH_DESKTOP_INTEGRATION(tmp_path))-- assert ok is False- assert "unreadable" in warning+ (tmp_path / ".jarvis-managed-install").write_text("{}\n", encoding="utf-8")+ monkeypatch.setattr(u.sys, "platform", "linux")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)+ assert u._managed_install_profile(tmp_path) == "headless"++ monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")+ assert u._managed_install_profile(tmp_path) == "full"