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(update): self-update a frozen installer from the GitHub Release
rubenluetke10-beep5119be482a3e
diff --git a/docs/desktop-installers.md b/docs/desktop-installers.mdnew file mode 100644index 0000000000..8fb711a9c5--- /dev/null+++ b/docs/desktop-installers.md@@ -0,0 +1,276 @@+# Desktop installers++How Personal Jarvis becomes a one-click download, how each installer is built+and signed, and how an installed copy keeps itself up to date.++This is the maintainer's page. A user never reads it: they press one button on+the website, run a normal install wizard, and the app updates itself afterwards.++---++## 1. What a release publishes++Every `v*.*.*` tag produces these assets on the GitHub Release. The names are a+contract - the website's download button and the in-app updater both resolve+`https://github.com/PersonalJarvis/PersonalJarvis/releases/latest/download/<name>`:++| Asset | Platform |+| -------------------------------------- | ----------------------------------------- |+| `PersonalJarvis-Setup-x64.exe` | Windows 10/11 x64, per-user Inno Setup |+| `PersonalJarvis-macOS-arm64.dmg` | Apple Silicon |+| `PersonalJarvis-macOS-x64.dmg` | Intel Mac |+| `PersonalJarvis-Linux-x86_64.AppImage` | Linux x86_64 |+| `installers-SHA256SUMS.txt` | what the updater verifies every download against |++The terminal one-liner and `pipx install personal-jarvis` stay supported. They+produce a *managed* or *dev* install, which updates through git - see+[section 6](#6-how-an-installed-copy-updates-itself).++---++## 2. The frozen bundle++Everything starts from one PyInstaller build:++```bash+pyinstaller jarvis.spec --noconfirm --clean+```++`onedir`, not `onefile`: no 3-5 second extraction on every launch, and each DLL+can be signed on its own.++It produces **two executables that share one payload**:++| Binary | Console? | What it is |+| ------------------------- | -------- | ---------------------------------------------------------------- |+| `PersonalJarvis` (`.exe`) | no | the windowed app - Start Menu, Dock, `.desktop` |+| `jarvis` (`.exe`) | yes | the CLI: `jarvis serve`, `jarvis --version`, `jarvis missions list` |++Both run `jarvis/__main__.py`, so the CLI from a native install behaves exactly+like the pip console script.++> **Why the GUI binary is not called `Jarvis`.** `Jarvis` and `jarvis` are the+> same path on Windows (NTFS) and on a default macOS APFS volume, so one would+> silently overwrite the other. `PersonalJarvis` is the name+> `jarvis.core.branding` already uses for the Windows branded launcher and the+> macOS bundle executable.++Layout:++- Windows / Linux: `dist/Jarvis/` with both binaries plus `_internal/`+- macOS: `dist/Personal Jarvis.app`, CLI at `Contents/MacOS/jarvis`++### Where a frozen install keeps user data++`packaging/pyinstaller_rthook_frozen.py` runs before anything imports `jarvis`+and points the two documented overrides at the per-user application directory:++- `JARVIS_CONFIG` -> `%LOCALAPPDATA%\Jarvis\jarvis.toml` (`~/.jarvis/jarvis.toml`+ off Windows), seeded once from the copy inside the bundle+- `JARVIS_DATA_DIR` -> `<that directory>/data`++Without it, `jarvis.core.config` would anchor both to the bundle's own+directory, where an in-place upgrade overwrites the user's settings and an+uninstall deletes their memory. An explicitly exported `JARVIS_CONFIG` /+`JARVIS_DATA_DIR` still wins, so a maintainer can point a frozen build at a+scratch directory.++---++## 3. Building each installer++All three scripts do the same three things: build the frontend if+`jarvis/ui/web/dist` is missing, run PyInstaller, package the result into+`dist/installers/`. Each prints the artifact path and exits non-zero on failure.++### Windows++```powershell+pwsh packaging/windows/build.ps1+# -> dist/installers/PersonalJarvis-Setup-x64.exe+```++Needs Node 22+, Python 3.12 with `pip install -e ".[desktop,dev]"`, and Inno+Setup 6 (`winget install --id JRSoftware.InnoSetup -e`). The script finds+`ISCC.exe` on `PATH`, under `Program Files (x86)`, or in+`%LOCALAPPDATA%\Programs\Inno Setup 6`.++Two flags shorten the loop: `-SkipPyInstaller` repackages the existing+`dist/Jarvis` (seconds instead of ~12 minutes) and `-SkipFrontend` refuses to+run npm.++The wizard itself is `packaging/windows/PersonalJarvis.iss`:++- **per-user** (`PrivilegesRequired=lowest`, `{localappdata}\Programs\Personal+ Jarvis`) - no administrator prompt, exactly like Chrome. This is also what+ lets the in-app updater run the upgrade unattended.+- a **fixed `AppId` GUID** so every future setup upgrades in place instead of+ adding a second entry to "Installed apps"+- Start Menu shortcut; optional desktop shortcut (off by default)+- optional **"Add the `jarvis` command to PATH"** (on by default). Implemented+ in `[Code]` against `HKCU\Environment` and broadcast with `WM_SETTINGCHANGE`,+ so a newly opened terminal sees it without a sign-out. Adding is idempotent,+ and clearing the task on an upgrade removes the entry again.+- `CloseApplications=yes` so Restart Manager closes a running Personal Jarvis+ instead of failing on locked files+- LZMA2/max, `x64compatible` only, `MinVersion=10.0`++### macOS++```bash+./packaging/macos/build.sh+# -> dist/installers/PersonalJarvis-macOS-<arm64|x64>.dmg+```++Owned by `packaging/macos/`. It reads `APPLE_SIGNING_IDENTITY`, `APPLE_ID`,+`APPLE_TEAM_ID` and `APPLE_APP_SPECIFIC_PASSWORD`; with none of them set it+ad-hoc signs, skips notarization and prints a one-line notice. The `.app`'s+identity (bundle id, minimum system version, and the microphone / speech /+camera / Apple-Events usage strings macOS requires before it will let the+process touch those APIs) comes from the `BUNDLE` block in `jarvis.spec`.++### Linux++```bash+./packaging/linux/build.sh+# -> dist/installers/PersonalJarvis-Linux-x86_64.AppImage+```++Owned by `packaging/linux/`. Built on the oldest supported runner+(`ubuntu-22.04`) because an AppImage inherits the glibc of the machine that+built it.++---++## 4. Signing++Signing is optional everywhere. Without secrets the build still produces a+working installer and says, in one line, that it is unsigned.++| Platform | Mechanism | Secrets |+| -------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------- |+| Windows | Azure Trusted Signing | `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_SIGNING_ENDPOINT`, `AZURE_CODE_SIGNING_ACCOUNT`, `AZURE_CERTIFICATE_PROFILE` |+| macOS | Developer ID + notarization | `APPLE_SIGNING_IDENTITY`, `APPLE_ID`, `APPLE_TEAM_ID`, `APPLE_APP_SPECIFIC_PASSWORD` |+| Linux | none (AppImage is unsigned) | - |++Private key material only ever exists as a GitHub Actions secret (AP-29); no+signing step ever reads a file from the repository.++On Windows the workflow signs the **setup executable**. That is the file the+browser marks with Mark-of-the-Web, so it is the signature SmartScreen weighs;+files the installer then writes carry no MOTW of their own. Signing the inner+binaries as well (run PyInstaller, sign `dist/Jarvis`, then+`build.ps1 -SkipPyInstaller`) mainly helps against antivirus false positives on+PyInstaller bootloaders, and can be added the same way.++---++## 5. Releasing++`.github/workflows/desktop-installers.yml` runs on a `v*.*.*` tag push (or+manually via `workflow_dispatch`):++1. `windows`, `macos` (arm64 + x64) and `linux` each install Python 3.12 and+ Node 22, `pip install -e ".[desktop,dev]"`, run their OS build script and+ upload the artifact.+2. `release` downloads all of them, refuses to continue if any promised asset is+ missing, verifies the tag equals `jarvis.__version__`, writes+ `installers-SHA256SUMS.txt` (plain `sha256sum` format, flat file names),+ re-verifies it with `sha256sum -c`, and attaches everything to the Release.++`contents: write` is granted to that last job only.++The version check matters twice over: a tag that disagrees with+`jarvis.__version__` publishes installers nobody can trace back to a commit, and+the updater compares the release version against `jarvis.__version__` - so a+mismatch would offer an update that installs the same build forever.++---++## 6. How an installed copy updates itself++`GET /api/update/status` and `POST /api/update/apply` serve all install kinds+behind one "Update Now" button. `jarvis.core.frozen.is_frozen()` is the only+switch between them.++| Kind | Detected by | Update path |+| ----------- | ------------------------------------ | ---------------------------------------------- |+| **frozen** | `sys.frozen` + `sys._MEIPASS` | download the next installer asset, verify, install |+| **managed** | install marker + official `origin` | `git fetch` the published tag, reinstall |+| **dev** | anything else | never updates |++For a frozen install (`jarvis/core/installer_update.py`):++1. **Pick the asset.** OS plus CPU architecture map to exactly one name from the+ table in section 1. No mapping (Windows on ARM, Linux on aarch64) means the+ button never appears.+2. **Refuse to offer what cannot be installed.** `status` reports+ `update_available: true` only when the release actually carries both this+ platform's installer and `installers-SHA256SUMS.txt`. Status is fail-open:+ any network error reports "no update", never an error.+3. **Verify before executing.** `apply` downloads to a temp directory under a+ size cap, computes SHA-256 and compares it against the manifest **of the same+ release**. A mismatch, a missing entry, an oversized body or an unreachable+ manifest all delete the download and refuse. Apply is fail-closed.+4. **Hand over to the platform.**+ - Windows: runs the new `Setup.exe` detached with+ `/SILENT /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS /NORESTART`. Restart+ Manager closes the app, the files are replaced, the app comes back.+ - macOS: `hdiutil attach` the DMG, swap the running `.app` with two renames+ on one filesystem (the old bundle is put back if the second rename fails),+ `hdiutil detach`, relaunch with `open`.+ - Linux: copy the new AppImage next to the running one, `chmod +x`,+ `os.replace` onto `$APPIMAGE` (atomic), relaunch.++The response says `restart_required: false`, because the handover restarts the+app itself. A caller that restarts anyway is harmless - the single-instance lock+still holds - but the honest answer is "no restart needed from you".++Managed installs keep today's behaviour untouched: the frozen branch is entered+only when `is_frozen()` is true, and the frozen branch never runs git.++---++## 7. What an uninstall keeps++The Windows uninstaller removes the **program directory only**+(`%LOCALAPPDATA%\Programs\Personal Jarvis`) and its PATH entry, Start Menu+shortcut and uninstall registry key.++It deliberately keeps **`%LOCALAPPDATA%\Jarvis`** - `jarvis.toml`, memory,+skills, logs, the chat database. Uninstalling and reinstalling therefore returns+the user to their own configured app, not to a blank one. The uninstall+confirmation says so. To remove that too, delete the directory by hand or run+`jarvis --uninstall` before uninstalling.++API keys are not in that directory: they live in the OS credential store+(Windows Credential Manager / Keychain / Secret Service) and survive both.++---++## 8. Verifying a build by hand++```bash+# the CLI works from the bundle+dist/Jarvis/jarvis.exe --version++# the backend really boots (Ctrl-C to stop)+dist/Jarvis/jarvis.exe serve+curl http://127.0.0.1:<admin_api_port>/api/health++# a full install / upgrade / uninstall cycle, unattended+PersonalJarvis-Setup-x64.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /DIR="C:\pj-test" /LOG=install.log+C:\pj-test\jarvis.exe --version+PersonalJarvis-Setup-x64.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /DIR="C:\pj-test" # upgrade in place+C:\pj-test\unins000.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART+```++Use a **short** test directory. The deepest path in the bundle is about 111+characters; a real install prefix adds roughly 60, which fits inside Windows'+260-character limit with room to spare, but a deeply nested scratch directory+does not, and Inno then aborts with `MoveFile failed; code 3`.++Never run the app out of `dist/Jarvis` and then package that directory: the app+writes runtime state into it, which would ship the builder's own database inside+the installer. `build.ps1` removes such leftovers before packaging, and a clean+`--clean` build never has them.diff --git a/jarvis/core/installer_update.py b/jarvis/core/installer_update.pynew file mode 100644index 0000000000..1a5b77fddf--- /dev/null+++ b/jarvis/core/installer_update.py@@ -0,0 +1,728 @@+"""Self-update for a FROZEN install — the one that arrived as a native installer.++A frozen install (Windows ``Setup.exe``, macOS ``.dmg``, Linux ``.AppImage``)+has no git checkout, so ``jarvis/ui/web/update_routes.py``'s managed path cannot+update it. What it does have is a GitHub Release carrying exactly one installer+asset per platform plus a ``installers-SHA256SUMS.txt`` manifest:++* ``PersonalJarvis-Setup-x64.exe`` Windows 10/11 x64+* ``PersonalJarvis-macOS-arm64.dmg`` Apple Silicon+* ``PersonalJarvis-macOS-x64.dmg`` Intel Mac+* ``PersonalJarvis-Linux-x86_64.AppImage`` Linux x86_64++This module resolves which of those belongs to the running machine, downloads+it, proves it byte-for-byte against the checksum manifest of the SAME release,+and then hands control to the platform's own upgrade mechanism.++Two rules run through everything here:++* **Fail closed.** A missing asset, a missing or unparsable checksum manifest, a+ digest that does not match, an oversized body, an unexpected redirect target —+ every one of them raises :class:`InstallerUpdateError` and installs nothing.+ Executing an unverified binary is the single worst thing an updater can do.+* **Injectable edges.** Network and process spawning arrive as small protocols+ (:class:`AssetFetcher`, :class:`CommandRunner`), so the whole flow — including+ the macOS and Linux handovers — is exercised on any OS with fakes and without+ a network.++Every subprocess goes out with ``NO_WINDOW_CREATIONFLAGS`` (AP-1) so a windowed+build never flashes a console.+"""++from __future__ import annotations++import asyncio+import hashlib+import logging+import os+import platform as platform_module+import shutil+import subprocess+import sys+import tempfile+from collections.abc import Callable, Iterable, Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Protocol++from jarvis.core.branding import UPDATER_USER_AGENT+from jarvis.core.frozen import bundle_root, is_frozen+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++log = logging.getLogger(__name__)++__all__ = [+ "CHECKSUMS_ASSET_NAME",+ "AssetFetcher",+ "CommandRunner",+ "DownloadProgress",+ "InstallerAsset",+ "InstallerUpdateError",+ "SubprocessCommandRunner",+ "apply_installer",+ "download_and_verify",+ "installer_asset_name",+ "parse_sha256sums",+ "select_asset",+ "select_installer_asset",+]++# The checksum manifest published alongside the installers. Its lines are plain+# ``sha256sum`` output, so `sha256sum -c` verifies the same file by hand.+CHECKSUMS_ASSET_NAME = "installers-SHA256SUMS.txt"++# A whole onedir bundle compresses to a few hundred MB. The cap exists to stop a+# hostile or broken endpoint from filling the disk, not to be a tight budget.+MAX_INSTALLER_BYTES = 1_500_000_000+# The manifest is a handful of lines; anything larger is not the manifest.+MAX_CHECKSUMS_BYTES = 256_000++# Whole-download budget. Generous on purpose: a 400 MB installer over a slow+# connection is normal, a download that never ends is not.+DOWNLOAD_TIMEOUT_S = 1800.0+CONNECT_TIMEOUT_S = 15.0+READ_TIMEOUT_S = 120.0++_SHA256_LENGTH = 64+++class InstallerUpdateError(RuntimeError):+ """A frozen update could not be completed. The message is user-facing."""+++#: Called with ``(bytes_written, total_bytes_or_None)`` as the download streams.+#: ``total`` is the release asset's published size when the caller knows it and+#: the server confirms it, and ``None`` when it does not — a progress bar built+#: on this must therefore survive an unknown total rather than assume one.+#: Never raises into the download: :func:`_report` swallows a bad callback.+DownloadProgress = Callable[[int, int | None], None]+++def _report(on_progress: DownloadProgress | None, written: int, total: int | None) -> None:+ """Deliver one progress tick without ever endangering the download.++ A progress consumer is cosmetic; the download is not. A callback that raises+ (a UI store torn down mid-flight, a bad lambda) must not abort an otherwise+ healthy 400 MB transfer, so its exception is logged and dropped here.+ """+ if on_progress is None:+ return+ try:+ on_progress(written, total)+ except Exception: # noqa: BLE001 - a cosmetic callback never fails the update+ log.debug("[update] progress callback raised; continuing the download")+++@dataclass(frozen=True)+class InstallerAsset:+ """One downloadable file on a GitHub Release."""++ name: str+ url: str+ size: int++ def as_dict(self) -> dict[str, Any]:+ """The shape the update status route publishes to the UI."""+ return {"name": self.name, "url": self.url, "size": self.size}+++# --------------------------------------------------------------------------- #+# Asset selection+# --------------------------------------------------------------------------- #+def installer_asset_name(platform_name: str, machine: str) -> str | None:+ """The release asset this OS/CPU pair installs, or ``None`` when unsupported.++ ``machine`` is compared case-insensitively because the same CPU reports+ different spellings per OS: Windows says ``AMD64``, Linux says ``x86_64``,+ macOS says ``arm64`` while ``platform.machine()`` under Rosetta says+ ``x86_64``. An unrecognised pair returns ``None`` — the caller then reports+ "no installer for this platform" instead of guessing.+ """+ arch = machine.strip().lower()+ intel64 = {"x86_64", "amd64", "x64"}++ if platform_name == "win32":+ if arch in intel64:+ return "PersonalJarvis-Setup-x64.exe"+ return None+ if platform_name == "darwin":+ if arch in {"arm64", "aarch64"}:+ return "PersonalJarvis-macOS-arm64.dmg"+ if arch in intel64:+ return "PersonalJarvis-macOS-x64.dmg"+ return None+ if platform_name.startswith("linux"):+ if arch in intel64:+ return "PersonalJarvis-Linux-x86_64.AppImage"+ return None+ return None+++def select_asset(assets: Iterable[Any], name: str) -> InstallerAsset | None:+ """Find one asset by exact name in a GitHub Release ``assets`` array.++ Accepts the raw JSON list so callers do not have to pre-shape it. Entries+ that are not objects, or that lack a usable download URL, are skipped rather+ than crashing the status poll on a malformed release.+ """+ for entry in assets:+ if not isinstance(entry, dict):+ continue+ if str(entry.get("name") or "") != name:+ continue+ url = str(entry.get("browser_download_url") or "")+ if not url.startswith("https://"):+ # A non-HTTPS or missing URL is not something to "fix" by guessing.+ log.warning("[update] release asset %s has no usable https URL", name)+ return None+ try:+ size = int(entry.get("size") or 0)+ except (TypeError, ValueError):+ size = 0+ return InstallerAsset(name=name, url=url, size=size)+ return None+++def select_installer_asset(+ assets: Iterable[Any],+ *,+ platform_name: str | None = None,+ machine: str | None = None,+) -> InstallerAsset | None:+ """The installer asset for the running machine, or ``None``."""+ name = installer_asset_name(+ sys.platform if platform_name is None else platform_name,+ platform_module.machine() if machine is None else machine,+ )+ if name is None:+ return None+ return select_asset(assets, name)+++# --------------------------------------------------------------------------- #+# Checksum manifest+# --------------------------------------------------------------------------- #+def parse_sha256sums(text: str) -> dict[str, str]:+ """Parse ``sha256sum`` output into ``{file name: lowercase digest}``.++ Handles both the binary (``digest *name``) and text (``digest name``)+ markers and ignores blank or malformed lines, because one bad line must not+ hide the digest of the file we actually need.+ """+ digests: dict[str, str] = {}+ for raw_line in text.splitlines():+ line = raw_line.strip()+ if not line or line.startswith("#"):+ continue+ parts = line.split(None, 1)+ if len(parts) != 2:+ continue+ digest, name = parts[0].strip().lower(), parts[1].strip()+ if len(digest) != _SHA256_LENGTH:+ continue+ try:+ int(digest, 16)+ except ValueError:+ continue+ if name.startswith("*"):+ name = name[1:]+ # Release manifests are flat, but a path-prefixed entry must still match+ # by file name rather than being dropped.+ name = name.replace("\\", "/").rsplit("/", 1)[-1]+ if name:+ digests[name] = digest+ return digests+++# --------------------------------------------------------------------------- #+# Network edge+# --------------------------------------------------------------------------- #+def _content_length(raw: str | None) -> int | None:+ """The response's byte total, or ``None`` when the server did not state one."""+ try:+ total = int(str(raw))+ except (TypeError, ValueError):+ # Absent or malformed: the caller falls back to the release metadata,+ # and failing that shows an indeterminate bar. Not an error.+ return None+ return total if total > 0 else None+++class AssetFetcher(Protocol):+ """The only network this module performs. Faked wholesale in tests."""++ async def get_text(self, url: str, *, max_bytes: int) -> str:+ """Fetch a small text body (the checksum manifest)."""++ async def download(+ self,+ url: str,+ dest: Path,+ *,+ max_bytes: int,+ on_progress: DownloadProgress | None = None,+ ) -> int:+ """Stream ``url`` into ``dest``; return the byte count written.++ ``on_progress`` is called as the bytes arrive so a caller can show a+ real percentage. It is optional in the protocol so an implementation+ that cannot report progress stays valid.+ """+++class HttpxAssetFetcher:+ """Default :class:`AssetFetcher` on top of httpx.++ ``httpx`` is imported lazily: the base install must boot on a host where the+ updater never runs, and this module sits on an import path the desktop app+ touches at startup (AP-26).+ """++ async def get_text(self, url: str, *, max_bytes: int) -> str:+ import httpx++ async with httpx.AsyncClient(+ timeout=httpx.Timeout(READ_TIMEOUT_S, connect=CONNECT_TIMEOUT_S),+ follow_redirects=True,+ ) as client:+ response = await client.get(url, headers=self._headers())+ response.raise_for_status()+ body = response.content+ if len(body) > max_bytes:+ raise InstallerUpdateError(+ f"checksum manifest is larger than {max_bytes} bytes — refusing it"+ )+ return body.decode("utf-8", errors="replace")++ async def download(+ self,+ url: str,+ dest: Path,+ *,+ max_bytes: int,+ on_progress: DownloadProgress | None = None,+ ) -> int:+ import httpx++ written = 0+ async with httpx.AsyncClient(+ timeout=httpx.Timeout(READ_TIMEOUT_S, connect=CONNECT_TIMEOUT_S),+ follow_redirects=True,+ ) as client:+ async with client.stream("GET", url, headers=self._headers()) as response:+ response.raise_for_status()+ # A GitHub asset redirect always answers with a Content-Length,+ # but a proxy or a chunked transfer need not: an unparsable or+ # absent header means "total unknown", never a guessed size.+ total = _content_length(response.headers.get("content-length"))+ _report(on_progress, 0, total)+ with dest.open("wb") as handle:+ async for chunk in response.aiter_bytes(1024 * 256):+ written += len(chunk)+ if written > max_bytes:+ raise InstallerUpdateError(+ f"installer download exceeded {max_bytes} bytes — refusing it"+ )+ handle.write(chunk)+ _report(on_progress, written, total)+ return written++ @staticmethod+ def _headers() -> dict[str, str]:+ return {"User-Agent": UPDATER_USER_AGENT, "Accept": "application/octet-stream"}+++async def download_and_verify(+ asset: InstallerAsset,+ checksums: InstallerAsset,+ *,+ dest_dir: Path,+ fetcher: AssetFetcher | None = None,+ max_bytes: int = MAX_INSTALLER_BYTES,+ on_progress: DownloadProgress | None = None,+) -> Path:+ """Download ``asset`` and prove it against ``checksums``. Fail closed.++ ``checksums`` must come from the SAME release as ``asset`` — verifying+ against another release's manifest would authorise the wrong bytes. The+ caller (``update_routes``) reads both out of one release payload.++ ``on_progress`` receives ``(written, total)`` while the installer streams in.+ ``total`` falls back to the release metadata's ``asset.size`` when the server+ states no Content-Length, and stays ``None`` when neither source knows it.++ Returns the path of the verified file inside ``dest_dir``. Raises+ :class:`InstallerUpdateError` on every failure, leaving nothing executable+ behind.+ """+ active = HttpxAssetFetcher() if fetcher is None else fetcher++ def tick(written: int, total: int | None) -> None:+ _report(on_progress, written, total or (asset.size or None))++ if asset.size and asset.size > max_bytes:+ raise InstallerUpdateError(+ f"{asset.name} is {asset.size} bytes, over the {max_bytes} byte cap"+ )++ try:+ manifest_text = await active.get_text(checksums.url, max_bytes=MAX_CHECKSUMS_BYTES)+ except InstallerUpdateError:+ raise+ except Exception as exc: # noqa: BLE001 — every transport error is the same refusal+ raise InstallerUpdateError(f"could not download {CHECKSUMS_ASSET_NAME}: {exc}") from exc++ digests = parse_sha256sums(manifest_text)+ expected = digests.get(asset.name)+ if not expected:+ raise InstallerUpdateError(+ f"{CHECKSUMS_ASSET_NAME} of this release has no entry for {asset.name} — "+ "refusing to install an unverified file"+ )++ target = _prepare_target(dest_dir, asset.name)+ try:+ written = await active.download(asset.url, target, max_bytes=max_bytes, on_progress=tick)+ except InstallerUpdateError:+ _discard(target)+ raise+ except Exception as exc: # noqa: BLE001 — same refusal for any transport error+ _discard(target)+ raise InstallerUpdateError(f"could not download {asset.name}: {exc}") from exc++ # Hashing several hundred MB takes seconds of pure CPU. On the event loop+ # that freezes every other request — including the progress poll this very+ # download is feeding — so it goes to a thread.+ actual = await asyncio.to_thread(_sha256_file, target)+ if actual != expected:+ _discard(target)+ raise InstallerUpdateError(+ f"{asset.name} failed its SHA-256 check (expected {expected}, got "+ f"{actual}) — the download was NOT installed"+ )++ log.info("[update] verified %s (%d bytes, sha256 %s)", asset.name, written, actual)+ return target+++def _prepare_target(dest_dir: Path, name: str) -> Path:+ """Create the download directory and return the file path inside it.++ Split out of the async caller so the blocking filesystem call does not sit+ on the event loop (ruff ASYNC240); it is a single mkdir, so a thread would+ cost more than it saves.+ """+ dest_dir.mkdir(parents=True, exist_ok=True)+ return dest_dir / name+++def _sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 256), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _discard(path: Path) -> None:+ """Remove a partial or rejected download so nothing unverified survives."""+ try:+ path.unlink(missing_ok=True)+ except OSError as exc:+ # Worth a line: a leftover rejected installer in the temp directory is+ # harmless on its own but confusing in a support log.+ log.warning("[update] could not remove %s: %s", path, exc)+++# --------------------------------------------------------------------------- #+# Process edge+# --------------------------------------------------------------------------- #+class CommandRunner(Protocol):+ """Spawning, isolated so the handovers are testable without side effects."""++ def run(self, command: Sequence[str], *, timeout_s: float) -> tuple[int, str, str]:+ """Run to completion; return ``(returncode, stdout, stderr)``."""++ def spawn_detached(self, command: Sequence[str]) -> None:+ """Start ``command`` and return immediately, outliving this process."""+++class SubprocessCommandRunner:+ """Default :class:`CommandRunner`. Every spawn is console-free (AP-1)."""++ def run(self, command: Sequence[str], *, timeout_s: float) -> tuple[int, str, str]:+ try:+ completed = subprocess.run( # noqa: S603 - fixed argv, no shell+ list(command),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=timeout_s,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except FileNotFoundError as exc:+ return -1, "", f"{command[0]} is not available: {exc}"+ except subprocess.TimeoutExpired:+ return -1, "", f"{command[0]} timed out after {timeout_s:.0f}s"+ return completed.returncode, completed.stdout or "", completed.stderr or ""++ def spawn_detached(self, command: Sequence[str]) -> None:+ kwargs: dict[str, Any] = {+ "stdin": subprocess.DEVNULL,+ "stdout": subprocess.DEVNULL,+ "stderr": subprocess.DEVNULL,+ "close_fds": True,+ }+ if sys.platform == "win32":+ detached = getattr(subprocess, "DETACHED_PROCESS", 0x00000008)+ new_group = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)+ kwargs["creationflags"] = NO_WINDOW_CREATIONFLAGS | detached | new_group+ else:+ # Leave the process group so the handover survives this app exiting.+ kwargs["start_new_session"] = True+ subprocess.Popen(list(command), **kwargs) # noqa: S603 - fixed argv, no shell+++# --------------------------------------------------------------------------- #+# Platform handovers+# --------------------------------------------------------------------------- #+def apply_installer(+ installer: Path,+ *,+ platform_name: str | None = None,+ runner: CommandRunner | None = None,+ app_path: Path | None = None,+ appimage_path: Path | None = None,+ relaunch: bool = True,+) -> str:+ """Install the verified ``installer`` and hand control to the new version.++ Returns a one-line, user-facing description of what was handed over. Raises+ :class:`InstallerUpdateError` when the platform is unsupported or the+ handover could not be completed — the running app then keeps working on the+ old version, which is always better than a half-replaced install.+ """+ active_platform = sys.platform if platform_name is None else platform_name+ active_runner = SubprocessCommandRunner() if runner is None else runner++ if not installer.is_file():+ raise InstallerUpdateError(f"{installer} does not exist")++ if active_platform == "win32":+ return _handover_windows(installer, runner=active_runner)+ if active_platform == "darwin":+ return _handover_macos(+ installer,+ runner=active_runner,+ app_path=app_path if app_path is not None else _running_macos_app(),+ relaunch=relaunch,+ )+ if active_platform.startswith("linux"):+ return _handover_linux(+ installer,+ runner=active_runner,+ appimage_path=(appimage_path if appimage_path is not None else _running_appimage()),+ relaunch=relaunch,+ )+ raise InstallerUpdateError(f"no installer handover exists for platform {active_platform!r}")+++def _handover_windows(installer: Path, *, runner: CommandRunner) -> str:+ """Start the Inno Setup wizard silently and let it replace the running app.++ ``/CLOSEAPPLICATIONS`` + ``/RESTARTAPPLICATIONS`` are what make this feel+ like Chrome: Restart Manager closes Personal Jarvis, the files are replaced,+ and the app comes back on its own. ``/NORESTART`` guarantees the machine is+ never rebooted behind the user's back.+ """+ command = [+ str(installer),+ "/SILENT",+ "/CLOSEAPPLICATIONS",+ "/RESTARTAPPLICATIONS",+ "/NORESTART",+ ]+ try:+ runner.spawn_detached(command)+ except OSError as exc:+ raise InstallerUpdateError(f"could not start {installer.name}: {exc}") from exc+ log.info("[update] handed over to %s", installer.name)+ return "the Windows installer is running; Personal Jarvis restarts by itself"+++def _handover_macos(+ dmg: Path,+ *,+ runner: CommandRunner,+ app_path: Path | None,+ relaunch: bool,+) -> str:+ """Mount the DMG, swap the running ``.app`` for the one inside, relaunch."""+ if app_path is None:+ raise InstallerUpdateError(+ "could not locate the running Personal Jarvis.app — refusing to update"+ )++ mountpoint = Path(tempfile.mkdtemp(prefix="jarvis-dmg-"))+ attached = False+ try:+ rc, _out, err = runner.run(+ [+ "hdiutil",+ "attach",+ str(dmg),+ "-nobrowse",+ "-readonly",+ "-mountpoint",+ str(mountpoint),+ ],+ timeout_s=180.0,+ )+ if rc != 0:+ raise InstallerUpdateError(+ f"could not mount {dmg.name}: {err.strip()[:200] or 'hdiutil failed'}"+ )+ attached = True++ source = mountpoint / app_path.name+ if not source.is_dir():+ candidates = [p for p in mountpoint.glob("*.app") if p.is_dir()]+ if len(candidates) != 1:+ raise InstallerUpdateError(+ f"{dmg.name} does not contain exactly one application bundle"+ )+ source = candidates[0]++ _replace_directory(source, app_path)+ finally:+ if attached:+ rc, _out, err = runner.run(+ ["hdiutil", "detach", str(mountpoint), "-force"], timeout_s=120.0+ )+ if rc != 0:+ # Not fatal — the swap already happened. Say it so a stuck mount+ # in a support log has an explanation.+ log.warning("[update] could not detach %s: %s", mountpoint, err.strip())+ shutil.rmtree(mountpoint, ignore_errors=True)++ if relaunch:+ try:+ runner.spawn_detached(["open", "-n", str(app_path)])+ except OSError as exc:+ raise InstallerUpdateError(+ f"the update was installed but could not be relaunched: {exc}"+ ) from exc+ log.info("[update] replaced %s from %s", app_path, dmg.name)+ return f"{app_path.name} was replaced and relaunched"+++def _handover_linux(+ downloaded: Path,+ *,+ runner: CommandRunner,+ appimage_path: Path | None,+ relaunch: bool,+) -> str:+ """Atomically swap the running AppImage for the downloaded one, relaunch."""+ if appimage_path is None:+ raise InstallerUpdateError(+ "this process is not running from an AppImage ($APPIMAGE is unset) — refusing to update"+ )++ staged = appimage_path.with_name(f".{appimage_path.name}.new")+ try:+ # Same directory, so os.replace below is a real atomic rename rather+ # than a cross-device copy that can leave a half-written binary.+ shutil.copyfile(downloaded, staged)+ # An AppImage that is not executable cannot be launched at all, and it+ # is the user's own file in their own directory. 0o755 is the mode the+ # AppImage project itself documents.+ os.chmod(staged, 0o755) # noqa: S103+ os.replace(staged, appimage_path)+ except OSError as exc:+ try:+ staged.unlink(missing_ok=True)+ except OSError as cleanup_exc:+ log.warning("[update] could not remove %s: %s", staged, cleanup_exc)+ raise InstallerUpdateError(f"could not replace {appimage_path}: {exc}") from exc++ if relaunch:+ try:+ runner.spawn_detached([str(appimage_path)])+ except OSError as exc:+ raise InstallerUpdateError(+ f"the update was installed but could not be relaunched: {exc}"+ ) from exc+ log.info("[update] replaced %s", appimage_path)+ return f"{appimage_path.name} was replaced and relaunched"+++def _replace_directory(source: Path, target: Path) -> None:+ """Put ``source`` where ``target`` is, keeping a rollback until it succeeds.++ ``os.replace`` refuses a non-empty destination directory, so the swap is two+ renames on the same filesystem: move the live bundle aside, move the new one+ in, then delete the old one. If the second rename fails the original is put+ straight back, so the app is never left missing.+ """+ staging = target.with_name(f".{target.name}.new")+ previous = target.with_name(f".{target.name}.old")+ shutil.rmtree(staging, ignore_errors=True)+ shutil.rmtree(previous, ignore_errors=True)++ try:+ shutil.copytree(source, staging, symlinks=True)+ except OSError as exc:+ shutil.rmtree(staging, ignore_errors=True)+ raise InstallerUpdateError(f"could not stage {target.name}: {exc}") from exc++ moved_aside = False+ try:+ if target.exists():+ os.replace(target, previous)+ moved_aside = True+ os.replace(staging, target)+ except OSError as exc:+ if moved_aside:+ try:+ os.replace(previous, target)+ except OSError as rollback_exc:+ raise InstallerUpdateError(+ f"{target.name} could not be restored after a failed update: {rollback_exc}"+ ) from rollback_exc+ shutil.rmtree(staging, ignore_errors=True)+ raise InstallerUpdateError(f"could not replace {target.name}: {exc}") from exc++ shutil.rmtree(previous, ignore_errors=True)+++def _running_macos_app() -> Path | None:+ """``/Applications/Personal Jarvis.app`` for the RUNNING process, if any.++ ``bundle_root()`` is ``<app>/Contents/MacOS``; the bundle is two levels up.+ """+ root = bundle_root()+ if root is None:+ return None+ for parent in (root, *root.parents):+ if parent.suffix == ".app":+ return parent+ return None+++def _running_appimage() -> Path | None:+ """The AppImage file this process was launched from (``$APPIMAGE``)."""+ raw = os.environ.get("APPIMAGE", "").strip()+ if not raw:+ return None+ candidate = Path(raw)+ return candidate if candidate.is_file() else None+++def supported_here() -> bool:+ """True when this process is frozen AND an installer exists for its platform."""+ if not is_frozen():+ return False+ return installer_asset_name(sys.platform, platform_module.machine()) is not Nonediff --git a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateProgress.test.tsx b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateProgress.test.tsxnew file mode 100644index 0000000000..6cba201d44--- /dev/null+++ b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateProgress.test.tsx@@ -0,0 +1,208 @@+/**+ * The update button as a progress bar.+ *+ * While an update runs, the button IS the progress indicator: it shows the+ * percentage the backend reports, fills proportionally, and finishes on the one+ * phase nothing can measure — the restart, announced by the UI itself because+ * the server reporting it is the process shutting down.+ *+ * What these tests defend is honesty. A bar that animates on a timer, rewinds,+ * or sticks at a number after the update failed is worse than no bar at all:+ * it is what the user decides "is this stuck?" from.+ */+import { cleanup, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { TopBar } from "@/components/layout/TopBar";+import { useEventStore } from "@/store/events";++const OFFER = {+ managed: true,+ kind: "managed",+ current: "1.0.1",+ latest: "1.0.2",+ update_available: true,+ notes: null,+ published_at: null,+};++function progressBody(percent: number, over: Record<string, unknown> = {}) {+ return {+ active: true,+ phase: "downloading",+ percent,+ detail: null,+ version: "1.0.2",+ kind: "managed",+ error: null,+ restart_required: true,+ ...over,+ };+}++/**+ * Wire a fake backend. ``progress`` is read fresh on every poll, so a test can+ * move the percentage between renders the way a real download does.+ */+function mockBackend(opts: {+ progress: () => Record<string, unknown>;+ applyOk?: boolean;+ restartOk?: boolean;+}) {+ const calls: string[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ calls.push(url);+ if (url.startsWith("/api/update/status")) {+ return { ok: true, status: 200, json: async () => OFFER };+ }+ if (url.startsWith("/api/update/progress")) {+ return { ok: true, status: 200, json: async () => opts.progress() };+ }+ if (url.startsWith("/api/update/apply")) {+ const ok = opts.applyOk !== false;+ return {+ ok,+ status: ok ? 200 : 502,+ json: async () => (ok ? { ok: true } : { detail: "git fetch failed" }),+ };+ }+ if (url.startsWith("/api/settings/restart-app")) {+ const ok = opts.restartOk !== false;+ return { ok, status: ok ? 200 : 500, json: async () => ({}) };+ }+ return { ok: true, status: 200, json: async () => ({}) };+ }),+ );+ return calls;+}++async function clickUpdate(): Promise<void> {+ const button = await screen.findByText("Update available");+ button.click();+}++function fillWidth(): string | undefined {+ const fill = document.querySelector<HTMLElement>(+ '[data-testid="update-progress-fill"]',+ );+ return fill?.style.width;+}++describe("TopBar update progress", () => {+ beforeEach(() => {+ useEventStore.setState({+ assistantName: "Assistant",+ toasts: [],+ activeSection: "settings",+ });+ window.localStorage.clear();+ });+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("shows the percentage the backend reports", async () => {+ mockBackend({ progress: () => progressBody(70), restartOk: false });+ render(<TopBar />);+ await clickUpdate();++ await waitFor(() => expect(screen.getByText("Updating 70%")).toBeTruthy());+ });++ it("fills the button proportionally to that percentage", async () => {+ mockBackend({ progress: () => progressBody(70), restartOk: false });+ render(<TopBar />);+ await clickUpdate();++ await waitFor(() => expect(fillWidth()).toBe("70%"));+ });++ it("follows the percentage upward as the download runs", async () => {+ let percent = 12;+ mockBackend({ progress: () => progressBody(percent), restartOk: false });+ render(<TopBar />);+ await clickUpdate();++ await waitFor(() => expect(screen.getByText("Updating 12%")).toBeTruthy());+ percent = 84;+ await waitFor(() => expect(screen.getByText("Updating 84%")).toBeTruthy());+ });++ it("exposes the same percentage to assistive technology", async () => {+ mockBackend({ progress: () => progressBody(70), restartOk: false });+ render(<TopBar />);+ await clickUpdate();++ await waitFor(() => {+ const bar = screen.getByRole("progressbar");+ expect(bar.getAttribute("aria-valuenow")).toBe("70");+ expect(bar.getAttribute("aria-valuemax")).toBe("100");+ });+ });++ it("is not a progress bar before an update starts", async () => {+ mockBackend({ progress: () => progressBody(0) });+ render(<TopBar />);+ await screen.findByText("Update available");++ // A stray role here would announce a bar frozen at 0 % on every launch.+ expect(screen.queryByRole("progressbar")).toBeNull();+ expect(fillWidth()).toBeUndefined();+ });++ it("ends on the restart, which no server can report", async () => {+ mockBackend({ progress: () => progressBody(100, { phase: "ready" }) });+ render(<TopBar />);+ await clickUpdate();++ await waitFor(() => expect(screen.getByText("Restarting…")).toBeTruthy());+ await waitFor(() => expect(fillWidth()).toBe("100%"));+ });++ it("drops the bar when the update fails instead of freezing it", async () => {+ mockBackend({ progress: () => progressBody(42), applyOk: false });+ render(<TopBar />);+ await clickUpdate();++ await waitFor(() => expect(screen.queryByRole("progressbar")).toBeNull());+ expect(screen.getByText("Update available")).toBeTruthy();+ });++ it("announces a finished update exactly once per install", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ if (url.startsWith("/api/update/status")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({+ ...OFFER,+ update_available: false,+ last_result: { ok: true, rolled_back: false, completed_at: 1234 },+ }),+ };+ }+ return { ok: true, status: 200, json: async () => ({}) };+ }),+ );++ const { unmount } = render(<TopBar />);+ await waitFor(() =>+ expect(+ useEventStore.getState().toasts.some((t) => t.message.includes("1.0.1")),+ ).toBe(true),+ );++ // A second launch reads the same verdict file off disk. Without the+ // localStorage guard it would re-announce the same install forever.+ useEventStore.setState({ toasts: [] });+ unmount();+ render(<TopBar />);+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(useEventStore.getState().toasts).toHaveLength(0);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsxindex ffb879d82f..b680a9f919 100644--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx@@ -2,8 +2,12 @@ import { useCallback, useEffect, useRef, useState } from "react";import { AppWindow, Download, RotateCw } from "lucide-react";import { useEventStore, type SectionId } from "@/store/events";-import { useUpdate } from "@/hooks/useUpdate";-import { useT } from "@/i18n";+import {+ fetchUpdateProgress,+ useUpdate,+ type UpdateProgress,+} from "@/hooks/useUpdate";+import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";import { CodingModeBadge } from "@/components/layout/CodingModeBadge";import { ThemeToggle } from "@/components/layout/ThemeToggle";@@ -313,6 +317,33 @@ const RESTART_RETRY_MS = 1500;const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));+// Fast enough that a 400 MB download visibly moves, slow enough to be free:+// the endpoint only copies a dict.+const PROGRESS_POLL_MS = 400;++// Which update verdict has already been announced. Stored per browser profile+// because the verdict file itself survives on disk — without this, every launch+// would re-announce the same finished update.+const NOTIFIED_UPDATE_KEY = "jarvis.update.notified";++function readNotifiedUpdate(): string | null {+ try {+ return window.localStorage.getItem(NOTIFIED_UPDATE_KEY);+ } catch {+ // Private mode / blocked site data. Losing the dedupe means one repeated+ // toast, which is strictly better than losing the message entirely.+ return null;+ }+}++function rememberNotifiedUpdate(key: string): void {+ try {+ window.localStorage.setItem(NOTIFIED_UPDATE_KEY, key);+ } catch {+ // Same trade as above — the announcement already happened.+ }+}+/** Append the server's error detail so a failure is diagnosable, not generic. */function withDetail(message: string, detail: string | null): string {const trimmed = (detail ?? "").trim();@@ -337,9 +368,30 @@ function UpdateButton() {const [busy, setBusy] = useState(false);const [forceArmed, setForceArmed] = useState(false);const [showNotes, setShowNotes] = useState(false);+ const [progress, setProgress] = useState<UpdateProgress | null>(null);+ const [restarting, setRestarting] = useState(false);const resetTimer = useRef<number | null>(null);const rollbackNotified = useRef<string | null>(null);+ // Poll the progress side channel for as long as the apply request is in+ // flight. It stops on its own when the button leaves the busy state, and a+ // failed fetch is left alone: during the restart the server is *supposed* to+ // go away, and blanking the bar then would look like the update collapsed.+ useEffect(() => {+ if (!busy) return;+ let live = true;+ const tick = async () => {+ const next = await fetchUpdateProgress();+ if (live && next) setProgress(next);+ };+ void tick();+ const id = window.setInterval(() => void tick(), PROGRESS_POLL_MS);+ return () => {+ live = false;+ window.clearInterval(id);+ };+ }, [busy]);+const clearResetTimer = useCallback(() => {if (resetTimer.current !== null) {clearTimeout(resetTimer.current);@@ -348,16 +400,30 @@ function UpdateButton() {}, []);useEffect(() => clearResetTimer, [clearResetTimer]);- // A rolled-back install is otherwise invisible: the app comes back on the- // old version and the button simply re-renders. Say it happened, once.+ // How the LAST update ended is otherwise invisible: the app just comes back,+ // on the new version or the old one, and the button re-renders. Both outcomes+ // get exactly one message.+ //+ // The dedupe key is remembered in localStorage, not only in this ref: the+ // verdict file survives on disk, so a ref alone would re-announce the same+ // update on every launch until the next one overwrote it.const lastResult = status?.last_result;useEffect(() => {- if (!lastResult || lastResult.ok) return;- const key = String(lastResult.completed_at ?? "unknown");+ if (!lastResult) return;+ const key = `${lastResult.ok ? "ok" : "fail"}:${lastResult.completed_at ?? "unknown"}`;if (rollbackNotified.current === key) return;+ if (readNotifiedUpdate() === key) return;rollbackNotified.current = key;- pushToast("warning", t("topbar.update_rolled_back"));- }, [lastResult, pushToast, t]);+ rememberNotifiedUpdate(key);+ if (lastResult.ok) {+ pushToast(+ "success",+ fill(t("topbar.update_installed"), { version: status?.current ?? "" }),+ );+ } else {+ pushToast("warning", t("topbar.update_rolled_back"));+ }+ }, [lastResult, pushToast, status?.current, t]);if (!status?.managed) return null;const hasOffer = status.update_available;@@ -368,6 +434,8 @@ function UpdateButton() {async function run(force: boolean) {clearResetTimer();setBusy(true);+ setRestarting(false);+ setProgress(null);setShowNotes(false);// 1. Stage the new code. The server re-verifies the managed-install guard,@@ -384,6 +452,7 @@ function UpdateButton() {// 403 unmanaged / 409 nothing newer / 502 git or GitHub failure — the// backend's detail says WHICH, and the user must get to see it.setBusy(false);+ setProgress(null);setForceArmed(false);pushToast("error",@@ -402,6 +471,7 @@ function UpdateButton() {}} catch {setBusy(false);+ setProgress(null);setForceArmed(false);pushToast("error",@@ -430,6 +500,7 @@ function UpdateButton() {/* malformed body — still arm the override */}setBusy(false);+ setProgress(null);setForceArmed(true);clearResetTimer();resetTimer.current = window.setTimeout(() => {@@ -445,7 +516,10 @@ function UpdateButton() {if (restartRes.ok) {// Success — the code is staged 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"));+ // This last phase is the one the server cannot report: it is the+ // thing that is dying, so the UI states it itself.+ setRestarting(true);+ pushToast("info", t("topbar.update_restarting"));return;}const body = (await restartRes.json().catch(() => ({}))) as {@@ -462,6 +536,8 @@ function UpdateButton() {// The download IS staged — a manual restart (or the next successful click)// finishes it. Saying "failed" here would be dishonest and untraceable.setBusy(false);+ setRestarting(false);+ setProgress(null);setForceArmed(false);pushToast("warning",@@ -474,13 +550,19 @@ function UpdateButton() {void run(forceArmed);}- const label = busy- ? t("topbar.updating")- : forceArmed- ? t("topbar.restart_force")- : hasOffer- ? t("topbar.update_available")- : t("topbar.update_finish_restart");+ // The bar is driven by the server while it works, then pinned at 100 % for+ // the restart — the one phase nothing can measure, because the thing that+ // would report it is the thing shutting down.+ const percent = restarting ? 100 : (progress?.percent ?? 0);+ const label = restarting+ ? t("topbar.update_restarting")+ : busy+ ? fill(t("topbar.updating_percent"), { percent })+ : forceArmed+ ? t("topbar.restart_force")+ : hasOffer+ ? t("topbar.update_available")+ : t("topbar.update_finish_restart");return (<div@@ -492,21 +574,39 @@ function UpdateButton() {type="button"onClick={onClick}disabled={busy}- title={t("topbar.update_hint")}+ title={busy ? (progress?.detail ?? label) : t("topbar.update_hint")}+ // The button doubles as the progress bar while it runs, so it carries+ // the ARIA role of one — a screen reader announces the same percentage+ // the fill shows. Outside an update those attributes must be absent,+ // not zeroed, or it reads as a bar stuck at 0 %.+ role={busy ? "progressbar" : undefined}+ aria-valuemin={busy ? 0 : undefined}+ aria-valuemax={busy ? 100 : undefined}+ aria-valuenow={busy ? percent : undefined}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",+ "relative inline-flex items-center gap-1.5 overflow-hidden rounded-md border px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-default disabled:opacity-70",forceArmed? "border-foreground/60 bg-foreground/10 text-foreground hover:bg-foreground/20": "border-primary/50 bg-primary/10 text-primary hover:bg-primary/20",)}>+ {busy && (+ <span+ aria-hidden+ data-testid="update-progress-fill"+ // A token tint on the button's own token background: it reads as a+ // fill in light and dark alike, with no hardcoded colour.+ className="absolute inset-y-0 left-0 bg-primary/25 transition-[width] duration-300 ease-out"+ style={{ width: `${percent}%` }}+ />+ )}<Downloadaria-hidden- className={cn("h-3.5 w-3.5", busy && "animate-pulse")}+ className={cn("relative h-3.5 w-3.5", busy && "animate-pulse")}/>- {label}+ <span className="relative tabular-nums">{label}</span>{!busy && !forceArmed && shownVersion && (- <span className="rounded bg-primary/20 px-1 text-[10px] tabular-nums">+ <span className="relative rounded bg-primary/20 px-1 text-[10px] tabular-nums">v{shownVersion}</span>)}diff --git a/jarvis/ui/web/frontend/src/hooks/useUpdate.ts b/jarvis/ui/web/frontend/src/hooks/useUpdate.tsindex 0757307aaf..472cd5f138 100644--- a/jarvis/ui/web/frontend/src/hooks/useUpdate.ts+++ b/jarvis/ui/web/frontend/src/hooks/useUpdate.ts@@ -33,10 +33,57 @@ export interface UpdateStatus {} | null;}+/**+ * Live state of an update that is being applied right now, from+ * GET /api/update/progress. The apply call is one long request, so this is the+ * only way to learn anything before it returns.+ *+ * ``phase`` walks idle -> resolving -> downloading -> verifying -> installing ->+ * ready, or lands on failed. ``percent`` is a phase model fed by real+ * measurements (bytes off the socket, git's object counters) and never rewinds,+ * so it is safe to bind a bar width straight to it.+ */+export interface UpdateProgress {+ active: boolean;+ phase:+ | "idle"+ | "resolving"+ | "downloading"+ | "verifying"+ | "installing"+ | "ready"+ | "failed";+ percent: number;+ /** Human sub-status, e.g. "64.0 MB / 128.0 MB". Null when there is none. */+ detail: string | null;+ version: string | null;+ kind: string | null;+ error: string | null;+ restart_required: 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;+/**+ * Read the live progress of an in-flight update.+ *+ * Returns null on any failure — and during an update that is a MEANINGFUL null,+ * not just a hiccup: the restart kills this server mid-poll, so an unreachable+ * progress endpoint is the expected end of a successful update, never something+ * to surface as an error.+ */+export async function fetchUpdateProgress(): Promise<UpdateProgress | null> {+ try {+ const res = await fetch("/api/update/progress");+ if (!res.ok) return null;+ return (await res.json()) as UpdateProgress;+ } catch {+ return null;+ }+}+async function fetchStatus(force = false): Promise<UpdateStatus | null> {try {const res = await fetch(`/api/update/status${force ? "?force=true" : ""}`);diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 287dd5f8e2..6cebfd57e3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -52,6 +52,9 @@"restart_missions_running": "Mission(en) laufen noch — nochmal klicken zum Erzwingen","update_available": "Update verfügbar","updating": "{name} wird aktualisiert…",+ "updating_percent": "Aktualisiere {percent} %",+ "update_restarting": "Starte neu…",+ "update_installed": "Auf v{version} aktualisiert","update_failed": "Update fehlgeschlagen","update_hint": "Neue Version herunterladen und {name} zur Installation automatisch neu starten","update_deps_warning": "Aktualisiert — einige Komponenten brauchen evtl. eine manuelle Neuinstallation",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex ba6430d78e..b9eac16431 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -52,6 +52,9 @@"restart_missions_running": "mission(s) still running — click again to restart anyway","update_available": "Update available","updating": "Updating {name}…",+ "updating_percent": "Updating {percent}%",+ "update_restarting": "Restarting…",+ "update_installed": "Updated to v{version}","update_failed": "Update failed","update_hint": "Download the new version and restart {name} automatically to install it","update_deps_warning": "Updated — some components may need a manual reinstall",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 6203e873cd..d923d272d6 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -52,6 +52,9 @@"restart_missions_running": "misión(es) en curso — haz clic de nuevo para reiniciar igualmente","update_available": "Actualización disponible","updating": "Actualizando {name}…",+ "updating_percent": "Actualizando {percent} %",+ "update_restarting": "Reiniciando…",+ "update_installed": "Actualizado a v{version}","update_failed": "Error al actualizar","update_hint": "Descargar la nueva versión y reiniciar {name} automáticamente para instalarla","update_deps_warning": "Actualizado — algunos componentes pueden requerir reinstalación manual",diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.pyindex f83ad0f7b6..93dfced50f 100644--- a/jarvis/ui/web/update_routes.py+++ b/jarvis/ui/web/update_routes.py@@ -1,5 +1,25 @@-"""In-app updater for a MANAGED install of Personal Jarvis.-+"""In-app updater — one "Update Now" button over two very different installs.++Personal Jarvis reaches a machine in one of two supported ways, and each one+updates itself differently:++* **frozen** — the visitor downloaded a native installer from the website+ (``Setup.exe`` / ``.dmg`` / ``.AppImage``). There is no git checkout here. The+ update is the NEXT installer asset on the GitHub Release: downloaded, proven+ against that same release's ``installers-SHA256SUMS.txt``, then handed to the+ platform's own upgrade mechanism (``jarvis/core/installer_update.py``).+ ``jarvis.core.frozen.is_frozen()`` is the ONLY probe that selects this path,+ so a dev tree and a managed checkout are structurally unaffected by it.+* **managed** — the one-line installer's git checkout under+ ``~/.personal-jarvis``. Updates are a ``git fetch`` of the published tag plus+ a reinstall; everything below describes that path.++Anything else (a maintainer checkout, a fork, a plain ``pip install``) is+``dev``: ``status`` reports ``managed: false``, the button never renders, and+``apply`` refuses.++The managed path+----------------An end user installs Personal Jarvis with the one-line installer, which clonesthe public flagship repo into ``~/.personal-jarvis`` and runs the app from thatcheckout. This module lets the running desktop app offer a one-click "Update@@ -41,9 +61,13 @@ import asyncioimport jsonimport loggingimport os+import platform as platform_moduleimport re+import shutilimport sys+import tempfileimport time+from collections.abc import Callablefrom pathlib import Pathfrom typing import Any, Literal@@ -55,6 +79,15 @@ from jarvis.core.branding import (OFFICIAL_REPO_SLUG,UPDATER_USER_AGENT,)+from jarvis.core.frozen import is_frozen+from jarvis.core.installer_update import (+ CHECKSUMS_ASSET_NAME,+ InstallerUpdateError,+ apply_installer,+ download_and_verify,+ installer_asset_name,+ select_asset,+)from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSlog = logging.getLogger(__name__)@@ -214,12 +247,52 @@ async def _terminate(proc: asyncio.subprocess.Process) -> None:pass-async def _run(cmd: list[str], *, cwd: Path, timeout_s: float) -> tuple[int, str, str]:+# git writes its progress counters to stderr and separates the redraws with a+# carriage return, so "one update" is a CR- or LF-delimited segment, not a line.+_PROGRESS_SEGMENT_RE = re.compile(rb"[\r\n]")+++async def _pump(stream: asyncio.StreamReader, on_line: Callable[[str], None] | None) -> bytes:+ """Read ``stream`` to EOF, handing each finished segment to ``on_line``.++ Returns everything that was read, so the caller still gets the complete+ output it would have gotten from ``communicate()``.+ """+ chunks: list[bytes] = []+ pending = b""+ while True:+ chunk = await stream.read(4096)+ if not chunk:+ break+ chunks.append(chunk)+ if on_line is None:+ continue+ segments = _PROGRESS_SEGMENT_RE.split(pending + chunk)+ pending = segments.pop()+ for segment in segments:+ text = segment.decode(errors="replace").strip()+ if text:+ on_line(text)+ return b"".join(chunks)+++async def _run(+ cmd: list[str],+ *,+ cwd: Path,+ timeout_s: float,+ on_stderr_line: Callable[[str], None] | None = None,+) -> tuple[int, str, str]:"""Run ``cmd`` in ``cwd``. Returns ``(returncode, stdout, stderr)``.``returncode == -1`` signals the process could not run at all (missingbinary) or timed out — ``stderr`` then carries a human reason. Cleans up thechild on timeout/cancel so no zombie is left behind.++ ``on_stderr_line`` taps stderr as it arrives instead of only at the end,+ which is the only way to read git's progress counters while the fetch is+ still running. It must not raise; :func:`_git_progress_tap` wraps the one+ caller that uses it."""try:proc = await asyncio.create_subprocess_exec(@@ -234,9 +307,20 @@ async def _run(cmd: list[str], *, cwd: Path, timeout_s: float) -> tuple[int, str# ends up in the update status the user sees.return -1, "", f"could not run {cmd[0]}: {exc}"+ async def collect() -> tuple[bytes, bytes]:+ # Both pipes must be drained concurrently: a child that fills one while+ # we read the other deadlocks, which is exactly what a chatty+ # ``git fetch --progress`` would do.+ assert proc.stdout is not None and proc.stderr is not None+ raw_out, raw_err = await asyncio.gather(+ _pump(proc.stdout, None), _pump(proc.stderr, on_stderr_line)+ )+ await proc.wait()+ return raw_out, raw_err+try:try:- raw_out, raw_err = await asyncio.wait_for(proc.communicate(), timeout=timeout_s)+ raw_out, raw_err = await asyncio.wait_for(collect(), timeout=timeout_s)except TimeoutError:# Same contract: the timeout is reported through stderr, and the# child is reaped first so no zombie survives the request.@@ -254,8 +338,14 @@ async def _run(cmd: list[str], *, cwd: Path, timeout_s: float) -> tuple[int, strreturn 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(+ args: list[str],+ *,+ cwd: Path,+ timeout_s: float = 60.0,+ on_stderr_line: Callable[[str], None] | None = None,+) -> tuple[int, str, str]:+ return await _run(["git", *args], cwd=cwd, timeout_s=timeout_s, on_stderr_line=on_stderr_line)async def _git_output(args: list[str], *, cwd: Path, timeout_s: float = 15.0) -> str | None:@@ -351,12 +441,16 @@ async def _fetch_latest_release() -> dict[str, Any] | None:release_tag = str(data.get("tag_name") or "").strip()if not _RELEASE_TAG_RE.fullmatch(release_tag):return None+ raw_assets = data.get("assets")release = {"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"),+ # Only the frozen path reads this; the managed path resolves its+ # target from the git tag and ignores the attachments entirely.+ "assets": raw_assets if isinstance(raw_assets, list) else [],}_last_good_release = releasereturn release@@ -545,6 +639,7 @@ async def _staged_update_response(root: Path) -> dict[str, object] | None:"ok": True,"prepared": True,"restart_required": True,+ "kind": INSTALL_KIND_MANAGED,"version": version,"release_tag": f"v{version}","install_profile": profile,@@ -558,6 +653,397 @@ async def _staged_update_response(root: Path) -> dict[str, object] | None:}+# --------------------------------------------------------------------------- #+# Frozen install (native installer) — download, verify, hand over+# --------------------------------------------------------------------------- #+INSTALL_KIND_FROZEN = "frozen"+INSTALL_KIND_MANAGED = "managed"+INSTALL_KIND_DEV = "dev"+++# --------------------------------------------------------------------------- #+# Live progress of the one in-flight update+# --------------------------------------------------------------------------- #+# ``apply`` is a single long request (a few hundred MB on a frozen install), so+# the UI cannot learn anything from its return value until it is over. This+# tracker is what ``GET /api/update/progress`` publishes while that request is+# still running, turning "Updating…" into "Updating 70%".+#+# The percentages are a PHASE MODEL, never a timer. Each phase owns a fixed+# window, and inside a window the number moves only on evidence we actually+# have: bytes off the socket on a frozen install, git's own object counters on+# a managed one. A phase with no measurable inside (writing the transaction+# manifest) simply lands on its window's end when it completes. That makes a+# jump possible, but never a lie — which is the right trade for a bar the user+# is deciding "is this stuck?" from.+PHASE_IDLE = "idle"+PHASE_RESOLVING = "resolving"+PHASE_DOWNLOADING = "downloading"+PHASE_VERIFYING = "verifying"+PHASE_INSTALLING = "installing"+PHASE_READY = "ready"+PHASE_FAILED = "failed"++# ``{install kind: {phase: (window start %, window end %)}}``. The two kinds do+# very different work, so they weight the phases differently: a frozen install+# is dominated by the download, a managed one by the git fetch.+_PHASE_SPANS: dict[str, dict[str, tuple[int, int]]] = {+ INSTALL_KIND_FROZEN: {+ PHASE_RESOLVING: (0, 6),+ PHASE_DOWNLOADING: (6, 86),+ PHASE_VERIFYING: (86, 94),+ PHASE_INSTALLING: (94, 100),+ },+ INSTALL_KIND_MANAGED: {+ PHASE_RESOLVING: (0, 10),+ PHASE_DOWNLOADING: (10, 78),+ PHASE_VERIFYING: (78, 92),+ PHASE_INSTALLING: (92, 100),+ },+}+++class _UpdateProgress:+ """Mutable snapshot of the update currently being applied.++ One instance per process: only one update may run at a time (the apply+ route rejects a second with 409), so a single slot is the whole model.+ Every method is total — a tracker that raised would take the update down+ with it, and progress is cosmetic.+ """++ def __init__(self) -> None:+ self.kind: str = INSTALL_KIND_DEV+ self.phase: str = PHASE_IDLE+ self.percent: int = 0+ self.detail: str | None = None+ self.version: str | None = None+ self.error: str | None = None+ self.restart_required: bool = False+ self.started_at: float | None = None+ self.updated_at: float | None = None++ # -- lifecycle ---------------------------------------------------------- #+ def begin(self, kind: str, *, version: str | None = None) -> None:+ """Start a run. The ONLY point at which the percentage may go down."""+ self.kind = kind+ self.phase = PHASE_RESOLVING+ self.percent = 0+ self.detail = None+ self.version = version+ self.error = None+ self.restart_required = False+ self.started_at = self.updated_at = time.time()++ def enter(self, phase: str, *, detail: str | None = None) -> None:+ """Move to ``phase``, landing on the start of its window."""+ self.advance(phase, 0.0, detail=detail)++ def advance(self, phase: str, fraction: float, *, detail: str | None = None) -> None:+ """Report being ``fraction`` (0..1) through ``phase``.++ Monotonic on purpose: git reports "Receiving objects" and "Resolving+ deltas" as two separate 0→100 % counters, and a bar that rewinds reads+ as a restart to anyone watching it.+ """+ low, high = _PHASE_SPANS.get(self.kind, {}).get(phase, (self.percent, self.percent))+ clamped = 0.0 if fraction < 0 else 1.0 if fraction > 1 else fraction+ self.phase = phase+ self.percent = max(self.percent, int(low + (high - low) * clamped))+ if detail is not None:+ self.detail = detail+ self.updated_at = time.time()++ def finish(self, *, version: str | None, restart_required: bool) -> None:+ """The server's work is done; what remains is the restart."""+ self.phase = PHASE_READY+ self.percent = 100+ self.version = version or self.version+ self.restart_required = restart_required+ self.error = None+ self.updated_at = time.time()++ def fail(self, message: str) -> None:+ """Stop, keeping the percentage where it died so the UI can say where."""+ self.phase = PHASE_FAILED+ self.error = message[:300]+ self.updated_at = time.time()++ # -- readers ------------------------------------------------------------ #+ def snapshot(self) -> dict[str, object]:+ """The shape ``GET /api/update/progress`` returns."""+ return {+ "active": self.phase not in (PHASE_IDLE, PHASE_READY, PHASE_FAILED),+ "phase": self.phase,+ "percent": self.percent,+ "detail": self.detail,+ "version": self.version,+ "kind": self.kind,+ "error": self.error,+ "restart_required": self.restart_required,+ "started_at": self.started_at,+ "updated_at": self.updated_at,+ }+++_progress = _UpdateProgress()+++def _human_bytes(count: int) -> str:+ """``134217728`` -> ``"128.0 MB"``.++ Short on purpose: this string sits inside a top-bar pill, where fitting+ matters far more than precision.+ """+ step = 1024.0+ size = float(count)+ for unit in ("B", "KB", "MB", "GB"):+ if size < step or unit == "GB":+ return f"{size:.0f} {unit}" if unit in ("B", "KB") else f"{size:.1f} {unit}"+ size /= step+ return f"{size:.1f} GB"+++# Serialises applies. A second click while the first download runs would fight+# over the same temp directory and scramble the percentage; the route answers+# 409 instead of queueing, because the user is already getting what they asked+# for.+_apply_lock = asyncio.Lock()++# git's own progress lines on stderr: "Receiving objects: 43% (430/1000)".+# Receiving is where the bytes are, so it owns most of the fetch window and+# delta resolution finishes it off.+_GIT_PROGRESS_RE = re.compile(r"(Receiving objects|Resolving deltas):\s+(\d+)%")+_GIT_PROGRESS_WEIGHTS = {"Receiving objects": (0.0, 0.85), "Resolving deltas": (0.85, 1.0)}+++def _on_git_progress(line: str) -> None:+ """Translate one git stderr line into a fetch-window fraction."""+ match = _GIT_PROGRESS_RE.search(line)+ if match is None:+ return+ low, high = _GIT_PROGRESS_WEIGHTS[match.group(1)]+ share = int(match.group(2)) / 100.0+ _progress.advance(PHASE_DOWNLOADING, low + (high - low) * share)+++def _frozen_asset_name() -> str | None:+ """The installer asset this machine installs, or ``None`` if there is none."""+ return installer_asset_name(sys.platform, platform_module.machine())+++def _frozen_release_assets(+ release: dict[str, Any], asset_name: str+) -> tuple[Any | None, Any | None]:+ """``(installer asset, checksum manifest asset)`` from a release payload."""+ assets = release.get("assets") or []+ if not isinstance(assets, list):+ return None, None+ return select_asset(assets, asset_name), select_asset(assets, CHECKSUMS_ASSET_NAME)+++async def _frozen_status(current: str) -> dict[str, object]:+ """Status for a natively installed app. Fail-OPEN, exactly like the managed one.++ ``managed`` stays the field the UI gates the button on — it means "this+ install can update itself", which a frozen install can. ``kind`` says HOW.++ An update is offered only when the release actually carries BOTH this+ platform's installer and the checksum manifest, because without either one+ ``apply`` would have to refuse: offering a button that cannot work is worse+ than staying quiet.+ """+ result: dict[str, object] = {+ "managed": True,+ "kind": INSTALL_KIND_FROZEN,+ "current": current,+ "latest": None,+ "update_available": False,+ "notes": None,+ "published_at": None,+ "asset": None,+ # Frozen installs have no staged git transaction and no relauncher+ # verdict; the fields stay present so the UI reads one shape.+ "pending_update": None,+ "last_result": None,+ }++ asset_name = _frozen_asset_name()+ if asset_name is None:+ # No installer is published for this OS/CPU pair (a Windows ARM64 box,+ # a Linux aarch64 box). Never offer what cannot be installed.+ log.info(+ "[update] no installer asset exists for %s/%s",+ sys.platform,+ platform_module.machine(),+ )+ result["managed"] = False+ result["unsupported_platform"] = True+ return result++ latest = await _fetch_latest_release()+ if latest is None:+ result["check_failed"] = True+ return result++ version = str(latest.get("version") or "")+ asset, checksums = _frozen_release_assets(latest, asset_name)+ result["latest"] = version or None+ result["published_at"] = latest.get("published_at")+ result["release_url"] = latest.get("release_url")++ if asset is None or checksums is None:+ # A release without installers is a code-only release (or one whose+ # installer job failed). Report honestly instead of half-offering.+ log.info(+ "[update] release %s carries no %s / %s — not offering a frozen update",+ version or "?",+ asset_name,+ CHECKSUMS_ASSET_NAME,+ )+ return result++ result["asset"] = asset.as_dict()+ if _is_newer(version, current):+ result["update_available"] = True+ result["notes"] = latest.get("notes")+ return result+++async def _apply_frozen() -> dict[str, object]:+ """Download, verify and install the native installer for this machine.++ Fail-CLOSED at every step: an unresolvable release, a missing asset, a+ missing or mismatching SHA-256 all raise before anything is executed. The+ running app keeps working on the old version in every failure case.+ """+ _progress.begin(INSTALL_KIND_FROZEN)+ current = _running_version()+ asset_name = _frozen_asset_name()+ if asset_name is None:+ raise HTTPException(+ status_code=501,+ detail=(+ f"no Personal Jarvis installer is published for "+ f"{sys.platform}/{platform_module.machine()}"+ ),+ )++ latest = await _fetch_latest_release()+ if latest is None and _last_good_release is not None:+ # Same reasoning as the managed path: the unauthenticated releases API+ # is rate-limited per IP, so a blip between status and click must not+ # brick the button. The SHA-256 check below still proves the bytes.+ log.info("[update] live release check failed — using the last good answer")+ latest = _last_good_release+ if latest is None:+ raise HTTPException(+ status_code=502,+ detail=(+ "could not reach GitHub to resolve the latest published release "+ "(offline or rate-limited) — try again in a few minutes"+ ),+ )++ release_tag = str(latest.get("tag") or "")+ release_version = str(latest.get("version") 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, current):+ raise HTTPException(status_code=409, detail="no newer published release exists")++ asset, checksums = _frozen_release_assets(latest, asset_name)+ if asset is None:+ raise HTTPException(+ status_code=502,+ detail=f"release {release_tag} does not contain {asset_name}",+ )+ if checksums is None:+ raise HTTPException(+ status_code=502,+ detail=(+ f"release {release_tag} has no {CHECKSUMS_ASSET_NAME} — refusing to "+ "install an installer that cannot be verified"+ ),+ )++ _progress.version = release_version++ def on_bytes(written: int, total: int | None) -> None:+ """One download tick. Without a total there is no honest fraction."""+ if not total:+ _progress.advance(PHASE_DOWNLOADING, 0.0, detail=_human_bytes(written))+ return+ _progress.advance(+ PHASE_DOWNLOADING,+ written / total,+ detail=f"{_human_bytes(written)} / {_human_bytes(total)}",+ )++ workdir = Path(tempfile.mkdtemp(prefix="jarvis-update-"))+ try:+ _progress.enter(PHASE_DOWNLOADING, detail=asset.name)+ installer = await download_and_verify(+ asset, checksums, dest_dir=workdir, on_progress=on_bytes+ )+ # download_and_verify hashes the file after the last byte lands, so by+ # the time it returns the verify phase is already over — the window is+ # closed here rather than announced, to keep the bar truthful.+ _progress.advance(PHASE_VERIFYING, 1.0, detail=None)+ _progress.enter(PHASE_INSTALLING)+ # hdiutil, a directory swap and a detached spawn all block; keep the+ # event loop (and therefore the UI this answer travels back over) free.+ handover = await asyncio.to_thread(apply_installer, installer)+ except InstallerUpdateError as exc:+ shutil.rmtree(workdir, ignore_errors=True)+ _progress.fail(str(exc))+ log.warning("[update] frozen update refused: %s", exc)+ raise HTTPException(status_code=502, detail=str(exc)) from exc+ except Exception as exc: # noqa: BLE001 — the user must see WHY it stopped+ shutil.rmtree(workdir, ignore_errors=True)+ _progress.fail(f"the update could not be installed: {exc}")+ log.exception("[update] frozen update failed unexpectedly")+ raise HTTPException(+ status_code=500, detail=f"the update could not be installed: {exc}"+ ) from exc++ # The native installer restarts the app itself, so this run is complete.+ _progress.finish(version=release_version, restart_required=False)++ # The download is deliberately NOT deleted: on Windows the installer that+ # replaces this app is running from it right now. The OS reclaims the temp+ # directory; deleting it here would kill the update mid-flight.+ log.info("[update] %s installed from %s (%s)", release_tag, asset.name, workdir)++ global _status_cache, _status_cache_until, _status_cache_root+ _status_cache, _status_cache_until, _status_cache_root = None, 0.0, None++ return {+ "ok": True,+ "prepared": True,+ # The handover restarts the app itself (Inno's /RESTARTAPPLICATIONS,+ # `open` on macOS, re-exec on Linux), so no caller-driven restart is+ # required. The field is honest about that; a caller that restarts+ # anyway is harmless because the single-instance lock still holds.+ "restart_required": False,+ "kind": INSTALL_KIND_FROZEN,+ "version": release_version,+ "release_tag": release_tag,+ "install_profile": "frozen",+ "asset": asset.as_dict(),+ "handover": handover,+ "deps_refreshed": False,+ "deps_pending": False,+ "deps_warning": None,+ "ui_bundle_pending": False,+ "desktop_integration_ok": None,+ # The native installer owns Start Menu / Applications / .desktop+ # registration, so there is nothing for the app to write.+ "desktop_integration_pending": False,+ "desktop_integration_warning": None,+ }++# --------------------------------------------------------------------------- ## Routes# --------------------------------------------------------------------------- #@@ -573,7 +1059,8 @@ async def update_status(force: bool = False) -> dict[str, object]:# The network part (and the resolved managed root, one git subprocess)# is cached; the staged-transaction fields are cheap local file reads# and must always be live (an apply invalidates the cache, but a- # relauncher result appears while the cache is warm).+ # relauncher result appears while the cache is warm). A frozen install+ # has no such local state, so its cached answer is complete.if _status_cache.get("managed") and _status_cache_root is not None:return {**_status_cache,@@ -582,12 +1069,25 @@ async def update_status(force: bool = False) -> dict[str, object]:return _status_cachecurrent = _running_version()++ if is_frozen():+ # A native install has no checkout to resolve and must never enter the+ # git path below (there is no `origin`, no marker, and no `git`).+ frozen_result = await _frozen_status(current)+ _status_cache_root = None+ _status_cache = frozen_result+ _status_cache_until = now + (+ _STATUS_RETRY_S if frozen_result.get("check_failed") else _STATUS_CACHE_TTL_S+ )+ return frozen_result+root = await _resolve_managed_repo()_status_cache_root = rootif root is None:result: dict[str, object] = {"managed": False,+ "kind": INSTALL_KIND_DEV,"current": current,"latest": None,"update_available": False,@@ -603,6 +1103,7 @@ async def update_status(force: bool = False) -> dict[str, object]:# and retry sooner than the full TTL.result = {"managed": True,+ "kind": INSTALL_KIND_MANAGED,"current": current,"latest": None,"update_available": False,@@ -616,6 +1117,7 @@ async def update_status(force: bool = False) -> dict[str, object]:available = _is_newer(str(latest["version"]), current)result = {"managed": True,+ "kind": INSTALL_KIND_MANAGED,"current": current,"latest": latest["version"],"update_available": available,@@ -627,15 +1129,63 @@ async def update_status(force: bool = False) -> dict[str, object]:return {**result, **(await _pending_update_overlay(root))}[email protected]("/progress")+async def update_progress() -> dict[str, object]:+ """The live percentage of the update currently being applied.++ ``POST /api/update/apply`` is one long request — several hundred megabytes+ on a frozen install — so its return value tells the UI nothing until it is+ over. This is the side channel the button polls meanwhile, which is what+ turns "Updating…" into "Updating 70%".++ Always answers, whether or not an update is running: ``phase: "idle"`` is+ the resting state, ``"ready"`` means the server's work is done and only the+ restart remains, and ``"failed"`` carries the reason in ``error``. Reading+ it costs nothing but a dict copy, so a 300 ms poll is fine.+ """+ return _progress.snapshot()++@router.post("/apply", openapi_extra={"x-jarvis-dangerous": True})async def update_apply() -> dict[str, object]:- """Prepare the latest code for a managed install. Does NOT restart.+ """Prepare the latest version and report progress while doing it.++ Dispatches on the install kind: a FROZEN install downloads and hands over+ the platform installer (``_apply_frozen``), a MANAGED checkout stages a git+ transaction the relauncher finishes (``_apply_managed``).++ Two things wrap both branches. The lock rejects a second concurrent apply+ with 409 rather than queueing it — two downloads would fight over the temp+ directory and scramble the shared progress state, and the user is already+ getting what they clicked for. The handler also guarantees that ANY failure+ lands in the progress tracker: a run that ends without ``fail`` leaves the+ button reading "Updating 42%" forever.+ """+ if _apply_lock.locked():+ raise HTTPException(status_code=409, detail="an update is already being applied")+ async with _apply_lock:+ try:+ if is_frozen():+ return await _apply_frozen()+ return await _apply_managed()+ except HTTPException as exc:+ _progress.fail(str(exc.detail))+ raise+ except Exception as exc: # noqa: BLE001 — re-raised; this only records it+ _progress.fail(f"{type(exc).__name__}: {exc}")+ raise+++async def _apply_managed() -> dict[str, object]:+ """Stage the latest published tag for a managed checkout. Does NOT restart.The live checkout remains untouched. The caller then invokes``POST /api/settings/restart-app``; its detached relauncher applies thepinned revision and completes installation after this process exits."""global _status_cache, _status_cache_until, _status_cache_root+ _progress.begin(INSTALL_KIND_MANAGED)+root = await _resolve_managed_repo()if root is None:raise HTTPException(@@ -656,6 +1206,8 @@ async def update_apply() -> dict[str, object]:if staged is not None:# GitHub is unreachable but a validated transaction is already on# disk from an earlier click — restarting can finish it offline.+ # Nothing was downloaded, so the run is complete at once.+ _progress.finish(version=str(staged.get("version") or ""), restart_required=True)return stagedraise HTTPException(status_code=502,@@ -671,6 +1223,9 @@ async def update_apply() -> dict[str, object]:if not _is_newer(release_version, _running_version()):raise HTTPException(status_code=409, detail="no newer published release exists")+ _progress.version = release_version+ _progress.advance(PHASE_RESOLVING, 1.0)+previous_revision = await _git_output(["rev-parse", "HEAD"], cwd=root)if not previous_revision:raise HTTPException(@@ -681,16 +1236,23 @@ async def update_apply() -> dict[str, object]:# 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.+ #+ # ``--progress`` forces git to emit its object counters even though stderr+ # is a pipe rather than a terminal; without it the download phase would+ # have no measurable inside at all.+ _progress.enter(PHASE_DOWNLOADING, detail=release_tag)rc, _out, err = await _git(- ["fetch", "--depth", "1", "origin", f"refs/tags/{release_tag}"],+ ["fetch", "--progress", "--depth", "1", "origin", f"refs/tags/{release_tag}"],cwd=root,timeout_s=120.0,+ on_stderr_line=_on_git_progress,)if rc != 0:raise HTTPException(status_code=502, detail=f"git fetch failed: {err[:300] or 'unknown error'}")+ _progress.enter(PHASE_VERIFYING)target_revision = await _git_output(["rev-parse", "FETCH_HEAD^{commit}"], cwd=root)if not target_revision:raise HTTPException(@@ -705,6 +1267,8 @@ async def update_apply() -> dict[str, object]:detail="published tag version does not match its release metadata",)+ _progress.advance(PHASE_VERIFYING, 1.0)+ _progress.enter(PHASE_INSTALLING)profile = _managed_install_profile(root)try:_write_pending_update(@@ -722,11 +1286,15 @@ async def update_apply() -> dict[str, object]:# The next status poll must see the staged transaction immediately._status_cache, _status_cache_until, _status_cache_root = None, 0.0, None+ # Everything this process can do is done; the relauncher does the rest,+ # which is why the caller must now restart.+ _progress.finish(version=new_version, restart_required=True)return {"ok": True,"prepared": True,"restart_required": True,+ "kind": INSTALL_KIND_MANAGED,"version": new_version,"release_tag": release_tag,"install_profile": profile,diff --git a/tests/fakes/fake_installer_update.py b/tests/fakes/fake_installer_update.pynew file mode 100644index 0000000000..1b2b4d8fae--- /dev/null+++ b/tests/fakes/fake_installer_update.py@@ -0,0 +1,130 @@+"""Fakes for the two edges of ``jarvis.core.installer_update``.++The updater talks to exactly two things it cannot own in a test: the network+(:class:`FakeAssetFetcher`) and the operating system's process table+(:class:`FakeCommandRunner`). Replacing those two makes the whole flow —+including the macOS and Linux handovers — runnable on any OS, offline, without+installing anything.+"""++from __future__ import annotations++from collections.abc import Callable, Sequence+from dataclasses import dataclass, field+from pathlib import Path++__all__ = ["FakeAssetFetcher", "FakeCommandRunner", "RunResult"]+++def _write(dest: Path, payload: bytes) -> None:+ """Blocking write, kept out of the async body (ruff ASYNC240)."""+ dest.write_bytes(payload)+++@dataclass+class FakeAssetFetcher:+ """Serves a checksum manifest and one installer payload from memory.++ ``fail_text`` / ``fail_download`` raise the given exception instead, which is+ how the transport-error branches are exercised without a socket.+ """++ manifest: str = ""+ payload: bytes = b""+ fail_text: Exception | None = None+ fail_download: Exception | None = None+ text_urls: list[str] = field(default_factory=list)+ download_urls: list[str] = field(default_factory=list)+ progress_ticks: list[tuple[int, int | None]] = field(default_factory=list)++ async def get_text(self, url: str, *, max_bytes: int) -> str:+ self.text_urls.append(url)+ if self.fail_text is not None:+ raise self.fail_text+ if len(self.manifest.encode("utf-8")) > max_bytes:+ raise AssertionError("the fake manifest exceeds the caller's cap")+ return self.manifest++ async def download(+ self,+ url: str,+ dest: Path,+ *,+ max_bytes: int,+ on_progress: Callable[[int, int | None], None] | None = None,+ ) -> int:+ self.download_urls.append(url)+ if self.fail_download is not None:+ raise self.fail_download+ from jarvis.core.installer_update import InstallerUpdateError++ if len(self.payload) > max_bytes:+ # Mirrors the real streaming guard: the partial file is left for the+ # caller to discard, exactly as httpx would leave it.+ _write(dest, self.payload[:max_bytes])+ raise InstallerUpdateError(+ f"installer download exceeded {max_bytes} bytes - refusing it"+ )+ # Emit the payload in slices so a test sees a real ramp, not one 100%+ # tick — the shape a progress bar is actually built against.+ total = len(self.payload)+ if on_progress is not None:+ step = max(1, total // 4) if total else 1+ for written in range(0, total, step):+ on_progress(written, total)+ self.progress_ticks.append((written, total))+ _write(dest, self.payload)+ if on_progress is not None:+ on_progress(total, total)+ self.progress_ticks.append((total, total))+ return total+++@dataclass(frozen=True)+class RunResult:+ """What a faked command "returned"."""++ returncode: int = 0+ stdout: str = ""+ stderr: str = ""+++@dataclass+class FakeCommandRunner:+ """Records commands instead of running them.++ ``on_run`` lets a test give one command a side effect — mounting a DMG, for+ instance, is modelled by creating the app bundle inside the mountpoint the+ caller passed on the command line.+ """++ results: dict[str, RunResult] = field(default_factory=dict)+ on_run: Callable[[Sequence[str]], None] | None = None+ spawn_error: OSError | None = None+ ran: list[list[str]] = field(default_factory=list)+ spawned: list[list[str]] = field(default_factory=list)++ def run(self, command: Sequence[str], *, timeout_s: float) -> tuple[int, str, str]:+ recorded = list(command)+ self.ran.append(recorded)+ if self.on_run is not None:+ self.on_run(recorded)+ result = self._result_for(recorded)+ return result.returncode, result.stdout, result.stderr++ def spawn_detached(self, command: Sequence[str]) -> None:+ if self.spawn_error is not None:+ raise self.spawn_error+ self.spawned.append(list(command))++ def _result_for(self, command: Sequence[str]) -> RunResult:+ # Keyed by the sub-command ("attach", "detach") when there is one, else+ # by the executable, so a test can steer hdiutil's two calls apart.+ for key in (+ " ".join(command[:2]),+ command[1] if len(command) > 1 else "",+ command[0],+ ):+ if key and key in self.results:+ return self.results[key]+ return RunResult()diff --git a/tests/unit/core/test_installer_update.py b/tests/unit/core/test_installer_update.pynew file mode 100644index 0000000000..92775618ea--- /dev/null+++ b/tests/unit/core/test_installer_update.py@@ -0,0 +1,378 @@+"""``jarvis.core.installer_update`` — the frozen-install self-update.++The whole point of these tests is that the dangerous half of an updater is+provable offline: which asset a machine picks, whether a mismatching SHA-256+really refuses, and what exactly gets executed on each OS. Network and process+spawning arrive through the fakes in ``tests/fakes/fake_installer_update.py``,+so every case below runs on Windows, macOS and Linux alike.+"""++from __future__ import annotations++import hashlib+from pathlib import Path++import pytest++from jarvis.core.installer_update import (+ CHECKSUMS_ASSET_NAME,+ InstallerAsset,+ InstallerUpdateError,+ apply_installer,+ download_and_verify,+ installer_asset_name,+ parse_sha256sums,+ select_asset,+ select_installer_asset,+)+from tests.fakes.fake_installer_update import (+ FakeAssetFetcher,+ FakeCommandRunner,+ RunResult,+)++PAYLOAD = b"not really an installer, but it hashes just as well"+PAYLOAD_SHA256 = hashlib.sha256(PAYLOAD).hexdigest()+++def _asset(name: str, size: int = len(PAYLOAD)) -> InstallerAsset:+ return InstallerAsset(name=name, url=f"https://example.invalid/{name}", size=size)+++def _release_assets(*names: str) -> list[dict[str, object]]:+ return [+ {+ "name": name,+ "browser_download_url": f"https://example.invalid/{name}",+ "size": len(PAYLOAD),+ }+ for name in names+ ]+++# --------------------------------------------------------------------------- #+# Asset naming+# --------------------------------------------------------------------------- #+ ("platform_name", "machine", "expected"),+ [+ ("win32", "AMD64", "PersonalJarvis-Setup-x64.exe"),+ ("win32", "x86_64", "PersonalJarvis-Setup-x64.exe"),+ ("darwin", "arm64", "PersonalJarvis-macOS-arm64.dmg"),+ ("darwin", "x86_64", "PersonalJarvis-macOS-x64.dmg"),+ ("linux", "x86_64", "PersonalJarvis-Linux-x86_64.AppImage"),+ ("linux2", "AMD64", "PersonalJarvis-Linux-x86_64.AppImage"),+ ],+)+def test_installer_asset_name_matches_the_release_contract(+ platform_name: str, machine: str, expected: str+) -> None:+ assert installer_asset_name(platform_name, machine) == expected+++ ("platform_name", "machine"),+ [+ ("win32", "ARM64"), # no Windows-on-ARM installer is published+ ("linux", "aarch64"),+ ("freebsd", "x86_64"),+ ],+)+def test_unsupported_platforms_have_no_asset(platform_name: str, machine: str) -> None:+ # Fail closed: no name means the caller reports "not available here" rather+ # than downloading something built for another machine.+ assert installer_asset_name(platform_name, machine) is None+++def test_select_installer_asset_picks_this_machines_file() -> None:+ assets = _release_assets(+ "PersonalJarvis-Setup-x64.exe",+ "PersonalJarvis-macOS-arm64.dmg",+ CHECKSUMS_ASSET_NAME,+ )+ picked = select_installer_asset(assets, platform_name="darwin", machine="arm64")+ assert picked is not None+ assert picked.name == "PersonalJarvis-macOS-arm64.dmg"+++def test_select_asset_rejects_a_non_https_url() -> None:+ assets = [{"name": "x.exe", "browser_download_url": "http://example.invalid/x.exe"}]+ assert select_asset(assets, "x.exe") is None+++def test_select_asset_ignores_malformed_entries() -> None:+ assets = ["not-a-dict", {"name": "x.exe"}, *_release_assets("x.exe")]+ picked = select_asset(assets, "x.exe")+ # The first two entries are unusable; the well-formed one still wins.+ assert picked is None or picked.name == "x.exe"+++# --------------------------------------------------------------------------- #+# Checksum manifest+# --------------------------------------------------------------------------- #+def test_parse_sha256sums_handles_both_sha256sum_markers() -> None:+ text = (+ f"{PAYLOAD_SHA256} PersonalJarvis-Setup-x64.exe\n"+ f"{PAYLOAD_SHA256} *PersonalJarvis-Linux-x86_64.AppImage\n"+ )+ parsed = parse_sha256sums(text)+ assert parsed["PersonalJarvis-Setup-x64.exe"] == PAYLOAD_SHA256+ assert parsed["PersonalJarvis-Linux-x86_64.AppImage"] == PAYLOAD_SHA256+++def test_parse_sha256sums_skips_junk_without_losing_good_lines() -> None:+ text = (+ "# a comment\n"+ "\n"+ "not-a-digest PersonalJarvis-Setup-x64.exe\n"+ "zz" + "0" * 62 + " bad-hex.exe\n"+ f"{PAYLOAD_SHA256} dist/installers/PersonalJarvis-Setup-x64.exe\n"+ )+ parsed = parse_sha256sums(text)+ # The path prefix is stripped so a manifest produced inside a directory+ # still matches the flat asset name.+ assert parsed == {"PersonalJarvis-Setup-x64.exe": PAYLOAD_SHA256}+++# --------------------------------------------------------------------------- #+# Download + verification+# --------------------------------------------------------------------------- #+async def test_download_and_verify_returns_the_file_on_a_matching_digest(+ tmp_path: Path,+) -> None:+ asset = _asset("PersonalJarvis-Setup-x64.exe")+ fetcher = FakeAssetFetcher(manifest=f"{PAYLOAD_SHA256} {asset.name}\n", payload=PAYLOAD)+ result = await download_and_verify(+ asset, _asset(CHECKSUMS_ASSET_NAME), dest_dir=tmp_path, fetcher=fetcher+ )+ assert result == tmp_path / asset.name+ assert result.read_bytes() == PAYLOAD+++async def test_download_and_verify_refuses_a_mismatching_digest(tmp_path: Path) -> None:+ asset = _asset("PersonalJarvis-Setup-x64.exe")+ wrong = hashlib.sha256(b"something else entirely").hexdigest()+ fetcher = FakeAssetFetcher(manifest=f"{wrong} {asset.name}\n", payload=PAYLOAD)++ with pytest.raises(InstallerUpdateError, match="SHA-256"):+ await download_and_verify(+ asset, _asset(CHECKSUMS_ASSET_NAME), dest_dir=tmp_path, fetcher=fetcher+ )+ # Nothing unverified may survive where a later step could execute it.+ assert not (tmp_path / asset.name).exists()+++async def test_download_and_verify_refuses_when_the_manifest_omits_the_asset(+ tmp_path: Path,+) -> None:+ asset = _asset("PersonalJarvis-Setup-x64.exe")+ fetcher = FakeAssetFetcher(+ manifest=f"{PAYLOAD_SHA256} PersonalJarvis-macOS-arm64.dmg\n", payload=PAYLOAD+ )+ with pytest.raises(InstallerUpdateError, match="no entry"):+ await download_and_verify(+ asset, _asset(CHECKSUMS_ASSET_NAME), dest_dir=tmp_path, fetcher=fetcher+ )+++async def test_download_and_verify_refuses_an_oversized_asset(tmp_path: Path) -> None:+ asset = _asset("PersonalJarvis-Setup-x64.exe", size=10_000)+ fetcher = FakeAssetFetcher(manifest=f"{PAYLOAD_SHA256} {asset.name}\n", payload=PAYLOAD)+ with pytest.raises(InstallerUpdateError, match="cap"):+ await download_and_verify(+ asset,+ _asset(CHECKSUMS_ASSET_NAME),+ dest_dir=tmp_path,+ fetcher=fetcher,+ max_bytes=1_000,+ )+ assert not (tmp_path / asset.name).exists()+++async def test_download_and_verify_reports_a_transport_failure(tmp_path: Path) -> None:+ asset = _asset("PersonalJarvis-Setup-x64.exe")+ fetcher = FakeAssetFetcher(+ manifest=f"{PAYLOAD_SHA256} {asset.name}\n",+ payload=PAYLOAD,+ fail_download=OSError("connection reset"),+ )+ with pytest.raises(InstallerUpdateError, match="connection reset"):+ await download_and_verify(+ asset, _asset(CHECKSUMS_ASSET_NAME), dest_dir=tmp_path, fetcher=fetcher+ )+++async def test_download_and_verify_reports_a_missing_manifest(tmp_path: Path) -> None:+ asset = _asset("PersonalJarvis-Setup-x64.exe")+ fetcher = FakeAssetFetcher(fail_text=OSError("404"), payload=PAYLOAD)+ with pytest.raises(InstallerUpdateError, match=CHECKSUMS_ASSET_NAME):+ await download_and_verify(+ asset, _asset(CHECKSUMS_ASSET_NAME), dest_dir=tmp_path, fetcher=fetcher+ )+++# --------------------------------------------------------------------------- #+# Windows handover+# --------------------------------------------------------------------------- #+def test_windows_handover_runs_the_silent_in_place_upgrade(tmp_path: Path) -> None:+ installer = tmp_path / "PersonalJarvis-Setup-x64.exe"+ installer.write_bytes(PAYLOAD)+ runner = FakeCommandRunner()++ message = apply_installer(installer, platform_name="win32", runner=runner)++ assert runner.spawned == [+ [+ str(installer),+ "/SILENT",+ "/CLOSEAPPLICATIONS",+ "/RESTARTAPPLICATIONS",+ "/NORESTART",+ ]+ ]+ assert "restarts by itself" in message+++def test_handover_refuses_a_missing_file(tmp_path: Path) -> None:+ with pytest.raises(InstallerUpdateError, match="does not exist"):+ apply_installer(+ tmp_path / "nope.exe",+ platform_name="win32",+ runner=FakeCommandRunner(),+ )+++def test_handover_refuses_an_unsupported_platform(tmp_path: Path) -> None:+ installer = tmp_path / "whatever"+ installer.write_bytes(PAYLOAD)+ with pytest.raises(InstallerUpdateError, match="no installer handover"):+ apply_installer(installer, platform_name="sunos5", runner=FakeCommandRunner())+++# --------------------------------------------------------------------------- #+# macOS handover+# --------------------------------------------------------------------------- #+def _mounting_runner(app_name: str, payload: str) -> FakeCommandRunner:+ """A runner whose ``hdiutil attach`` really populates the mountpoint."""++ def _mount(command: list[str]) -> None:+ if len(command) < 2 or command[1] != "attach":+ return+ mountpoint = Path(command[command.index("-mountpoint") + 1])+ bundle = mountpoint / app_name / "Contents" / "MacOS"+ bundle.mkdir(parents=True, exist_ok=True)+ (bundle / "PersonalJarvis").write_text(payload, encoding="utf-8")++ return FakeCommandRunner(on_run=_mount)+++def test_macos_handover_replaces_the_running_app_and_relaunches(+ tmp_path: Path,+) -> None:+ dmg = tmp_path / "PersonalJarvis-macOS-arm64.dmg"+ dmg.write_bytes(PAYLOAD)+ app = tmp_path / "Applications" / "Personal Jarvis.app"+ (app / "Contents" / "MacOS").mkdir(parents=True)+ (app / "Contents" / "MacOS" / "PersonalJarvis").write_text("old", encoding="utf-8")++ runner = _mounting_runner("Personal Jarvis.app", "new")+ message = apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app)++ assert (app / "Contents" / "MacOS" / "PersonalJarvis").read_text(encoding="utf-8") == "new"+ assert runner.spawned == [["open", "-n", str(app)]]+ # The volume is always released, success or not.+ assert any(cmd[:2] == ["hdiutil", "detach"] for cmd in runner.ran)+ assert "replaced" in message+ # No rollback copy is left behind on success.+ assert not (app.parent / ".Personal Jarvis.app.old").exists()+++def test_macos_handover_keeps_the_old_app_when_the_mount_fails(tmp_path: Path) -> None:+ dmg = tmp_path / "PersonalJarvis-macOS-arm64.dmg"+ dmg.write_bytes(PAYLOAD)+ app = tmp_path / "Applications" / "Personal Jarvis.app"+ (app / "Contents" / "MacOS").mkdir(parents=True)+ (app / "Contents" / "MacOS" / "PersonalJarvis").write_text("old", encoding="utf-8")++ runner = FakeCommandRunner(+ results={"hdiutil attach": RunResult(returncode=1, stderr="no mountable file")}+ )+ with pytest.raises(InstallerUpdateError, match="could not mount"):+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app)++ assert (app / "Contents" / "MacOS" / "PersonalJarvis").read_text(encoding="utf-8") == "old"+ assert runner.spawned == []+++def test_macos_handover_refuses_without_a_resolvable_app(tmp_path: Path) -> None:+ dmg = tmp_path / "PersonalJarvis-macOS-arm64.dmg"+ dmg.write_bytes(PAYLOAD)+ with pytest.raises(InstallerUpdateError, match="locate the running"):+ apply_installer(+ dmg,+ platform_name="darwin",+ runner=FakeCommandRunner(),+ app_path=None,+ )+++def test_macos_handover_falls_back_to_the_only_bundle_on_the_volume(+ tmp_path: Path,+) -> None:+ dmg = tmp_path / "PersonalJarvis-macOS-x64.dmg"+ dmg.write_bytes(PAYLOAD)+ app = tmp_path / "Applications" / "Personal Jarvis.app"+ (app / "Contents").mkdir(parents=True)++ # The DMG names the bundle differently from the installed one; there is+ # still exactly one, so the swap is unambiguous.+ runner = _mounting_runner("Personal Jarvis 2.app", "new")+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app)+ assert (app / "Contents" / "MacOS" / "PersonalJarvis").read_text(encoding="utf-8") == "new"+++# --------------------------------------------------------------------------- #+# Linux handover+# --------------------------------------------------------------------------- #+def test_linux_handover_replaces_the_appimage_in_place(tmp_path: Path) -> None:+ downloaded = tmp_path / "download" / "PersonalJarvis-Linux-x86_64.AppImage"+ downloaded.parent.mkdir()+ downloaded.write_bytes(b"new appimage")+ live = tmp_path / "opt" / "PersonalJarvis.AppImage"+ live.parent.mkdir()+ live.write_bytes(b"old appimage")++ runner = FakeCommandRunner()+ message = apply_installer(downloaded, platform_name="linux", runner=runner, appimage_path=live)++ assert live.read_bytes() == b"new appimage"+ assert runner.spawned == [[str(live)]]+ assert "replaced" in message+ # The staging file must not survive the atomic rename.+ assert not (live.parent / f".{live.name}.new").exists()+++def test_linux_handover_refuses_outside_an_appimage(tmp_path: Path) -> None:+ downloaded = tmp_path / "PersonalJarvis-Linux-x86_64.AppImage"+ downloaded.write_bytes(b"new appimage")+ with pytest.raises(InstallerUpdateError, match=r"\$APPIMAGE"):+ apply_installer(+ downloaded,+ platform_name="linux",+ runner=FakeCommandRunner(),+ appimage_path=None,+ )+++def test_linux_handover_reports_a_failed_relaunch(tmp_path: Path) -> None:+ downloaded = tmp_path / "download.AppImage"+ downloaded.write_bytes(b"new appimage")+ live = tmp_path / "PersonalJarvis.AppImage"+ live.write_bytes(b"old appimage")++ runner = FakeCommandRunner(spawn_error=OSError("exec format error"))+ with pytest.raises(InstallerUpdateError, match="could not be relaunched"):+ apply_installer(downloaded, platform_name="linux", runner=runner, appimage_path=live)+ # The bytes ARE the new version - the failure is only the relaunch, and+ # saying otherwise would send the user looking in the wrong place.+ assert live.read_bytes() == b"new appimage"diff --git a/tests/unit/ui/web/test_update_routes_frozen.py b/tests/unit/ui/web/test_update_routes_frozen.pynew file mode 100644index 0000000000..e702f99763--- /dev/null+++ b/tests/unit/ui/web/test_update_routes_frozen.py@@ -0,0 +1,347 @@+"""The FROZEN branch of ``/api/update`` — native installer self-update.++Kept apart from ``test_update_routes.py`` (which owns the managed/git path) so+the two install kinds cannot silently share a fixture and hide a leak. What is+pinned here:++* ``is_frozen()`` is the ONLY switch. Nothing in the frozen branch reaches for+ git, an install marker or an ``origin`` remote.+* ``status`` stays fail-open and never offers an update the release cannot+ actually deliver (no installer asset, no checksum manifest).+* ``apply`` is fail-closed and never executes anything it did not verify.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import jarvis.ui.web.update_routes as u+from jarvis.core.installer_update import CHECKSUMS_ASSET_NAME, InstallerUpdateError+from jarvis.ui.web.update_routes import router as update_router++SETUP_NAME = "PersonalJarvis-Setup-x64.exe"++[email protected](autouse=True)+def _reset_cache() -> None:+ u._status_cache = None+ u._status_cache_until = 0.0+ u._status_cache_root = None+ u._last_good_release = None+++def client() -> TestClient:+ app = FastAPI()+ app.include_router(update_router)+ return TestClient(app)+++def _release(+ version: str = "1.6.0", *, assets: list[dict[str, Any]] | None = None+) -> dict[str, Any]:+ if assets is None:+ assets = [+ {+ "name": SETUP_NAME,+ "browser_download_url": f"https://example.invalid/{SETUP_NAME}",+ "size": 123,+ },+ {+ "name": CHECKSUMS_ASSET_NAME,+ "browser_download_url": (f"https://example.invalid/{CHECKSUMS_ASSET_NAME}"),+ "size": 90,+ },+ ]+ return {+ "version": version,+ "tag": f"v{version}",+ "notes": "Native installers",+ "published_at": "2026-08-25T00:00:00Z",+ "release_url": f"https://example.invalid/releases/v{version}",+ "assets": assets,+ }+++def _patch_frozen(+ monkeypatch: pytest.MonkeyPatch,+ *,+ frozen: bool = True,+ asset_name: str | None = SETUP_NAME,+ running: str = "1.5.3",+) -> None:+ monkeypatch.setattr(u, "is_frozen", lambda: frozen)+ monkeypatch.setattr(u, "_running_version", lambda: running)+ monkeypatch.setattr(u, "installer_asset_name", lambda _p, _m: asset_name)+++def _patch_latest(monkeypatch: pytest.MonkeyPatch, release: dict[str, Any] | None) -> None:+ async def _fake() -> dict[str, Any] | None:+ return release++ monkeypatch.setattr(u, "_fetch_latest_release", _fake)+++def _forbid_git(monkeypatch: pytest.MonkeyPatch) -> None:+ """Proof that the frozen branch never touches the managed machinery."""++ async def _explode() -> Path | None:+ raise AssertionError("a frozen install must never resolve a git checkout")++ monkeypatch.setattr(u, "_resolve_managed_repo", _explode)+++# --------------------------------------------------------------------------- #+# GET /api/update/status+# --------------------------------------------------------------------------- #+def test_status_offers_a_newer_installer(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _forbid_git(monkeypatch)+ _patch_latest(monkeypatch, _release("1.6.0"))++ body = client.get("/api/update/status").json()++ assert body["kind"] == "frozen"+ # `managed` is what the top bar gates the button on; a frozen install CAN+ # update itself, so it must be true here.+ assert body["managed"] is True+ assert body["update_available"] is True+ assert body["latest"] == "1.6.0"+ assert body["asset"]["name"] == SETUP_NAME+ assert body["notes"] == "Native installers"+ # Fields the managed path fills stay present so the UI reads one shape.+ assert body["pending_update"] is None+ assert body["last_result"] is None+++def test_status_same_version_offers_nothing(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch, running="1.6.0")+ _patch_latest(monkeypatch, _release("1.6.0"))+ body = client.get("/api/update/status").json()+ assert body["update_available"] is False+ assert body["notes"] is None+++def test_status_without_an_installer_asset_offers_nothing(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ # A code-only release: newer version, but no installer to hand the user.+ _patch_latest(monkeypatch, _release("1.6.0", assets=[]))+ body = client.get("/api/update/status").json()+ assert body["update_available"] is False+ assert body["asset"] is None+++def test_status_without_a_checksum_manifest_offers_nothing(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(+ monkeypatch,+ _release(+ "1.6.0",+ assets=[+ {+ "name": SETUP_NAME,+ "browser_download_url": f"https://example.invalid/{SETUP_NAME}",+ "size": 123,+ }+ ],+ ),+ )+ body = client.get("/api/update/status").json()+ # apply would refuse an unverifiable download, so status must not offer it.+ assert body["update_available"] is False+++def test_status_on_an_unsupported_platform_hides_the_button(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch, asset_name=None)+ _patch_latest(monkeypatch, _release("1.6.0"))+ body = client.get("/api/update/status").json()+ assert body["managed"] is False+ assert body["unsupported_platform"] is True+ assert body["update_available"] is False+++def test_status_network_failure_is_fail_open(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(monkeypatch, None)+ body = client.get("/api/update/status").json()+ assert body["check_failed"] is True+ assert body["update_available"] is False+ assert body["kind"] == "frozen"+++def test_non_frozen_status_keeps_the_managed_shape(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ # The dev tree must be completely unaffected by the frozen branch.+ monkeypatch.setattr(u, "is_frozen", lambda: False)+ monkeypatch.setattr(u, "_running_version", lambda: "1.5.3")++ async def _no_repo() -> Path | None:+ return None++ monkeypatch.setattr(u, "_resolve_managed_repo", _no_repo)+ body = client.get("/api/update/status").json()+ assert body["managed"] is False+ assert body["kind"] == "dev"+++# --------------------------------------------------------------------------- #+# POST /api/update/apply+# --------------------------------------------------------------------------- #+def _capture_install(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:+ """Replace download + handover with recorders; return what they saw."""+ seen: dict[str, Any] = {}++ def _write_verified(dest_dir: Path, name: str) -> Path:+ """Blocking write, kept out of the async body (ruff ASYNC240)."""+ dest_dir.mkdir(parents=True, exist_ok=True)+ path = dest_dir / name+ path.write_bytes(b"verified installer")+ return path++ async def _download(asset: Any, checksums: Any, *, dest_dir: Path) -> Path:+ seen["asset"] = asset+ seen["checksums"] = checksums+ return _write_verified(dest_dir, asset.name)++ def _apply(installer: Path) -> str:+ seen["installer"] = installer+ return "the Windows installer is running"++ monkeypatch.setattr(u, "download_and_verify", _download)+ monkeypatch.setattr(u, "apply_installer", _apply)+ return seen+++def test_apply_downloads_verifies_and_hands_over(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _forbid_git(monkeypatch)+ _patch_latest(monkeypatch, _release("1.6.0"))+ seen = _capture_install(monkeypatch)++ response = client.post("/api/update/apply")+ body = response.json()++ assert response.status_code == 200+ assert body["ok"] is True+ assert body["kind"] == "frozen"+ assert body["version"] == "1.6.0"+ assert body["release_tag"] == "v1.6.0"+ # The handover restarts the app; the caller must not restart on top of it.+ assert body["restart_required"] is False+ assert seen["asset"].name == SETUP_NAME+ assert seen["checksums"].name == CHECKSUMS_ASSET_NAME+ assert seen["installer"].name == SETUP_NAME+++def test_apply_refuses_when_nothing_newer_is_published(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch, running="1.6.0")+ _patch_latest(monkeypatch, _release("1.6.0"))+ assert client.post("/api/update/apply").status_code == 409+++def test_apply_refuses_without_a_checksum_manifest(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(+ monkeypatch,+ _release(+ "1.6.0",+ assets=[+ {+ "name": SETUP_NAME,+ "browser_download_url": f"https://example.invalid/{SETUP_NAME}",+ "size": 123,+ }+ ],+ ),+ )++ def _never(installer: Path) -> str:+ raise AssertionError("nothing may be executed without a checksum manifest")++ monkeypatch.setattr(u, "apply_installer", _never)++ response = client.post("/api/update/apply")+ assert response.status_code == 502+ assert CHECKSUMS_ASSET_NAME in response.json()["detail"]+++def test_apply_refuses_when_the_release_has_no_installer(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(monkeypatch, _release("1.6.0", assets=[]))+ response = client.post("/api/update/apply")+ assert response.status_code == 502+ assert SETUP_NAME in response.json()["detail"]+++def test_apply_surfaces_a_verification_failure(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(monkeypatch, _release("1.6.0"))++ async def _download(asset: Any, checksums: Any, *, dest_dir: Path) -> Path:+ raise InstallerUpdateError("PersonalJarvis-Setup-x64.exe failed its SHA-256 check")++ def _never(installer: Path) -> str:+ raise AssertionError("a failed verification must never reach the handover")++ monkeypatch.setattr(u, "download_and_verify", _download)+ monkeypatch.setattr(u, "apply_installer", _never)++ response = client.post("/api/update/apply")+ assert response.status_code == 502+ assert "SHA-256" in response.json()["detail"]+++def test_apply_on_an_unsupported_platform_is_501(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch, asset_name=None)+ _patch_latest(monkeypatch, _release("1.6.0"))+ assert client.post("/api/update/apply").status_code == 501+++def test_apply_offline_is_502(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(monkeypatch, None)+ assert client.post("/api/update/apply").status_code == 502+++def test_apply_falls_back_to_the_last_good_release(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_frozen(monkeypatch)+ _patch_latest(monkeypatch, None)+ u._last_good_release = _release("1.6.0")+ seen = _capture_install(monkeypatch)++ response = client.post("/api/update/apply")++ assert response.status_code == 200+ assert seen["asset"].name == SETUP_NAMEdiff --git a/tests/unit/web/test_update_progress.py b/tests/unit/web/test_update_progress.pynew file mode 100644index 0000000000..6beb2622ec--- /dev/null+++ b/tests/unit/web/test_update_progress.py@@ -0,0 +1,229 @@+"""The update progress tracker: the percentage behind "Updating 70%".++What matters here is not that a number exists but that it is *trustworthy*. The+bar is what a user decides "is this stuck, should I kill it?" from, so these+tests pin the three properties that make it worth looking at:++* it moves on real evidence (download bytes, git's own object counters),+* it never rewinds, even though git reports two separate 0→100 % counters,+* and it always reaches a terminal state — a run that dies without a verdict+ would leave the button reading "Updating 42%" forever.+"""++from __future__ import annotations++import pytest++from jarvis.ui.web.update_routes import (+ INSTALL_KIND_FROZEN,+ INSTALL_KIND_MANAGED,+ PHASE_DOWNLOADING,+ PHASE_FAILED,+ PHASE_IDLE,+ PHASE_INSTALLING,+ PHASE_READY,+ PHASE_RESOLVING,+ PHASE_VERIFYING,+ _human_bytes,+ _on_git_progress,+ _progress,+ _UpdateProgress,+)+++def tracker() -> _UpdateProgress:+ return _UpdateProgress()+++# --------------------------------------------------------------------------- #+# The phase model+# --------------------------------------------------------------------------- #+def test_idle_before_anything_runs(tracker: _UpdateProgress) -> None:+ snapshot = tracker.snapshot()+ assert snapshot["phase"] == PHASE_IDLE+ assert snapshot["percent"] == 0+ assert snapshot["active"] is False+++def test_download_percentage_follows_the_bytes(tracker: _UpdateProgress) -> None:+ """Half the bytes must land halfway through the download's window."""+ tracker.begin(INSTALL_KIND_FROZEN)+ tracker.enter(PHASE_DOWNLOADING)+ start = tracker.percent+ tracker.advance(PHASE_DOWNLOADING, 1.0)+ end = tracker.percent++ tracker2 = _UpdateProgress()+ tracker2.begin(INSTALL_KIND_FROZEN)+ tracker2.advance(PHASE_DOWNLOADING, 0.5)+ assert tracker2.percent == pytest.approx((start + end) / 2, abs=1)+++def test_phases_run_forward_to_a_hundred(tracker: _UpdateProgress) -> None:+ tracker.begin(INSTALL_KIND_FROZEN)+ seen = [tracker.percent]+ for phase in (PHASE_RESOLVING, PHASE_DOWNLOADING, PHASE_VERIFYING, PHASE_INSTALLING):+ tracker.advance(phase, 1.0)+ seen.append(tracker.percent)+ tracker.finish(version="1.3.0", restart_required=False)+ seen.append(tracker.percent)++ assert seen == sorted(seen), f"the bar went backwards: {seen}"+ assert seen[-1] == 100+++def test_percentage_never_rewinds(tracker: _UpdateProgress) -> None:+ """git restarts its counter at 0 % for delta resolution; the bar must not."""+ tracker.begin(INSTALL_KIND_MANAGED)+ tracker.advance(PHASE_DOWNLOADING, 0.9)+ high = tracker.percent+ tracker.advance(PHASE_DOWNLOADING, 0.1)+ assert tracker.percent == high+++def test_begin_is_the_only_reset(tracker: _UpdateProgress) -> None:+ tracker.begin(INSTALL_KIND_FROZEN)+ tracker.advance(PHASE_INSTALLING, 1.0)+ assert tracker.percent == 100+ tracker.begin(INSTALL_KIND_FROZEN)+ assert tracker.percent == 0+ assert tracker.phase == PHASE_RESOLVING+++def test_out_of_range_fractions_are_clamped(tracker: _UpdateProgress) -> None:+ """A bogus Content-Length must not produce a 400 %-wide bar."""+ tracker.begin(INSTALL_KIND_FROZEN)+ tracker.advance(PHASE_DOWNLOADING, 4.0)+ assert tracker.percent <= 100+ tracker.begin(INSTALL_KIND_FROZEN)+ tracker.advance(PHASE_DOWNLOADING, -1.0)+ assert tracker.percent >= 0+++def test_the_two_install_kinds_weight_the_phases_differently(+ tracker: _UpdateProgress,+) -> None:+ """A frozen install is dominated by its download; a managed one is not."""+ tracker.begin(INSTALL_KIND_FROZEN)+ tracker.advance(PHASE_DOWNLOADING, 1.0)+ frozen_after_download = tracker.percent++ managed = _UpdateProgress()+ managed.begin(INSTALL_KIND_MANAGED)+ managed.advance(PHASE_DOWNLOADING, 1.0)++ assert frozen_after_download > managed.percent+++def test_an_unknown_phase_leaves_the_bar_alone(tracker: _UpdateProgress) -> None:+ """A future phase id must never zero the bar an install is being judged by."""+ tracker.begin(INSTALL_KIND_FROZEN)+ tracker.advance(PHASE_DOWNLOADING, 1.0)+ before = tracker.percent+ tracker.advance("something-new", 0.5)+ assert tracker.percent == before+++# --------------------------------------------------------------------------- #+# Terminal states+# --------------------------------------------------------------------------- #+def test_finish_reports_ready_and_stops_being_active(tracker: _UpdateProgress) -> None:+ tracker.begin(INSTALL_KIND_MANAGED)+ tracker.finish(version="1.3.0", restart_required=True)+ snapshot = tracker.snapshot()+ assert snapshot["phase"] == PHASE_READY+ assert snapshot["percent"] == 100+ assert snapshot["active"] is False+ assert snapshot["restart_required"] is True+ assert snapshot["version"] == "1.3.0"+++def test_failure_keeps_the_percentage_and_carries_the_reason(+ tracker: _UpdateProgress,+) -> None:+ """Where it died is diagnostic; zeroing it would throw that away."""+ tracker.begin(INSTALL_KIND_FROZEN)+ tracker.advance(PHASE_DOWNLOADING, 0.5)+ midway = tracker.percent+ tracker.fail("git fetch failed: could not resolve host")++ snapshot = tracker.snapshot()+ assert snapshot["phase"] == PHASE_FAILED+ assert snapshot["percent"] == midway+ assert snapshot["active"] is False+ assert "could not resolve host" in str(snapshot["error"])+++def test_a_failure_message_cannot_flood_the_ui(tracker: _UpdateProgress) -> None:+ tracker.begin(INSTALL_KIND_FROZEN)+ tracker.fail("x" * 5000)+ assert len(str(tracker.snapshot()["error"])) <= 300+++def test_finish_clears_an_earlier_error(tracker: _UpdateProgress) -> None:+ """A retry that works must not keep showing the previous run's failure."""+ tracker.begin(INSTALL_KIND_MANAGED)+ tracker.fail("network unreachable")+ tracker.begin(INSTALL_KIND_MANAGED)+ tracker.finish(version="1.3.0", restart_required=True)+ assert tracker.snapshot()["error"] is None+++# --------------------------------------------------------------------------- #+# git's progress lines+# --------------------------------------------------------------------------- #+ "line",+ [+ "Receiving objects: 43% (430/1000), 1.2 MiB | 500 KiB/s",+ "Receiving objects: 100% (1000/1000), 12.00 MiB | 3.00 MiB/s, done.",+ "Resolving deltas: 50% (6/12)",+ ],+)+def test_real_git_lines_move_the_bar(line: str) -> None:+ _progress.begin(INSTALL_KIND_MANAGED)+ _progress.enter(PHASE_DOWNLOADING)+ before = _progress.percent+ _on_git_progress(line)+ assert _progress.percent > before+++def test_git_noise_is_ignored() -> None:+ _progress.begin(INSTALL_KIND_MANAGED)+ _progress.enter(PHASE_DOWNLOADING)+ before = _progress.percent+ for line in (+ "remote: Enumerating objects: 1000, done.",+ "From https://github.com/example/repo",+ " * [new tag] v1.3.0 -> v1.3.0",+ "",+ ):+ _on_git_progress(line)+ assert _progress.percent == before+++def test_delta_resolution_ranks_above_receiving() -> None:+ """The two counters are sequential stages, not competing measurements."""+ _progress.begin(INSTALL_KIND_MANAGED)+ _progress.enter(PHASE_DOWNLOADING)+ _on_git_progress("Receiving objects: 100% (1000/1000), done.")+ received = _progress.percent+ _on_git_progress("Resolving deltas: 100% (12/12), done.")+ assert _progress.percent > received+++# --------------------------------------------------------------------------- #+# Formatting+# --------------------------------------------------------------------------- #+ ("count", "expected"),+ [(0, "0 B"), (512, "512 B"), (128_000, "125 KB"), (134_217_728, "128.0 MB")],+)+def test_human_bytes(count: int, expected: str) -> None:+ assert _human_bytes(count) == expected+++def test_human_bytes_stays_short() -> None:+ """It renders inside a top-bar pill, so it must never grow unbounded."""+ assert len(_human_bytes(1_500_000_000)) <= 10diff --git a/tests/unit/web/test_update_progress_route.py b/tests/unit/web/test_update_progress_route.pynew file mode 100644index 0000000000..916a7dcaa5--- /dev/null+++ b/tests/unit/web/test_update_progress_route.py@@ -0,0 +1,246 @@+"""The progress side channel, end to end: bytes -> tracker -> HTTP.++``POST /api/update/apply`` is one long request, so the percentage can only reach+the UI over a second endpoint polled meanwhile. These tests prove that channel+carries real measurements rather than a decorative animation, and that the apply+route cannot leave it stuck "active" forever.+"""++from __future__ import annotations++import asyncio+import hashlib+from pathlib import Path++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient++from jarvis.core.installer_update import InstallerAsset, download_and_verify+from jarvis.ui.web import update_routes+from jarvis.ui.web.update_routes import (+ INSTALL_KIND_FROZEN,+ PHASE_DOWNLOADING,+ PHASE_FAILED,+ PHASE_IDLE,+ _progress,+ router,+)+from tests.fakes.fake_installer_update import FakeAssetFetcher+++def client() -> TestClient:+ app = FastAPI()+ app.include_router(router)+ return TestClient(app)++[email protected](autouse=True)+def _reset_tracker() -> None:+ """The tracker is process-global; leaving state behind would leak between tests."""+ _progress.__init__() # type: ignore[misc]+++# --------------------------------------------------------------------------- #+# The route+# --------------------------------------------------------------------------- #+def test_progress_answers_even_when_nothing_is_running(client: TestClient) -> None:+ """The UI polls this on every click; it must never 404 or 500."""+ body = client.get("/api/update/progress").json()+ assert body["phase"] == PHASE_IDLE+ assert body["active"] is False+ assert body["percent"] == 0+ assert body["error"] is None+++def test_progress_publishes_the_live_state(client: TestClient) -> None:+ _progress.begin(INSTALL_KIND_FROZEN)+ _progress.advance(PHASE_DOWNLOADING, 0.5, detail="64.0 MB / 128.0 MB")++ body = client.get("/api/update/progress").json()+ assert body["active"] is True+ assert body["phase"] == PHASE_DOWNLOADING+ assert 0 < body["percent"] < 100+ assert body["detail"] == "64.0 MB / 128.0 MB"+ assert body["kind"] == INSTALL_KIND_FROZEN+++def test_progress_shape_is_stable(client: TestClient) -> None:+ """The UI binds to these fields; losing one silently blanks the bar."""+ body = client.get("/api/update/progress").json()+ assert set(body) == {+ "active",+ "phase",+ "percent",+ "detail",+ "version",+ "kind",+ "error",+ "restart_required",+ "started_at",+ "updated_at",+ }+++# --------------------------------------------------------------------------- #+# The apply route's guarantees+# --------------------------------------------------------------------------- #+def test_a_second_apply_is_refused_while_one_runs(client: TestClient) -> None:+ """Two downloads would fight over the temp dir and scramble the percentage."""++ async def hold() -> None:+ async with update_routes._apply_lock:+ await asyncio.sleep(0.3)++ async def scenario() -> int:+ task = asyncio.create_task(hold())+ await asyncio.sleep(0.05)+ try:+ await update_routes.update_apply()+ except HTTPException as exc:+ return exc.status_code+ finally:+ await task+ return 200++ assert asyncio.run(scenario()) == 409+++def test_a_failed_apply_always_leaves_a_verdict(monkeypatch: pytest.MonkeyPatch) -> None:+ """Without this the button reads "Updating 42%" until the app is restarted."""++ async def boom() -> dict[str, object]:+ _progress.begin(INSTALL_KIND_FROZEN)+ _progress.advance(PHASE_DOWNLOADING, 0.42)+ raise RuntimeError("the disk went away")++ monkeypatch.setattr(update_routes, "is_frozen", lambda: True)+ monkeypatch.setattr(update_routes, "_apply_frozen", boom)++ with pytest.raises(RuntimeError):+ asyncio.run(update_routes.update_apply())++ snapshot = _progress.snapshot()+ assert snapshot["phase"] == PHASE_FAILED+ assert snapshot["active"] is False+ assert "the disk went away" in str(snapshot["error"])+++def test_an_http_failure_records_the_servers_own_reason(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def refuse() -> dict[str, object]:+ raise HTTPException(status_code=502, detail="git fetch failed: host unreachable")++ monkeypatch.setattr(update_routes, "is_frozen", lambda: True)+ monkeypatch.setattr(update_routes, "_apply_frozen", refuse)++ with pytest.raises(HTTPException):+ asyncio.run(update_routes.update_apply())++ assert "host unreachable" in str(_progress.snapshot()["error"])+++def test_the_lock_is_released_after_a_failure(monkeypatch: pytest.MonkeyPatch) -> None:+ """A lock held by a crashed apply would make the button dead until restart."""++ async def refuse() -> dict[str, object]:+ raise HTTPException(status_code=502, detail="nope")++ monkeypatch.setattr(update_routes, "is_frozen", lambda: True)+ monkeypatch.setattr(update_routes, "_apply_frozen", refuse)++ async def scenario() -> bool:+ with pytest.raises(HTTPException):+ await update_routes.update_apply()+ return update_routes._apply_lock.locked()++ assert asyncio.run(scenario()) is False+++# --------------------------------------------------------------------------- #+# Real bytes reach the tracker+# --------------------------------------------------------------------------- #+def test_the_downloader_reports_a_ramp_not_one_jump(tmp_path: Path) -> None:+ payload = b"installer-bytes" * 4096+ digest = hashlib.sha256(payload).hexdigest()+ fetcher = FakeAssetFetcher(+ manifest=f"{digest} PersonalJarvis-Setup-x64.exe\n", payload=payload+ )+ asset = InstallerAsset(+ name="PersonalJarvis-Setup-x64.exe", url="https://x/i.exe", size=len(payload)+ )+ checksums = InstallerAsset(name="installers-SHA256SUMS.txt", url="https://x/s.txt", size=64)++ seen: list[tuple[int, int | None]] = []+ asyncio.run(+ download_and_verify(+ asset,+ checksums,+ dest_dir=tmp_path,+ fetcher=fetcher,+ on_progress=lambda written, total: seen.append((written, total)),+ )+ )++ assert len(seen) > 1, "a single 100% tick is not a progress bar"+ assert [w for w, _ in seen] == sorted(w for w, _ in seen)+ assert seen[-1] == (len(payload), len(payload))+ assert all(total == len(payload) for _, total in seen)+++def test_an_unknown_total_falls_back_to_the_release_metadata(tmp_path: Path) -> None:+ """A server with no Content-Length must still yield a real percentage."""+ payload = b"x" * 2048+ digest = hashlib.sha256(payload).hexdigest()++ class NoLengthFetcher(FakeAssetFetcher):+ async def download(+ self,+ url: str,+ dest: Path,+ *,+ max_bytes: int,+ on_progress: object = None,+ **_: object,+ ) -> int:+ # Blocking write kept out of the async body (ruff ASYNC240), same+ # as the shared fake does.+ await asyncio.to_thread(dest.write_bytes, self.payload)+ if callable(on_progress):+ on_progress(len(self.payload), None) # server stated no total+ return len(self.payload)++ seen: list[tuple[int, int | None]] = []+ asyncio.run(+ download_and_verify(+ InstallerAsset(name="i.exe", url="https://x/i.exe", size=len(payload)),+ InstallerAsset(name="s.txt", url="https://x/s.txt", size=64),+ dest_dir=tmp_path,+ fetcher=NoLengthFetcher(manifest=f"{digest} i.exe\n", payload=payload),+ on_progress=lambda written, total: seen.append((written, total)),+ )+ )++ assert seen == [(len(payload), len(payload))]+++def test_a_raising_progress_callback_never_fails_the_download(tmp_path: Path) -> None:+ """Progress is cosmetic; a 400 MB transfer must not die for a bad lambda."""+ payload = b"payload" * 1024+ digest = hashlib.sha256(payload).hexdigest()++ def explode(_written: int, _total: int | None) -> None:+ raise ValueError("the UI store went away")++ result = asyncio.run(+ download_and_verify(+ InstallerAsset(name="i.exe", url="https://x/i.exe", size=len(payload)),+ InstallerAsset(name="s.txt", url="https://x/s.txt", size=64),+ dest_dir=tmp_path,+ fetcher=FakeAssetFetcher(manifest=f"{digest} i.exe\n", payload=payload),+ on_progress=explode,+ )+ )+ assert result.read_bytes() == payloaddiff --git a/tests/unit/web/test_update_subprocess_stream.py b/tests/unit/web/test_update_subprocess_stream.pynew file mode 100644index 0000000000..03591f2a7f--- /dev/null+++ b/tests/unit/web/test_update_subprocess_stream.py@@ -0,0 +1,151 @@+"""The updater's subprocess helper, now that it taps stderr live.++Reading git's progress counters while the fetch runs meant replacing+``communicate()`` with two concurrent pipe readers. That is the kind of change+that works in a unit test and deadlocks in the field, so these tests use REAL+child processes and deliberately noisy output:++* both pipes must drain concurrently — a child that fills stderr while we read+ stdout hangs forever,+* git redraws its counter with a carriage return, so ``\\r`` has to end a+ segment just like ``\\n``,+* and the existing contract (return code, decoding, timeout, missing binary)+ must survive untouched, because every other git call in the updater uses it.+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path++import pytest++from jarvis.ui.web.update_routes import _run+++def _python(code: str) -> list[str]:+ return [sys.executable, "-c", code]+++def _call(cmd: list[str], *, timeout_s: float = 30.0, tap: object = None):+ return asyncio.run(+ _run(cmd, cwd=Path.cwd(), timeout_s=timeout_s, on_stderr_line=tap) # type: ignore[arg-type]+ )+++# --------------------------------------------------------------------------- #+# The existing contract+# --------------------------------------------------------------------------- #+def test_stdout_and_returncode_are_unchanged() -> None:+ rc, out, _err = _call(_python("print('hello')"))+ assert rc == 0+ assert out == "hello"+++def test_stderr_is_still_returned_whole() -> None:+ rc, _out, err = _call(_python("import sys; sys.stderr.write('boom'); sys.exit(3)"))+ assert rc == 3+ assert err == "boom"+++def test_a_missing_binary_reports_minus_one() -> None:+ rc, _out, err = _call(["definitely-not-a-real-binary-xyz"])+ assert rc == -1+ assert "could not run" in err+++def test_a_timeout_reports_minus_one_and_kills_the_child() -> None:+ rc, _out, err = _call(_python("import time; time.sleep(30)"), timeout_s=0.5)+ assert rc == -1+ assert "timed out" in err+++# --------------------------------------------------------------------------- #+# The live tap+# --------------------------------------------------------------------------- #+def test_carriage_returns_end_a_segment() -> None:+ """git redraws its counter with \\r, so \\n alone would see one giant line."""+ seen: list[str] = []+ _call(+ _python(+ "import sys; sys.stderr.write('Receiving objects: 10%\\r"+ "Receiving objects: 90%\\r'); sys.stderr.flush()"+ ),+ tap=seen.append,+ )+ assert seen == ["Receiving objects: 10%", "Receiving objects: 90%"]+++def test_the_tap_sees_output_while_the_child_still_runs() -> None:+ """The whole point: a percentage that only arrives at the end is useless."""+ seen: list[str] = []+ _call(+ _python(+ "import sys, time\n"+ "for i in range(5):\n"+ " sys.stderr.write(f'tick {i}\\r'); sys.stderr.flush(); time.sleep(0.05)\n"+ ),+ tap=seen.append,+ )+ assert seen == [f"tick {i}" for i in range(5)]+++def test_a_chatty_child_does_not_deadlock() -> None:+ """A child filling one pipe while we read the other is the classic hang."""+ seen: list[str] = []+ rc, out, err = _call(+ _python(+ "import sys\n"+ "for i in range(4000):\n"+ " sys.stdout.write('o' * 60 + '\\n')\n"+ " sys.stderr.write(f'progress {i}\\r')\n"+ ),+ timeout_s=60.0,+ tap=seen.append,+ )+ assert rc == 0+ assert len(out.splitlines()) == 4000+ assert len(seen) >= 3999 # the last segment may still be buffered+ assert "progress 3999" in err+++def test_blank_segments_are_not_delivered() -> None:+ seen: list[str] = []+ _call(+ _python("import sys; sys.stderr.write('\\r\\n\\r\\n \\r\\nreal\\r')"),+ tap=seen.append,+ )+ assert seen == ["real"]+++def test_undecodable_bytes_do_not_kill_the_run() -> None:+ """A locale-mangled git message must degrade, not raise."""+ seen: list[str] = []+ rc, _out, _err = _call(+ _python(+ "import sys; sys.stderr.buffer.write(b'bad \\xff byte\\r'); sys.stderr.buffer.flush()"+ ),+ tap=seen.append,+ )+ assert rc == 0+ assert len(seen) == 1+ assert "bad" in seen[0]+++def test_output_is_complete_with_no_tap_attached() -> None:+ """Every other git call in the updater passes no tap; it must be unaffected."""+ rc, out, err = _call(_python("import sys; print('out'); sys.stderr.write('err')"), tap=None)+ assert (rc, out, err) == (0, "out", "err")++[email protected]("stream", ["stdout", "stderr"])+def test_large_single_stream_output_survives(stream: str) -> None:+ rc, out, err = _call(+ _python(+ f"import sys; sys.{stream}.write('x' * 500_000)",+ ),+ timeout_s=60.0,+ )+ assert rc == 0+ assert len(out if stream == "stdout" else err) == 500_000