Skip to content

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

fix(update): native installs come back after an update or restart on every OS (#286)

Ruben Lütke5856d19617c3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ce312ca873..fc0e832ce6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -90,6 +90,7 @@ jobs:
browser: ${{ steps.lanes.outputs.browser }}
macos_desktop: ${{ steps.lanes.outputs.macos_desktop }}
installer: ${{ steps.lanes.outputs.installer }}
+ updater: ${{ steps.lanes.outputs.updater }}
macos: ${{ steps.mode.outputs.macos }}
base: ${{ steps.mode.outputs.base }}
pr_mode: ${{ steps.mode.outputs.pr_mode }}
@@ -589,6 +590,52 @@ jobs:
- name: Provider-neutral realtime contract
run: python -m pytest tests/contract/test_gpt_live.py tests/contract/test_realtime_provider_contract.py tests/contract/test_realtime_reliability_gate.py -q -p no:cacheprovider
+ # The in-app updater on every OS it ships to. Each one replaces a running
+ # app differently (Inno handover, .app swap, AppImage swap, git transaction
+ # + restart helper), and the POSIX-only tests run the real relaunch waiter,
+ # so this lane is never narrowed to one runner the way PR test jobs are.
+ updater:
+ name: updater (${{ matrix.os }})
+ needs: detect
+ if: needs.detect.outputs.updater == 'true'
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 25
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: "3.11"
+ - name: Portable base + focused runner
+ shell: bash
+ run: |
+ python -m pip install -e .
+ python -m pip install pytest pytest-asyncio
+ - name: Updater suite (status, verify, handover, restart, rollback)
+ shell: bash
+ run: |
+ git config --global user.email [email protected]
+ git config --global user.name ci
+ python -m pytest -q -p no:cacheprovider -rs \
+ tests/unit/core/test_installer_update.py \
+ tests/unit/install/test_installer_update_contract.py \
+ tests/unit/ui/test_relauncher.py \
+ tests/unit/ui/test_relauncher_frozen.py \
+ tests/unit/ui/test_relauncher_fresh_env.py \
+ tests/unit/ui/test_relauncher_update_transaction.py \
+ tests/unit/ui/web/test_launcher_update_handoff.py \
+ tests/unit/ui/web/test_update_routes.py \
+ tests/unit/ui/web/test_update_routes_frozen.py \
+ tests/unit/web/test_update_progress.py \
+ tests/unit/web/test_update_progress_route.py \
+ tests/unit/web/test_update_subprocess_stream.py \
+ tests/integration/test_update_apply_real_git.py
+
realtime-slim:
name: realtime on python:3.11-slim (no PortAudio)
needs: detect
@@ -711,6 +758,7 @@ jobs:
- browser
- macos-desktop
- installer
+ - updater
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
diff --git a/docs/ci-pipeline.md b/docs/ci-pipeline.md
index c1e097fb19..61d4de0b0d 100644
--- a/docs/ci-pipeline.md
+++ b/docs/ci-pipeline.md
@@ -25,7 +25,7 @@ agent branch ──► pull request ──► CI (lanes) ──► CI gate ─
| `tests windows` | Four shards on full runs; on a pull request one runner takes only the tests the diff can reach. | `scripts/ci/select_tests.py` |
| `tests macos 1..3` | Nightly and manual runs only (~10x runner cost). | — |
| `test report + floor` | Sums all Linux shards, enforces the min-passed floor, lists baselined failures that now pass, and on main refreshes the per-file duration cache that balances the shards. | `scripts/ci/ratchet_tests.py` |
-| Lanes | `frontend`, `jarvisctl`, `deps`, `realtime` (3 OS + slim container), `dragdrop`, `browser`, `macOS desktop`, `installer smoke` — each only when its paths change. | — |
+| Lanes | `frontend`, `jarvisctl`, `deps`, `realtime` (3 OS + slim container), `updater` (3 OS: in-app update, native handover, restart helper), `dragdrop`, `browser`, `macOS desktop`, `installer smoke` — each only when its paths change. | — |
| `CI gate` | Aggregates every job. **The only required check.** Skipped lanes pass; the nightly run is strict and fails on any skip. | `scripts/ci/required_results.py` |
### Known failures: the ratchet
diff --git a/docs/os-parity.md b/docs/os-parity.md
index eecf58aae4..28f9af76de 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -743,6 +743,24 @@ mount that disappears when the app exits — and the uninstall path would delete
shortcuts it never created. Covered by
`tests/unit/setup/test_desktop_integration.py`.
+**In-app update of a native install (2026-10-01).** The new version may only
+start once the running app is gone (the single-instance lock), so every
+handover ends with the update route quitting the app, and each OS brings the
+new version back its own way: Windows runs the Inno installer with
+`/SILENT /SUPPRESSMSGBOXES /CLOSEAPPLICATIONS /NORESTART /RELAUNCH=1`, and the
+installer's own `[Run]` entry (`Check: RelaunchRequested`, not `skipifsilent`)
+starts the app again; macOS swaps the `.app` and Linux the AppImage, then a
+detached POSIX `sh` waiter (`relaunch_after_exit_command`) starts the new
+version once the old PID has exited. The plain Restart button of a frozen
+build re-enters its own executable with `--relauncher` (a frozen build has no
+`python -m`), and relaunches through `$APPIMAGE` on Linux and `open -n` on
+macOS. A frozen apply runs the mission guard before downloading. A host with
+no desktop window (`jarvis serve`) keeps running and is told to restart by
+hand. Covered by `tests/unit/core/test_installer_update.py` (the waiter is
+executed for real on macOS and Linux), `tests/unit/ui/test_relauncher_frozen.py`
+and `tests/unit/ui/web/test_update_routes_frozen.py`, run on all three OSes by
+the CI `updater` lane. Not yet run against a real installed build on any OS.
+
| # | Impact | Area | Gap | Evidence | Behavior off-Windows |
|---|---|---|---|---|---|
| P-38 | Medium | Native installer / desktop window | The Linux AppImage and `.deb` have **no native desktop window**. Windows (WebView2) and macOS (WKWebView) get one from the frozen bundle; Linux does not, because pywebview's GTK backend needs PyGObject and a frozen interpreter can never import the distribution's `python3-gi` (it is compiled against the system CPython), while bundling GTK 3 + WebKit2GTK portably means shipping its helper processes, GIO modules, pixbuf loaders, GSettings schemas and typelibs. The Qt route is also closed today: the `[desktop]` extra installs `pyside6-essentials`, which has no QtWebEngine, and `jarvis.spec` excludes PySide6 outright. Adding `pyside6-addons` and dropping that exclusion is the realistic fix, at roughly +400 MB | `packaging/linux/README.md` ("The window question"), `jarvis/ui/desktop_app.py::_degrade_to_browser_ui`, `jarvis.spec` `excludes`, `pyproject.toml` `[desktop]` | Linux: honest degradation, verified against a real build — the app catches pywebview's `WebViewException`, keeps the backend serving, and `AppRun` waits for `/api/health` and opens the interface with `xdg-open`. Everything except the window frame works, including the whole CLI. A source/pipx install on a Linux desktop with `python3-gi` + `gir1.2-webkit2-4.1` still gets the native window; only the frozen build does not. Sub-gap: the app's fallback message advises installing those system packages, which does not help a frozen build |
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index 1b9553111a..c36083b847 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -31,6 +31,14 @@ if len(sys.argv) == 3 and sys.argv[1] == "--audio-device-probe":
raise SystemExit(_audio_device_probe_main(sys.argv[2]))
+# The restart helper of a frozen build. ``python -m jarvis.ui.relauncher`` is
+# what a source install spawns; a frozen executable has no ``-m``, so it is
+# re-entered with this private flag instead (see relauncher.RELAUNCHER_FLAG).
+if len(sys.argv) >= 2 and sys.argv[1] == "--relauncher":
+ from jarvis.ui.relauncher import main as _relauncher_main
+
+ raise SystemExit(_relauncher_main(sys.argv[2:]))
+
# Windows Terminal defaults to cp1252 — which breaks Unicode (box-drawing,
# emojis, ✓/✗). Force utf-8 before printing anything.
if sys.platform == "win32":
diff --git a/jarvis/core/installer_update.py b/jarvis/core/installer_update.py
index 7d907c4fa1..0f97e0f8ec 100644
--- a/jarvis/core/installer_update.py
+++ b/jarvis/core/installer_update.py
@@ -502,6 +502,7 @@ def apply_installer(
app_path: Path | None = None,
appimage_path: Path | None = None,
relaunch: bool = True,
+ wait_for_pid: int | None = None,
) -> str:
"""Install the verified ``installer`` and hand control to the new version.
@@ -509,9 +510,15 @@ def apply_installer(
: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.
+
+ The caller must QUIT the running app once this returns. The new version is
+ started only after ``wait_for_pid`` (default: this process) has exited:
+ started any earlier, it would find the single-instance lock still held,
+ focus the old window and exit — leaving the user on the old version.
"""
active_platform = sys.platform if platform_name is None else platform_name
active_runner = SubprocessCommandRunner() if runner is None else runner
+ old_pid = os.getpid() if wait_for_pid is None else wait_for_pid
if not installer.is_file():
raise InstallerUpdateError(f"{installer} does not exist")
@@ -524,6 +531,7 @@ def apply_installer(
runner=active_runner,
app_path=app_path if app_path is not None else _running_macos_app(),
relaunch=relaunch,
+ wait_for_pid=old_pid,
)
if active_platform.startswith("linux"):
return _handover_linux(
@@ -531,24 +539,38 @@ def apply_installer(
runner=active_runner,
appimage_path=(appimage_path if appimage_path is not None else _running_appimage()),
relaunch=relaunch,
+ wait_for_pid=old_pid,
)
raise InstallerUpdateError(f"no installer handover exists for platform {active_platform!r}")
+# The Inno Setup parameter that tells the installer to start the app again
+# once the files are in place (see the RelaunchRequested check in
+# packaging/windows/PersonalJarvis.iss).
+WINDOWS_RELAUNCH_PARAM = "/RELAUNCH=1"
+
+
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.
+ The app quits right after this returns; ``/CLOSEAPPLICATIONS`` lets
+ Restart Manager close anything still holding a file (the detached terminal
+ host, a slow shutdown). ``/SUPPRESSMSGBOXES`` keeps a silent upgrade from
+ stopping on a dialog nobody asked for, and ``/NORESTART`` guarantees the
+ machine is never rebooted behind the user's back.
+
+ The app comes back through ``/RELAUNCH=1``, which the installer's own
+ ``[Run]`` entry honours. ``/RESTARTAPPLICATIONS`` is deliberately absent: it
+ only restarts apps registered with ``RegisterApplicationRestart``, which
+ this one is not, so it promised a relaunch that never happened.
"""
command = [
str(installer),
"/SILENT",
+ "/SUPPRESSMSGBOXES",
"/CLOSEAPPLICATIONS",
- "/RESTARTAPPLICATIONS",
"/NORESTART",
+ WINDOWS_RELAUNCH_PARAM,
]
try:
runner.spawn_detached(command)
@@ -564,6 +586,7 @@ def _handover_macos(
runner: CommandRunner,
app_path: Path | None,
relaunch: bool,
+ wait_for_pid: int,
) -> str:
"""Mount the DMG, swap the running ``.app`` for the one inside, relaunch."""
if app_path is None:
@@ -615,13 +638,15 @@ def _handover_macos(
if relaunch:
try:
- runner.spawn_detached(["open", "-n", str(app_path)])
+ runner.spawn_detached(
+ relaunch_after_exit_command(wait_for_pid, ["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"
+ return f"{app_path.name} was replaced; it restarts as soon as this window closes"
def _handover_linux(
@@ -630,6 +655,7 @@ def _handover_linux(
runner: CommandRunner,
appimage_path: Path | None,
relaunch: bool,
+ wait_for_pid: int,
) -> str:
"""Atomically swap the running AppImage for the downloaded one, relaunch."""
if appimage_path is None:
@@ -656,13 +682,41 @@ def _handover_linux(
if relaunch:
try:
- runner.spawn_detached([str(appimage_path)])
+ runner.spawn_detached(
+ relaunch_after_exit_command(wait_for_pid, [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"
+ return f"{appimage_path.name} was replaced; it restarts as soon as this window closes"
+
+
+# How long the relaunch waiter gives the old app to exit (240 x 0.5 s). Past
+# that it launches anyway: the new instance then finds the old one still
+# holding the lock and simply focuses it, which is harmless.
+RELAUNCH_WAIT_TICKS = 240
+
+# POSIX sh, so it exists on every macOS and Linux box — including a frozen
+# build that ships no Python of its own outside the bundle. ``$1`` is the PID
+# to outlive, the rest is the command to exec.
+_WAIT_THEN_EXEC = (
+ 'pid="$1"; shift; n=0; '
+ f'while kill -0 "$pid" 2>/dev/null && [ "$n" -lt {RELAUNCH_WAIT_TICKS} ]; '
+ "do sleep 0.5; n=$((n+1)); done; "
+ 'exec "$@"'
+)
+
+
+def relaunch_after_exit_command(pid: int, command: Sequence[str]) -> list[str]:
+ """Argv that waits for ``pid`` to exit, then execs ``command`` (POSIX only).
+
+ Spawned detached right before the app quits. The single-instance lock only
+ frees once the old process is gone, so the new version must not start a
+ moment earlier — otherwise it focuses the dying window and exits.
+ """
+ return ["/bin/sh", "-c", _WAIT_THEN_EXEC, "jarvis-relaunch", str(pid), *command]
def _replace_directory(source: Path, target: Path) -> None:
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 136d6c12f9..931f731a1a 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -3657,6 +3657,8 @@ class DesktopApp:
desktop_launch_args,
detached_creationflags,
fresh_user_env,
+ relauncher_command,
+ restart_workdir,
run_restart_quit_sequence,
spawn_detached,
)
@@ -3669,15 +3671,12 @@ class DesktopApp:
try:
import jarvis as _jarvis
- repo_root = str(Path(_jarvis.__file__).resolve().parent.parent)
- argv = [
- sys.executable,
- "-m",
- "jarvis.ui.relauncher",
- str(os.getpid()),
- repo_root,
- *desktop_launch_args(),
- ]
+ # The checkout on a source install; a stable per-user directory on a
+ # frozen one, whose bundle may be a mount that dies with this process.
+ repo_root = restart_workdir(str(Path(_jarvis.__file__).resolve().parent.parent))
+ # ``python -m`` on a source install, the frozen executable's own
+ # helper flag on a native install (which has no ``-m``).
+ argv = relauncher_command(os.getpid(), repo_root, desktop_launch_args())
if drop_elevation:
from jarvis.platform.deescalate import spawn_unelevated
diff --git a/jarvis/ui/relauncher.py b/jarvis/ui/relauncher.py
index 48b392ab51..0323754c42 100644
--- a/jarvis/ui/relauncher.py
+++ b/jarvis/ui/relauncher.py
@@ -84,6 +84,112 @@ def _desktop_overrides(*, port: int | None, dev: bool, no_lock: bool) -> tuple[s
return tuple(args)
+# The private flag a FROZEN executable answers with this module's ``main``.
+# A PyInstaller build has no ``python -m``: its executable IS the app, and its
+# argument parser rejects ``-m`` outright — so before this flag existed, every
+# Restart (and every update restart) of a native install quit the app and
+# never brought it back. ``jarvis/__main__.py`` dispatches it before any other
+# import.
+RELAUNCHER_FLAG = "--relauncher"
+
+
+def _frozen() -> bool:
+ from jarvis.core.frozen import is_frozen
+
+ return is_frozen()
+
+
+def _enclosing_macos_app(executable: str) -> Path | None:
+ """``/Applications/Personal Jarvis.app`` for an executable inside it."""
+ for parent in Path(executable).resolve().parents:
+ if parent.suffix == ".app":
+ return parent
+ return None
+
+
+def frozen_self_command(
+ executable: str,
+ *,
+ platform_name: str | None = None,
+ environ: dict[str, str] | None = None,
+) -> list[str]:
+ """Argv that starts THIS frozen build again, from where the user installed it.
+
+ * Linux AppImage: ``sys.executable`` lives inside the AppImage's private
+ mount, which disappears with the process that mounted it — so the
+ relaunch goes through ``$APPIMAGE``, the file the user actually runs.
+ * macOS: the bundle is opened through LaunchServices (``open -n``), the
+ same identity the Dock and Finder use, so privacy permissions keep
+ attaching to the app rather than to a bare binary.
+ * Windows (and anything else): the executable itself.
+ """
+ active_platform = sys.platform if platform_name is None else platform_name
+ env = os.environ if environ is None else environ
+ if active_platform.startswith("linux"):
+ appimage = (env.get("APPIMAGE") or "").strip()
+ if appimage:
+ return [appimage]
+ if active_platform == "darwin":
+ app = _enclosing_macos_app(executable)
+ if app is not None:
+ return ["/usr/bin/open", "-n", "-W", str(app)]
+ return [executable]
+
+
+def restart_workdir(
+ source_root: str,
+ *,
+ frozen: bool | None = None,
+ environ: dict[str, str] | None = None,
+) -> str:
+ """Directory the restart helper runs in and reads ``jarvis.toml`` from.
+
+ A source install uses its checkout. A frozen build must not: inside an
+ AppImage the bundle is a private mount that disappears with the old
+ process, so a helper parked there cannot even spawn the new version. Its
+ ``jarvis.toml`` lives in the per-user data directory the runtime hook
+ points ``JARVIS_CONFIG`` at, so that directory is the stable choice.
+ """
+ is_frozen_build = _frozen() if frozen is None else frozen
+ if not is_frozen_build:
+ return source_root
+ env = os.environ if environ is None else environ
+ config = (env.get("JARVIS_CONFIG") or "").strip()
+ if config and Path(config).parent.is_dir():
+ return str(Path(config).parent)
+ return str(Path.home())
+
+
+def relauncher_command(
+ pid: int,
+ cwd: str,
+ launcher_args: tuple[str, ...] = (),
+ *,
+ executable: str | None = None,
+ frozen: bool | None = None,
+ platform_name: str | None = None,
+ environ: dict[str, str] | None = None,
+) -> list[str]:
+ """Argv that starts this module as the detached restart helper.
+
+ A source install runs ``python -m jarvis.ui.relauncher``. A frozen build
+ has no interpreter to hand ``-m`` to, so it re-enters its own executable
+ with :data:`RELAUNCHER_FLAG`. A frozen relaunch boots the bare executable,
+ which takes no desktop overrides, so those are dropped there.
+ """
+ active_executable = sys.executable if executable is None else executable
+ is_frozen_build = _frozen() if frozen is None else frozen
+ if is_frozen_build:
+ helper = frozen_self_command(
+ active_executable, platform_name=platform_name, environ=environ
+ )
+ if helper and helper[0] == "/usr/bin/open":
+ # LaunchServices would start a second app, not the helper.
+ helper = [active_executable]
+ return [*helper, RELAUNCHER_FLAG, str(pid), cwd]
+ return [active_executable, "-m", "jarvis.ui.relauncher", str(pid), cwd, *launcher_args]
+
+
def build_launch_command(
executable: str,
*,
@@ -95,7 +201,13 @@ def build_launch_command(
never attach TCC access to a raw Python interpreter. A missing or invalid
bundle therefore fails closed; the managed installer/repair path owns
recreating it.
+
+ A frozen build has neither ``-m`` nor the managed bundle; it starts itself
+ again through :func:`frozen_self_command`.
"""
+ if _frozen():
+ return frozen_self_command(executable)
+
from jarvis.core.instance import current_instance
identity = current_instance()
diff --git a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
index 894fdb04be..5b31c5569d 100644
--- a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
+++ b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
@@ -1,7 +1,11 @@
/**
* The TopBar update button: it renders ONLY when the backend reports a managed
- * install with an available update, shows the new version, and stays hidden on
- * an unmanaged checkout (the dev-tree safety guard surfaced in the UI).
+ * install with an available update, and stays hidden on an unmanaged checkout
+ * (the dev-tree safety guard surfaced in the UI).
+ *
+ * At rest it is a quiet icon with an accent dot; the version, the release notes
+ * and the one action live in a panel the icon opens. A single click on the icon
+ * must never start an update — only the panel's "Update & restart" does.
*/
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -23,6 +27,12 @@ function mockUpdateStatus(body: Record<string, unknown>): void {
);
}
+/** Open the panel from the title-strip icon, then press its install action. */
+async function openAndInstall(): Promise<void> {
+ fireEvent.click(await screen.findByRole("button", { name: /update available/i }));
+ fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
+}
+
describe("TopBar update button", () => {
beforeEach(() => {
// The front page hides this bar; these tests need the global chrome.
@@ -47,8 +57,90 @@ describe("TopBar update button", () => {
published_at: null,
});
render(<TopBar />);
- await waitFor(() => expect(screen.getByText("Update available")).toBeTruthy());
- expect(screen.getByText("v1.0.2")).toBeTruthy();
+ const button = await screen.findByRole("button", { name: /update available/i });
+ // The version rides in the accessible name; the strip itself shows no text.
+ expect(button.getAttribute("aria-label")).toContain("v1.0.2");
+ expect(screen.queryByText("Update available")).toBeNull();
+ expect(screen.getByTestId("update-dot")).toBeTruthy();
+ });
+
+ it("opens a panel with version, current version and notes on click", async () => {
+ mockUpdateStatus({
+ managed: true,
+ current: "1.0.1",
+ latest: "1.0.2",
+ update_available: true,
+ notes: "## What's new\n- **Faster** startup\n- Fixed `voice` lag",
+ published_at: null,
+ });
+ render(<TopBar />);
+ fireEvent.click(await screen.findByRole("button", { name: /update available/i }));
+
+ const panel = await screen.findByRole("dialog", { name: "Update available" });
+ expect(panel.textContent).toContain("v1.0.2");
+ expect(panel.textContent).toContain("You have v1.0.1");
+ // Markdown punctuation is stripped, the words stay.
+ expect(panel.textContent).toContain("What's new");
+ expect(panel.textContent).toContain("• Faster startup");
+ expect(panel.textContent).toContain("Fixed voice lag");
+ expect(panel.textContent).not.toContain("##");
+ expect(panel.textContent).not.toContain("**");
+ });
+
+ it("never starts an update from the icon click alone", async () => {
+ const fetchMock = vi.fn(async (url: string) => {
+ if (url.startsWith("/api/update/status")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ managed: true,
+ current: "1.0.1",
+ latest: "1.0.2",
+ update_available: true,
+ notes: null,
+ }),
+ };
+ }
+ return { ok: true, status: 200, json: async () => ({}) };
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ render(<TopBar />);
+ fireEvent.click(await screen.findByRole("button", { name: /update available/i }));
+ await screen.findByRole("dialog");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ const urls = fetchMock.mock.calls.map((call) => String(call[0]));
+ expect(urls.some((url) => url.startsWith("/api/update/apply"))).toBe(false);
+ expect(urls.some((url) => url.startsWith("/api/settings/restart-app"))).toBe(false);
+ });
+
+ it("closes the panel on Later, on Escape and on an outside click", async () => {
+ mockUpdateStatus({
+ managed: true,
+ current: "1.0.1",
+ latest: "1.0.2",
+ update_available: true,
+ notes: null,
+ published_at: null,
+ });
+ render(<TopBar />);
+ const button = await screen.findByRole("button", { name: /update available/i });
+
+ fireEvent.click(button);
+ fireEvent.click(await screen.findByRole("button", { name: "Later" }));
+ expect(screen.queryByRole("dialog")).toBeNull();
+
+ fireEvent.click(button);
+ await screen.findByRole("dialog");
+ fireEvent.keyDown(document, { key: "Escape" });
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+
+ fireEvent.click(button);
+ await screen.findByRole("dialog");
+ fireEvent.pointerDown(document.body);
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(button.getAttribute("aria-expanded")).toBe("false");
});
it("hides the Update button on an unmanaged checkout (dev-tree guard)", async () => {
@@ -111,9 +203,7 @@ describe("TopBar update button", () => {
);
render(<TopBar />);
- fireEvent.click(
- await screen.findByRole("button", { name: /update available/i }),
- );
+ await openAndInstall();
await waitFor(() => {
expect(
@@ -161,9 +251,7 @@ describe("TopBar update button", () => {
);
render(<TopBar />);
- fireEvent.click(
- await screen.findByRole("button", { name: /update available/i }),
- );
+ await openAndInstall();
// Three restart attempts with a retry pause happen before the verdict.
await waitFor(
@@ -194,8 +282,11 @@ describe("TopBar update button", () => {
pending_update: { version: "1.0.12", target_revision: "b".repeat(40) },
});
render(<TopBar />);
- await waitFor(() => expect(screen.getByText("Finish update")).toBeTruthy());
- expect(screen.getByText("v1.0.12")).toBeTruthy();
+ const button = await screen.findByRole("button", { name: /finish update/i });
+ expect(button.getAttribute("aria-label")).toContain("v1.0.12");
+ fireEvent.click(button);
+ const panel = await screen.findByRole("dialog", { name: "Finish update" });
+ expect(panel.textContent).toContain("v1.0.12");
});
it("announces a rolled-back update instead of failing silently", async () => {
@@ -254,9 +345,7 @@ describe("TopBar update button", () => {
);
render(<TopBar />);
- fireEvent.click(
- await screen.findByRole("button", { name: /update available/i }),
- );
+ await openAndInstall();
await waitFor(() => {
expect(
@@ -270,4 +359,149 @@ describe("TopBar update button", () => {
).toBe(true);
});
});
+
+ it("never restarts on top of a native installer that already took over", async () => {
+ const urls: string[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) => {
+ urls.push(url);
+ if (url.startsWith("/api/update/status")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ managed: true,
+ current: "1.5.3",
+ latest: "1.6.0",
+ update_available: true,
+ notes: null,
+ }),
+ };
+ }
+ if (url.startsWith("/api/update/apply")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ ok: true, kind: "frozen", restart_required: false, quitting: true }),
+ };
+ }
+ return { ok: true, status: 200, json: async () => ({}) };
+ }),
+ );
+
+ render(<TopBar />);
+ await openAndInstall();
+
+ await waitFor(() => expect(screen.getByText("Restarting…")).toBeTruthy());
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ // On a frozen build a second restart would race the installer for the
+ // program files - the server is already closing the app.
+ expect(urls.some((url) => url.startsWith("/api/settings/restart-app"))).toBe(false);
+ });
+
+ it("arms the mission override when the install itself is refused", async () => {
+ const urls: string[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) => {
+ urls.push(url);
+ if (url.startsWith("/api/update/status")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ managed: true,
+ current: "1.5.3",
+ latest: "1.6.0",
+ update_available: true,
+ notes: null,
+ }),
+ };
+ }
+ if (url === "/api/update/apply") {
+ return {
+ ok: false,
+ status: 409,
+ json: async () => ({
+ detail: { error: "missions_running", missions: [{ id: "m-1" }, { id: "m-2" }] },
+ }),
+ };
+ }
+ if (url === "/api/update/apply?force=true") {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ ok: true, restart_required: false }),
+ };
+ }
+ return { ok: true, status: 200, json: async () => ({}) };
+ }),
+ );
+
+ render(<TopBar />);
+ await openAndInstall();
+
+ await waitFor(() =>
+ expect(
+ useEventStore
+ .getState()
+ .toasts.some((toast) => toast.kind === "warning" && toast.message.startsWith("2 ")),
+ ).toBe(true),
+ );
+ fireEvent.click(await screen.findByRole("button", { name: "Restart anyway?" }));
+
+ await waitFor(() => expect(urls).toContain("/api/update/apply?force=true"));
+ expect(urls.some((url) => url.startsWith("/api/settings/restart-app"))).toBe(false);
+ });
+
+ it("tells the user to restart when nothing could close the app after an install", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) => {
+ if (url.startsWith("/api/update/status")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ managed: true,
+ current: "1.5.3",
+ latest: "1.6.0",
+ update_available: true,
+ notes: null,
+ }),
+ };
+ }
+ if (url.startsWith("/api/update/apply")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ ok: true,
+ restart_required: false,
+ quitting: false,
+ handover: "PersonalJarvis.AppImage was replaced",
+ }),
+ };
+ }
+ return { ok: true, status: 200, json: async () => ({}) };
+ }),
+ );
+
+ render(<TopBar />);
+ await openAndInstall();
+
+ await waitFor(() =>
+ expect(
+ useEventStore
+ .getState()
+ .toasts.some(
+ (toast) => toast.kind === "warning" && toast.message.includes("AppImage was replaced"),
+ ),
+ ).toBe(true),
+ );
+ // Not stuck on "Restarting…": the control is usable again.
+ expect(screen.queryByText("Restarting…")).toBeNull();
+ expect(screen.queryByRole("progressbar")).toBeNull();
+ });
});
diff --git a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateProgress.test.tsx b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateProgress.test.tsx
index a14950ff0f..b8ee6cb74e 100644
--- a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateProgress.test.tsx
+++ b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateProgress.test.tsx
@@ -1,10 +1,11 @@
/**
* 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.
+ * While an update runs, the title-strip icon becomes a progress ring and the
+ * update panel shows the percentage the backend reports, fills its bar
+ * 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:
@@ -80,9 +81,10 @@ function mockBackend(opts: {
return calls;
}
+/** Open the update panel from the title-strip icon, then start the update. */
async function clickUpdate(): Promise<void> {
- const button = await screen.findByText("Update available");
- button.click();
+ (await screen.findByRole("button", { name: /update available/i })).click();
+ (await screen.findByRole("button", { name: "Update & restart" })).click();
}
function fillWidth(): string | undefined {
@@ -148,7 +150,7 @@ describe("TopBar update progress", () => {
it("is not a progress bar before an update starts", async () => {
mockBackend({ progress: () => progressBody(0) });
render(<TopBar />);
- await screen.findByText("Update available");
+ await screen.findByRole("button", { name: /update available/i });
// A stray role here would announce a bar frozen at 0 % on every launch.
expect(screen.queryByRole("progressbar")).toBeNull();
diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
index 764ce4f91e..2217c5059b 100644
--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
@@ -376,15 +376,89 @@ function withDetail(message: string, detail: string | null): string {
return `${message} (${trimmed.slice(0, 180)})`;
}
+
/**
- * Shown when the backend reports a managed install with a newer published
- * release (``status.update_available``) — or with a staged-but-not-installed
- * transaction (``status.pending_update``) left behind by an earlier attempt.
- * One click stages the new code (`POST /api/update/apply`) and then restarts
- * to install it, reusing the same mission-guard (409 → force) flow as the
- * restart button. Hovering reveals the release notes. On a dev tree / manual
- * clone the status is ``managed: false``, so this renders nothing and can
- * never trigger a self-update.
+ * Release notes arrive as GitHub Markdown. The panel shows them as plain
+ * prose, so heading hashes, bold markers and list bullets are dropped rather
+ * than printed as literal punctuation.
+ */
+function plainNotes(notes: string): string {
+ return notes
+ .replace(/\r\n/g, "\n")
+ .split("\n")
+ .map((line) =>
+ line
+ .replace(/^\s{0,3}#{1,6}\s+/, "")
+ .replace(/^\s*[-*+]\s+/, "• ")
+ .replace(/\*\*(.+?)\*\*/g, "$1")
+ .replace(/`([^`]+)`/g, "$1"),
+ )
+ .join("\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim()
+ .slice(0, 800);
+}
+
+/** Geometry of the progress ring that replaces the icon while an update runs. */
+const RING_RADIUS = 6.5;
+const RING_LENGTH = 2 * Math.PI * RING_RADIUS;
+
+/**
+ * A 16 px ring that fills with the update percentage — the whole progress
+ * indicator the title strip needs, at the size of the icon it replaces, so a
+ * running update never pushes the neighbouring buttons around.
+ */
+function ProgressRing({ percent, spinning }: { percent: number; spinning: boolean }) {
+ const clamped = Math.min(100, Math.max(0, percent));
+ return (
+ <svg
+ aria-hidden
+ viewBox="0 0 16 16"
+ className={cn("h-4 w-4 -rotate-90", spinning && "animate-spin")}
+ >
+ <circle
+ cx="8"
+ cy="8"
+ r={RING_RADIUS}
+ fill="none"
+ strokeWidth="2"
+ className="stroke-border-strong"
+ />
+ <circle
+ cx="8"
+ cy="8"
+ r={RING_RADIUS}
+ fill="none"
+ strokeWidth="2"
+ strokeLinecap="round"
+ className="stroke-accent transition-[stroke-dashoffset] duration-300 ease-out"
+ strokeDasharray={RING_LENGTH}
+ strokeDashoffset={RING_LENGTH * (1 - clamped / 100)}
+ />
+ </svg>
+ );
+}
+
+/**
+ * The update entry point in the title strip.
+ *
+ * At rest it is one more quiet icon among theme, detach and restart: a download
+ * glyph with a small accent dot. That is the whole announcement — an update is
+ * good news, not an alarm, and most of the time the user is busy with
+ * something else. Clicking opens a small panel with the version, the release
+ * notes and the one action, so a stray click can never start a restart.
+ *
+ * It renders only when the backend reports a managed install with a newer
+ * published release (``status.update_available``) — or with a
+ * staged-but-not-installed transaction (``status.pending_update``) left behind
+ * by an earlier attempt. "Update & restart" stages the new code
+ * (`POST /api/update/apply`) and then restarts to install it, reusing the same
+ * mission-guard (409 → force) flow as the restart button. On a dev tree or
+ * manual clone the status is ``managed: false``, so this renders nothing and
+ * can never trigger a self-update.
+ *
+ * While the update runs, the icon becomes a progress ring and the panel (if
+ * open) shows the percentage, the server's sub-status and a thin bar.
*/
function UpdateButton() {
const t = useT();
@@ -392,11 +466,12 @@ function UpdateButton() {
const { status } = useUpdate();
const [busy, setBusy] = useState(false);
const [forceArmed, setForceArmed] = useState(false);
- const [showNotes, setShowNotes] = useState(false);
+ const [open, setOpen] = 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);
+ const rootRef = useRef<HTMLDivElement | 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
@@ -417,6 +492,27 @@ function UpdateButton() {
};
}, [busy]);
+ // The panel closes on a click outside it or on Escape, like every other
+ // floating layer — also mid-update, which is harmless: the ring on the
+ // button keeps reporting the progress either way.
+ useEffect(() => {
+ if (!open) return;
+ const onPointerDown = (event: PointerEvent) => {
+ const root = rootRef.current;
+ if (root && event.target instanceof Node && root.contains(event.target)) return;
+ setOpen(false);
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("pointerdown", onPointerDown);
+ document.addEventListener("keydown", onKeyDown);
+ return () => {
+ document.removeEventListener("pointerdown", onPointerDown);
+ document.removeEventListener("keydown", onKeyDown);
+ };
+ }, [open]);
+
const clearResetTimer = useCallback(() => {
if (resetTimer.current !== null) {
clearTimeout(resetTimer.current);
@@ -456,23 +552,53 @@ function UpdateButton() {
if (!hasOffer && !hasStaged) return null;
const shownVersion = status.latest ?? status.pending_update?.version ?? null;
+ // The mission guard refused (a quit would kill live missions): surface the
+ // count and arm a force override, so the next click is the user's explicit
+ // decision — never a silent kill.
+ function armForce(count: number) {
+ setBusy(false);
+ setProgress(null);
+ setForceArmed(true);
+ setOpen(true);
+ clearResetTimer();
+ resetTimer.current = window.setTimeout(() => {
+ setForceArmed(false);
+ resetTimer.current = null;
+ }, CONFIRM_TIMEOUT_MS);
+ pushToast("warning", `${count} ${t("topbar.restart_missions_running")}`);
+ }
+
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,
// so a spoofed client can't force a reset on an unmanaged checkout. This is
// idempotent — with a transaction already staged it succeeds even offline.
try {
- const applyRes = await fetch("/api/update/apply", { method: "POST" });
+ const applyRes = await fetch(
+ force ? "/api/update/apply?force=true" : "/api/update/apply",
+ { method: "POST" },
+ );
const applyBody = (await applyRes.json().catch(() => ({}))) as {
- detail?: string;
+ detail?: unknown;
+ restart_required?: boolean;
+ quitting?: boolean;
+ handover?: string | null;
deps_warning?: string | null;
desktop_integration_warning?: string | null;
};
+ const missionGuard = applyBody.detail as
+ | { error?: string; missions?: unknown[] }
+ | undefined;
+ if (applyRes.status === 409 && missionGuard?.error === "missions_running") {
+ // A native install quits for the installer, so the server runs the
+ // mission guard BEFORE downloading. Same override as the restart.
+ armForce(missionGuard.missions?.length ?? 0);
+ return;
+ }
if (!applyRes.ok) {
// 403 unmanaged / 409 nothing newer / 502 git or GitHub failure — the
// backend's detail says WHICH, and the user must get to see it.
@@ -483,7 +609,9 @@ function UpdateButton() {
"error",
withDetail(
t("topbar.update_failed"),
- applyBody.detail ?? `HTTP ${applyRes.status}`,
+ typeof applyBody.detail === "string"
+ ? applyBody.detail
+ : `HTTP ${applyRes.status}`,
),
);
return;
@@ -494,6 +622,27 @@ function UpdateButton() {
if (applyBody.desktop_integration_warning) {
pushToast("warning", t("topbar.update_desktop_warning"));
}
+ if (applyBody.restart_required === false && applyBody.quitting === false) {
+ // Installed, but nothing could close this app (no desktop window,
+ // e.g. a browser-only host): it keeps running the old version until
+ // the user restarts it. Say so instead of spinning forever.
+ setBusy(false);
+ setProgress(null);
+ setForceArmed(false);
+ pushToast(
+ "warning",
+ withDetail(t("topbar.update_staged_restart_failed"), applyBody.handover ?? null),
+ );
+ return;
+ }
+ if (applyBody.restart_required === false) {
+ // A native installer took over and the server is already closing
+ // this app; the new version starts by itself once it is gone. A
+ // restart on top would race the installer for the program files.
+ setRestarting(true);
+ pushToast("info", t("topbar.update_restarting"));
+ return;
+ }
} catch {
setBusy(false);
setProgress(null);
@@ -524,18 +673,7 @@ function UpdateButton() {
} catch {
/* malformed body — still arm the override */
}
- setBusy(false);
- setProgress(null);
- setForceArmed(true);
- clearResetTimer();
- resetTimer.current = window.setTimeout(() => {
- setForceArmed(false);
- resetTimer.current = null;
- }, CONFIRM_TIMEOUT_MS);
- pushToast(
- "warning",
- `${count} ${t("topbar.restart_missions_running")}`,
- );
+ armForce(count);
return;
}
if (restartRes.ok) {
@@ -570,7 +708,7 @@ function UpdateButton() {
);
}
- function onClick() {
+ function onInstall() {
if (busy) return;
void run(forceArmed);
}
@@ -579,78 +717,134 @@ function UpdateButton() {
// 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
+ const busyLabel = 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");
+ : fill(t("topbar.updating_percent"), { percent });
+ const title = hasOffer ? t("topbar.update_available") : t("topbar.update_finish_restart");
+ const buttonLabel = busy
+ ? busyLabel
+ : shownVersion
+ ? `${title} · v${shownVersion}`
+ : title;
+ const actionLabel = forceArmed
+ ? t("topbar.restart_force")
+ : hasOffer
+ ? t("topbar.update_now")
+ : t("topbar.update_finish_restart");
+ const notes = status.notes ? plainNotes(status.notes) : "";
return (
- <div
- className="relative"
- onMouseEnter={() => !busy && status.notes && setShowNotes(true)}
- onMouseLeave={() => setShowNotes(false)}
- >
+ <div ref={rootRef} className="relative">
<button
type="button"
- onClick={onClick}
- disabled={busy}
- 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 %.
+ onClick={() => setOpen((v) => !v)}
+ title={busy ? (progress?.detail ?? busyLabel) : buttonLabel}
+ aria-label={buttonLabel}
+ aria-haspopup="dialog"
+ aria-expanded={open}
+ data-testid="update-button"
+ // While it runs, the button carries the ARIA role of the progress bar
+ // its ring draws — a screen reader announces the same percentage.
+ // 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={clsx(
CHROME_BUTTON,
- "relative overflow-hidden px-3",
- // The one offer in the bar, so it is the one thing here with a fill
- // of its own: an object on the chrome, answering the pointer one
- // step up. It used to be accent-tinted TEXT on an accent-tinted
- // wash, which put the loudest ink in the window on a button most
- // users never need.
- forceArmed ? CHROME_ARMED : "bg-card text-foreground hover:bg-secondary",
+ "relative w-8 justify-center px-0",
+ open ? "bg-secondary text-foreground" : CHROME_QUIET,
)}
>
- {busy && (
- <span
- aria-hidden
- data-testid="update-progress-fill"
- // The bar is the next surface UP from the button's own, so it
- // stays readable whether the button is resting or hovered — and
- // it is a named token, not a tint of one.
- className="absolute inset-y-0 left-0 bg-popover transition-[width] duration-300 ease-out"
- style={{ width: `${percent}%` }}
- />
- )}
- <Download
- aria-hidden
- className={cn("relative h-4 w-4", busy && "animate-pulse")}
- />
- <span className="relative tabular-nums">{label}</span>
- {!busy && !forceArmed && shownVersion && (
- <span className="relative rounded-full bg-secondary px-1.5 text-micro tabular-nums text-muted-foreground">
- v{shownVersion}
- </span>
+ {busy ? (
+ <ProgressRing percent={percent} spinning={restarting} />
+ ) : (
+ <>
+ <Download aria-hidden className="h-4 w-4" />
+ {/* The whole announcement: one accent dot, like an unread mark. */}
+ <span
+ aria-hidden
+ data-testid="update-dot"
+ className="absolute right-1.5 top-1.5 h-1.5 w-1.5 rounded-full bg-accent"
+ />
+ </>
)}
</button>
- {showNotes && status.notes && (
+ {open && (
// A floating layer: the float surface, the float shadow, and no border
// of its own — the shadow already carries the rim.
- <div className="absolute right-0 top-full z-50 mt-2 w-80 rounded-lg bg-popover p-block text-left shadow-float">
- <div className="mb-2 text-title font-semibold text-foreground-strong">
- {t("topbar.update_available")} · v{shownVersion}
- </div>
- <div className="max-h-64 overflow-y-auto whitespace-pre-wrap text-meta text-muted-foreground">
- {status.notes.slice(0, 800)}
+ <div
+ role="dialog"
+ aria-label={title}
+ data-testid="update-panel"
+ className="absolute right-0 top-full z-50 mt-1.5 w-72 rounded-lg bg-popover p-3 text-left shadow-float"
+ >
+ <div className="flex items-baseline justify-between gap-3">
+ <span className="text-meta font-semibold text-foreground-strong">
+ {busy ? busyLabel : title}
+ </span>
+ {shownVersion && (
+ <span className="shrink-0 text-micro tabular-nums text-muted-foreground">
+ v{shownVersion}
+ </span>
+ )}
</div>
+ {busy ? (
+ <>
+ <div className="mt-2.5 h-1 overflow-hidden rounded-full bg-secondary">
+ <div
+ aria-hidden
+ data-testid="update-progress-fill"
+ className="h-full rounded-full bg-accent transition-[width] duration-300 ease-out"
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+ {progress?.detail && !restarting && (
+ <div className="mt-1.5 truncate text-micro tabular-nums text-muted-foreground">
+ {progress.detail}
+ </div>
+ )}
+ </>
+ ) : (
+ <>
+ <div className="mt-0.5 text-micro text-muted-foreground">
+ {fill(t("topbar.update_current_version"), { version: status.current })}
+ </div>
+ {notes && (
+ <div className="mt-2.5 max-h-48 overflow-y-auto whitespace-pre-wrap border-t border-border pt-2.5 text-micro leading-relaxed text-muted-foreground">
+ {notes}
+ </div>
+ )}
+ <div className="mt-3 flex flex-wrap items-center justify-between gap-x-2 gap-y-2">
+ <span className="min-w-0 text-micro text-muted-foreground">
+ {t("topbar.update_restart_note")}
+ </span>
+ <div className="ml-auto flex shrink-0 items-center gap-1.5">
+ <button
+ type="button"
+ onClick={() => setOpen(false)}
+ className="h-7 rounded-md px-2.5 text-micro font-medium text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {t("topbar.update_later")}
+ </button>
+ <button
+ type="button"
+ onClick={onInstall}
+ data-testid="update-install"
+ className={clsx(
+ "h-7 rounded-md px-2.5 text-micro font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ forceArmed
+ ? CHROME_ARMED
+ : "bg-primary text-primary-foreground hover:bg-primary/90",
+ )}
+ >
+ {actionLabel}
+ </button>
+ </div>
+ </div>
+ </>
+ )}
</div>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index f369c9975b..012e761e5c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -108,6 +108,10 @@
"update_staged_restart_failed": "Update heruntergeladen — starte {name} neu, um die Installation abzuschließen",
"update_rolled_back": "Das letzte Update konnte nicht installiert werden — {name} wurde auf die vorherige Version zurückgesetzt",
"update_network_error": "Netzwerkfehler",
+ "update_now": "Aktualisieren & neu starten",
+ "update_later": "Später",
+ "update_current_version": "Installiert: v{version}",
+ "update_restart_note": "{name} startet einmal neu.",
"detach": "Eigenes Fenster",
"detach_hint": "Diese Ansicht in einem eigenen Fenster öffnen",
"detach_failed": "Eigenes Fenster konnte nicht geöffnet werden",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 8a8b184e90..b4070bb804 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -108,6 +108,10 @@
"update_staged_restart_failed": "Update downloaded — restart {name} to finish installing it",
"update_rolled_back": "The last update could not be installed — {name} was rolled back to the previous version",
"update_network_error": "network error",
+ "update_now": "Update & restart",
+ "update_later": "Later",
+ "update_current_version": "You have v{version}",
+ "update_restart_note": "{name} restarts once.",
"detach": "Own window",
"detach_hint": "Open this view in its own window",
"detach_failed": "Could not open a separate window",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 846f2e43d4..043a621c1f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -108,6 +108,10 @@
"update_staged_restart_failed": "Actualización descargada — reinicia {name} para terminar la instalación",
"update_rolled_back": "La última actualización no se pudo instalar — {name} volvió a la versión anterior",
"update_network_error": "error de red",
+ "update_now": "Actualizar y reiniciar",
+ "update_later": "Más tarde",
+ "update_current_version": "Tienes la v{version}",
+ "update_restart_note": "{name} se reinicia una vez.",
"detach": "Ventana propia",
"detach_hint": "Abrir esta vista en su propia ventana",
"detach_failed": "No se pudo abrir una ventana separada",
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index fb65d116b2..80b74c708f 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -1136,6 +1136,113 @@ def _health_answers(port: int, *, timeout: float = 2.0) -> bool:
return response.status_code == 200
+# How long a freshly installed native build waits for the OLDER build it is
+# replacing to exit. Long enough for an old app to finish quitting after its
+# installer handover; short enough that a genuinely stuck old instance still
+# reaches the normal "already running" recovery.
+UPDATE_HANDOFF_WAIT_S = 90.0
+
+
+def _holder_version(port: int, *, timeout: float = 1.5) -> str | None:
+ """The version the running instance reports on ``/api/health``, if any."""
+ try:
+ import httpx
+ except Exception: # noqa: BLE001 — no probe possible means no hand-off claim
+ return None
+ try:
+ response = httpx.get(f"http://127.0.0.1:{int(port)}/api/health", timeout=timeout)
+ version = response.json().get("version")
+ except Exception: # noqa: BLE001 — silent/old holder: treat as "unknown version"
+ return None
+ return version if isinstance(version, str) and version.strip() else None
+
+
+def _is_older(holder: str, ours: str) -> bool:
+ """True only when ``holder`` is provably an older release than ``ours``."""
+ try:
+ from packaging.version import InvalidVersion, Version
+ except Exception: # noqa: BLE001 — cannot compare means "not older"
+ return False
+ try:
+ return Version(holder) < Version(ours)
+ except InvalidVersion: # an unparsable version proves nothing, so no hand-off wait
+ return False
+
+
+def _wait_out_an_older_holder(
+ *,
+ frozen: bool | None = None,
+ read_meta=None,
+ version_of=None,
+ acquire=None,
+ running_version: str | None = None,
+ sleep=None,
+ now=None,
+ wait_s: float = UPDATE_HANDOFF_WAIT_S,
+):
+ """Take over from an OLDER native build that is quitting for an update.
+
+ Native builds up to v2.4.x start the new version while they themselves are
+ still running: macOS ``open -n`` and the Linux AppImage respawn fire right
+ after the swap, before the old app has quit. The new version then found the
+ lock held, focused the old window and exited — and the old app quit a
+ moment later, leaving nothing running. When the lock holder reports an
+ older version than this build, this is that hand-off: wait for it to let
+ go instead of bowing out. Returns the lock, or ``None`` to fall through to
+ the normal "already running" handling (same version, a dev tree, a holder
+ that does not answer, or one that never exits).
+ """
+ from loguru import logger
+
+ from jarvis.ui import desktop_app as _desktop_app
+
+ if frozen is None:
+ from jarvis.core.frozen import is_frozen
+
+ frozen = is_frozen()
+ if not frozen:
+ return None
+ read_meta = read_meta or _desktop_app._read_meta
+ version_of = version_of or _holder_version
+ if acquire is None:
+
+ def acquire():
+ return _desktop_app.acquire_single_instance_lock(
+ timeout=0.5, terminate=lambda _pid: False
+ )
+
+ if running_version is None:
+ from jarvis import __version__ as running_version
+ sleep = sleep or time.sleep
+ now = now or time.monotonic
+
+ meta = None
+ with contextlib.suppress(Exception):
+ meta = read_meta()
+ port = meta.get("port") if isinstance(meta, dict) else None
+ if port is None:
+ return None
+ holder = version_of(int(port))
+ if holder is None or not _is_older(holder, running_version):
+ return None
+
+ logger.info(
+ "launcher: v{} is still running while v{} starts — an update hand-over; "
+ "waiting up to {:.0f}s for it to quit",
+ holder,
+ running_version,
+ wait_s,
+ )
+ deadline = now() + wait_s
+ while now() < deadline:
+ try:
+ return acquire()
+ except _desktop_app.SingleInstanceError: # still held by the old app: poll again
+ sleep(0.5)
+ logger.warning("launcher: the older v{} never quit — normal recovery takes over", holder)
+ return None
+
+
def _holder_alive(pid: int) -> bool:
"""False only when ``pid`` has certainly exited; an unknown answer is True.
@@ -1475,12 +1582,16 @@ def _run_desktop(cfg, use_lock: bool) -> int:
try:
lock = acquire_single_instance_lock()
except SingleInstanceError as exc:
- print(f"{APP_DISPLAY_NAME} is already running.", file=sys.stderr)
- lock = _recover_from_already_running(
- exc,
- focus=focus_existing_instance_robust,
- health=_health_answers,
- )
+ # An older native build quitting for an update is not "already
+ # running" — this build is its replacement and takes over.
+ lock = _wait_out_an_older_holder()
+ if lock is None:
+ print(f"{APP_DISPLAY_NAME} is already running.", file=sys.stderr)
+ lock = _recover_from_already_running(
+ exc,
+ focus=focus_existing_instance_robust,
+ health=_health_answers,
+ )
if lock is None:
return 3
diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.py
index 93dfced50f..054b1b7ca8 100644
--- a/jarvis/ui/web/update_routes.py
+++ b/jarvis/ui/web/update_routes.py
@@ -71,7 +71,7 @@ from collections.abc import Callable
from pathlib import Path
from typing import Any, Literal
-from fastapi import APIRouter, HTTPException
+from fastapi import APIRouter, HTTPException, Request
from jarvis.core.branding import (
MANAGED_INSTALL_MARKER,
@@ -910,14 +910,80 @@ async def _frozen_status(current: str) -> dict[str, object]:
return result
-async def _apply_frozen() -> dict[str, object]:
+def _running_missions(request: Request | None) -> list[str]:
+ """IDs of the missions an app quit would kill right now (empty on doubt)."""
+ if request is None:
+ return []
+ kontrollierer = getattr(request.app.state, "kontrollierer", None)
+ list_running = getattr(kontrollierer, "running_mission_ids", None)
+ if not callable(list_running):
+ return []
+ try:
+ return [str(mid) for mid in list_running()]
+ except Exception: # noqa: BLE001 — a wedged guard must not block the update
+ log.warning("[update] could not list running missions", exc_info=True)
+ return []
+
+
+def _refuse_if_missions_run(request: Request | None, *, force: bool) -> None:
+ """Raise the restart route's 409 when quitting now would kill missions."""
+ if force:
+ return
+ running = _running_missions(request)
+ if running:
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "error": "missions_running",
+ "missions": [{"id": mid, "title": ""} for mid in running],
+ },
+ )
+
+
+def _desktop_can_quit(request: Request | None) -> bool:
+ """True when a desktop window exists that ``_quit_for_update`` can close."""
+ if request is None:
+ return False
+ desktop = getattr(request.app.state, "desktop_app", None)
+ return callable(getattr(desktop, "request_quit", None))
+
+
+def _quit_for_update(request: Request | None) -> bool:
+ """Close the desktop app so the handed-over installer can take its place.
+
+ The native handover only starts the new version once THIS process is gone
+ (the single-instance lock), so a successful handover must be followed by a
+ quit. Returns False on a host without a desktop window (``jarvis serve``):
+ the user then restarts by hand, and the response says so.
+ """
+ if request is None:
+ return False
+ desktop = getattr(request.app.state, "desktop_app", None)
+ quit_fn = getattr(desktop, "request_quit", None)
+ if not callable(quit_fn):
+ return False
+ try:
+ return bool(quit_fn())
+ except Exception: # noqa: BLE001 — reported to the caller as "restart by hand"
+ log.warning("[update] could not quit for the update", exc_info=True)
+ return False
+
+
+async def _apply_frozen(
+ request: Request | None = None, *, force: bool = False
+) -> 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.
+
+ A successful handover ends this app (the installer replaces it), so the
+ same mission guard as ``/api/settings/restart-app`` runs FIRST — before a
+ single byte is downloaded — and refuses with 409 unless ``force`` is set.
"""
_progress.begin(INSTALL_KIND_FROZEN)
+ _refuse_if_missions_run(request, force=force)
current = _running_version()
asset_name = _frozen_asset_name()
if asset_name is None:
@@ -990,10 +1056,23 @@ async def _apply_frozen() -> dict[str, object]:
# 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)
+ # The download can take minutes; a mission started meanwhile must get
+ # the same protection, so the guard runs again right before the point
+ # of no return.
+ _refuse_if_missions_run(request, force=force)
_progress.enter(PHASE_INSTALLING)
+ # Without a window to close (``jarvis serve``, a browser-only AppImage)
+ # this process keeps running, so a relaunch waiter would only start a
+ # second instance that bounces off the lock: the user restarts instead.
+ relaunch = _desktop_can_quit(request)
# 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)
+ handover = await asyncio.to_thread(
+ lambda: apply_installer(installer, relaunch=relaunch)
+ )
+ except HTTPException:
+ shutil.rmtree(workdir, ignore_errors=True)
+ raise
except InstallerUpdateError as exc:
shutil.rmtree(workdir, ignore_errors=True)
_progress.fail(str(exc))
@@ -1009,10 +1088,17 @@ async def _apply_frozen() -> dict[str, object]:
# 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.
+ # The new version starts once this process is gone — so go.
+ quitting = _quit_for_update(request)
+ if not quitting:
+ handover = f"{handover} — restart Personal Jarvis to finish the update"
+
+ # On Windows the installer that replaces this app is running from the
+ # download right now, so it stays (deleting it would kill the update). On
+ # macOS and Linux the swap is already done, and nothing reclaims a
+ # hundreds-of-MB file in the temp directory on its own.
+ if sys.platform != "win32":
+ shutil.rmtree(workdir, ignore_errors=True)
log.info("[update] %s installed from %s (%s)", release_tag, asset.name, workdir)
global _status_cache, _status_cache_until, _status_cache_root
@@ -1021,11 +1107,13 @@ async def _apply_frozen() -> dict[str, object]:
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.
+ # The handover relaunches the app itself once this process exits
+ # (the installer's /RELAUNCH=1 run on Windows, a wait-then-exec helper
+ # on macOS and Linux), and this route already scheduled that exit. A
+ # caller must NOT restart on top: on a frozen build that would race
+ # the installer for the program files.
"restart_required": False,
+ "quitting": quitting,
"kind": INSTALL_KIND_FROZEN,
"version": release_version,
"release_tag": release_tag,
@@ -1147,7 +1235,7 @@ async def update_progress() -> dict[str, object]:
@router.post("/apply", openapi_extra={"x-jarvis-dangerous": True})
-async def update_apply() -> dict[str, object]:
+async def update_apply(request: Request, force: bool = False) -> dict[str, object]:
"""Prepare the latest version and report progress while doing it.
Dispatches on the install kind: a FROZEN install downloads and hands over
@@ -1166,10 +1254,13 @@ async def update_apply() -> dict[str, object]:
async with _apply_lock:
try:
if is_frozen():
- return await _apply_frozen()
+ return await _apply_frozen(request, force=force)
return await _apply_managed()
except HTTPException as exc:
- _progress.fail(str(exc.detail))
+ detail = exc.detail
+ if isinstance(detail, dict) and detail.get("error") == "missions_running":
+ detail = "missions are running — confirm to update anyway"
+ _progress.fail(str(detail))
raise
except Exception as exc: # noqa: BLE001 — re-raised; this only records it
_progress.fail(f"{type(exc).__name__}: {exc}")
diff --git a/packaging/windows/PersonalJarvis.iss b/packaging/windows/PersonalJarvis.iss
index c30c582a6f..7850214c49 100644
--- a/packaging/windows/PersonalJarvis.iss
+++ b/packaging/windows/PersonalJarvis.iss
@@ -8,9 +8,12 @@
; * A fixed AppId. Every future release reuses it, so Windows recognises the
; new setup as the SAME application and upgrades in place instead of leaving
; two entries in "Installed apps".
-; * CloseApplications=yes. The updater runs this file with /CLOSEAPPLICATIONS
-; /RESTARTAPPLICATIONS, so Restart Manager closes the running app, the files
-; are replaced, and Personal Jarvis comes back by itself.
+; * CloseApplications=yes. The in-app updater quits the app and runs this
+; file with /SILENT /SUPPRESSMSGBOXES /CLOSEAPPLICATIONS /RELAUNCH=1, so
+; Restart Manager closes anything still holding a file, the files are
+; replaced, and the second [Run] entry starts Personal Jarvis again.
+; (/RESTARTAPPLICATIONS would only restart apps registered with
+; RegisterApplicationRestart, which this one is not.)
; * The uninstaller removes the program directory ONLY. Settings, memory,
; skills and logs live in %LOCALAPPDATA%\Jarvis and are deliberately kept, so
; an uninstall/reinstall cycle does not destroy the user's data.
@@ -99,6 +102,10 @@ Name: "{userdesktop}\{#AppName}"; Filename: "{app}\{#GuiExeName}"; WorkingDir: "
[Run]
Filename: "{app}\{#GuiExeName}"; Description: "{cm:LaunchProgram,{#AppName}}"; WorkingDir: "{app}"; Flags: nowait postinstall skipifsilent
+; The in-app updater's relaunch. A silent upgrade skips the entry above, so
+; without this one the app would quit for the update and never come back.
+; runasoriginaluser: an all-users install runs elevated, the app must not.
+Filename: "{app}\{#GuiExeName}"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser; Check: RelaunchRequested
[Messages]
ConfirmUninstall=Do you really want to remove %1?%n%nYour settings, memory, skills and logs are NOT deleted - they stay in {#UserDataDirDisplay}.
@@ -247,3 +254,22 @@ begin
if CurUninstallStep = usPostUninstall then
RemoveDirFromUserPath(ExpandConstant('{app}'));
end;
+
+{ True when the in-app updater asked for the app to come back (see the [Run]
+ section). Updaters up to v2.4.x passed /RESTARTAPPLICATIONS instead of
+ /RELAUNCH=1 and nothing relaunched the app; honouring that flag too means
+ an install updating FROM one of those versions also comes back. }
+function RelaunchRequested: Boolean;
+var
+ I: Integer;
+begin
+ Result := ExpandConstant('{param:RELAUNCH|0}') = '1';
+ if Result then
+ Exit;
+ for I := 1 to ParamCount do
+ if CompareText(ParamStr(I), '/RESTARTAPPLICATIONS') = 0 then
+ begin
+ Result := True;
+ Exit;
+ end;
+end;
diff --git a/scripts/ci/classify_changes.py b/scripts/ci/classify_changes.py
index 4c03254ac5..1039b68cd7 100644
--- a/scripts/ci/classify_changes.py
+++ b/scripts/ci/classify_changes.py
@@ -153,6 +153,32 @@ _INSTALLER_FILES = {
".github/workflows/sign-installer.yml",
}
+# In-app updater: status, download + verify, native handover, the restart
+# helper that finishes it, and the installer scripts it hands over to. Each
+# OS replaces a running app differently, so this lane runs on all three.
+_UPDATER_PREFIXES = (
+ "jarvis/core/installer_update",
+ "jarvis/core/frozen",
+ "jarvis/ui/relauncher",
+ "jarvis/ui/web/update_routes",
+ "packaging/",
+ "tests/fakes/fake_installer_update",
+ "tests/integration/test_update_",
+ "tests/unit/core/test_installer_update",
+ "tests/unit/install/test_installer_update",
+ "tests/unit/ui/test_relauncher",
+ "tests/unit/ui/web/test_launcher_update_handoff",
+ "tests/unit/ui/web/test_update_routes",
+ "tests/unit/web/test_update_",
+)
+_UPDATER_FILES = {
+ "jarvis/__main__.py",
+ "jarvis/ui/desktop_app.py",
+ "jarvis/ui/web/launcher.py",
+ "jarvis/ui/web/settings_routes.py",
+ ".github/workflows/desktop-installers.yml",
+} | _DEPS_FILES
+
LANES = (
"python",
"frontend",
@@ -163,6 +189,7 @@ LANES = (
"browser",
"macos_desktop",
"installer",
+ "updater",
)
@@ -205,6 +232,7 @@ def classify(paths: Iterable[str], *, full: bool = False) -> dict[str, bool]:
"browser": _any(changed, _BROWSER_PREFIXES, _BROWSER_FILES),
"macos_desktop": _any(changed, _MACOS_PREFIXES, _MACOS_FILES),
"installer": _any(changed, _INSTALLER_PREFIXES, _INSTALLER_FILES),
+ "updater": _any(changed, _UPDATER_PREFIXES, _UPDATER_FILES),
"full": False,
}
diff --git a/scripts/ci/test-baseline-linux.json b/scripts/ci/test-baseline-linux.json
index fe45591cfa..2dc1239a97 100644
--- a/scripts/ci/test-baseline-linux.json
+++ b/scripts/ci/test-baseline-linux.json
@@ -151,18 +151,9 @@
"tests.unit.test_tts_defaults_parity::test_all_tts_providers_have_defaults_entry",
"tests.unit.ui.jarvisbar.test_qt_overlay::test_full_frame_paint_clears_black_backing_and_previous_pixels",
"tests.unit.ui.test_icon_identity::test_bundled_app_icon_png_is_white_rounded_tile",
- "tests.unit.ui.test_relauncher::test_main_spawns_branded_exe_with_the_loop_guard",
"tests.unit.ui.web.test_skills_routes::test_creator_author_writes_a_draft_skill_with_a_brain",
"tests.unit.ui.web.test_society_figure_routes::test_a_contract_figure_is_accepted_stored_and_served",
"tests.unit.ui.web.test_society_routes::test_memory_file_serves_society_page_and_refuses_escape",
- "tests.unit.ui.web.test_update_routes::test_apply_falls_back_to_cached_release_when_refetch_fails",
- "tests.unit.ui.web.test_update_routes::test_apply_git_fetch_failure_is_502",
- "tests.unit.ui.web.test_update_routes::test_apply_happy_path_pulls_and_signals_restart",
- "tests.unit.ui.web.test_update_routes::test_apply_invalidates_status_cache",
- "tests.unit.ui.web.test_update_routes::test_apply_preserves_headless_profile_for_deferred_installer",
- "tests.unit.ui.web.test_update_routes_frozen::test_apply_downloads_verifies_and_hands_over",
- "tests.unit.ui.web.test_update_routes_frozen::test_apply_falls_back_to_the_last_good_release",
- "tests.unit.ui.web.test_update_routes_frozen::test_apply_surfaces_a_verification_failure",
"tests.unit.web.test_agentic_ide_prompt_writer_route::test_a_connected_cli_is_listed_under_its_own_name",
"tests.unit.web.test_agentic_ide_prompt_writer_route::test_a_disconnected_subscription_is_listed_but_marked",
"tests.unit.web.test_agentic_ide_prompt_writer_route::test_a_usable_tool_model_can_be_chosen",
diff --git a/scripts/ci/test-baseline-windows.json b/scripts/ci/test-baseline-windows.json
index a0bb8049d3..5243646b93 100644
--- a/scripts/ci/test-baseline-windows.json
+++ b/scripts/ci/test-baseline-windows.json
@@ -165,14 +165,6 @@
"tests.unit.ui.web.test_skills_routes::test_creator_author_writes_a_draft_skill_with_a_brain",
"tests.unit.ui.web.test_society_figure_routes::test_a_contract_figure_is_accepted_stored_and_served",
"tests.unit.ui.web.test_society_routes::test_memory_file_serves_society_page_and_refuses_escape",
- "tests.unit.ui.web.test_update_routes::test_apply_falls_back_to_cached_release_when_refetch_fails",
- "tests.unit.ui.web.test_update_routes::test_apply_git_fetch_failure_is_502",
- "tests.unit.ui.web.test_update_routes::test_apply_happy_path_pulls_and_signals_restart",
- "tests.unit.ui.web.test_update_routes::test_apply_invalidates_status_cache",
- "tests.unit.ui.web.test_update_routes::test_apply_preserves_headless_profile_for_deferred_installer",
- "tests.unit.ui.web.test_update_routes_frozen::test_apply_downloads_verifies_and_hands_over",
- "tests.unit.ui.web.test_update_routes_frozen::test_apply_falls_back_to_the_last_good_release",
- "tests.unit.ui.web.test_update_routes_frozen::test_apply_surfaces_a_verification_failure",
"tests.unit.web.test_agentic_ide_prompt_writer_route::test_a_connected_cli_is_listed_under_its_own_name",
"tests.unit.web.test_agentic_ide_prompt_writer_route::test_a_disconnected_subscription_is_listed_but_marked",
"tests.unit.web.test_agentic_ide_prompt_writer_route::test_a_usable_tool_model_can_be_chosen",
diff --git a/tests/integration/test_update_apply_real_git.py b/tests/integration/test_update_apply_real_git.py
index b93b9d358a..698fd7c10a 100644
--- a/tests/integration/test_update_apply_real_git.py
+++ b/tests/integration/test_update_apply_real_git.py
@@ -97,7 +97,8 @@ def test_real_apply_fetches_and_pins_without_mutating_live_head(
return {"version": "9.9.10", "tag": "v9.9.10"}
monkeypatch.setattr(u, "_fetch_latest_release", _latest)
- result = asyncio.run(u.update_apply())
+ # No request: a managed apply never quits the app itself, so it needs none.
+ result = asyncio.run(u.update_apply(None))
assert result["ok"] is True
assert result["prepared"] is True
diff --git a/tests/unit/ci/test_pipeline_scripts.py b/tests/unit/ci/test_pipeline_scripts.py
index fcad7c9db6..b65f2d6442 100644
--- a/tests/unit/ci/test_pipeline_scripts.py
+++ b/tests/unit/ci/test_pipeline_scripts.py
@@ -54,6 +54,22 @@ def test_route_change_turns_on_cli_lane_and_windows_path_is_normalized():
assert result["python"] is True
+def test_updater_change_turns_on_the_cross_os_updater_lane():
+ for path in (
+ "jarvis/core/installer_update.py",
+ "jarvis\\ui\\relauncher.py",
+ "packaging/windows/PersonalJarvis.iss",
+ "tests/unit/ui/web/test_update_routes_frozen.py",
+ ):
+ assert classify_changes.classify([path])["updater"] is True, path
+
+
+def test_unrelated_python_change_leaves_the_updater_lane_off():
+ result = classify_changes.classify(["jarvis/society/roster.py"])
+ assert result["python"] is True
+ assert result["updater"] is False
+
+
def test_lockfile_change_reaches_deps_realtime_and_installer():
result = classify_changes.classify(["requirements.txt"])
assert result["deps"] and result["realtime"] and result["installer"]
diff --git a/tests/unit/core/test_installer_update.py b/tests/unit/core/test_installer_update.py
index 92775618ea..a06b27243f 100644
--- a/tests/unit/core/test_installer_update.py
+++ b/tests/unit/core/test_installer_update.py
@@ -10,18 +10,25 @@ so every case below runs on Windows, macOS and Linux alike.
from __future__ import annotations
import hashlib
+import os
+import stat
+import subprocess
+import sys
+import time
from pathlib import Path
import pytest
from jarvis.core.installer_update import (
CHECKSUMS_ASSET_NAME,
+ WINDOWS_RELAUNCH_PARAM,
InstallerAsset,
InstallerUpdateError,
apply_installer,
download_and_verify,
installer_asset_name,
parse_sha256sums,
+ relaunch_after_exit_command,
select_asset,
select_installer_asset,
)
@@ -225,14 +232,45 @@ def test_windows_handover_runs_the_silent_in_place_upgrade(tmp_path: Path) -> No
[
str(installer),
"/SILENT",
+ "/SUPPRESSMSGBOXES",
"/CLOSEAPPLICATIONS",
- "/RESTARTAPPLICATIONS",
"/NORESTART",
+ WINDOWS_RELAUNCH_PARAM,
]
]
assert "restarts by itself" in message
+def test_windows_handover_never_relies_on_restart_manager_relaunch(tmp_path: Path) -> None:
+ """/RESTARTAPPLICATIONS needs RegisterApplicationRestart, which the app never
+ calls — it promised a relaunch that never happened."""
+ installer = tmp_path / "PersonalJarvis-Setup-x64.exe"
+ installer.write_bytes(PAYLOAD)
+ runner = FakeCommandRunner()
+ apply_installer(installer, platform_name="win32", runner=runner)
+ assert "/RESTARTAPPLICATIONS" not in runner.spawned[0]
+
+
+def test_windows_installer_script_honours_the_relaunch_param() -> None:
+ """The flag the app passes must be the one the installer's [Run] reads."""
+ iss = Path(__file__).resolve().parents[3] / "packaging" / "windows" / "PersonalJarvis.iss"
+ text = iss.read_text(encoding="utf-8")
+ name = WINDOWS_RELAUNCH_PARAM.lstrip("/").split("=", 1)[0]
+ assert f"{{param:{name}|0}}" in text
+ assert "Check: RelaunchRequested" in text
+ run_section = text.split("\n[Run]\n", 1)[1].split("\n[", 1)[0]
+ relaunch_lines = [line for line in run_section.splitlines() if "RelaunchRequested" in line]
+ assert relaunch_lines, "the relaunch [Run] entry is missing"
+ # A silent upgrade skips every entry flagged skipifsilent - this one must not be.
+ assert "skipifsilent" not in relaunch_lines[0]
+ assert "runasoriginaluser" in relaunch_lines[0]
+
+ # Apps up to v2.4.x hand the NEW installer their old flags; it must still
+ # bring them back, or the first update onto this fix leaves the app closed.
+ function = text.split("function RelaunchRequested", 1)[1].split("\nend;", 1)[0]
+ assert "/RESTARTAPPLICATIONS" in function
+
+
def test_handover_refuses_a_missing_file(tmp_path: Path) -> None:
with pytest.raises(InstallerUpdateError, match="does not exist"):
apply_installer(
@@ -276,10 +314,14 @@ def test_macos_handover_replaces_the_running_app_and_relaunches(
(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)
+ message = apply_installer(
+ dmg, platform_name="darwin", runner=runner, app_path=app, wait_for_pid=4242
+ )
assert (app / "Contents" / "MacOS" / "PersonalJarvis").read_text(encoding="utf-8") == "new"
- assert runner.spawned == [["open", "-n", str(app)]]
+ # The relaunch waits for the old app: started earlier it would bounce off
+ # the single-instance lock and leave the user on the old version.
+ assert runner.spawned == [relaunch_after_exit_command(4242, ["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
@@ -343,10 +385,12 @@ def test_linux_handover_replaces_the_appimage_in_place(tmp_path: Path) -> None:
live.write_bytes(b"old appimage")
runner = FakeCommandRunner()
- message = apply_installer(downloaded, platform_name="linux", runner=runner, appimage_path=live)
+ message = apply_installer(
+ downloaded, platform_name="linux", runner=runner, appimage_path=live, wait_for_pid=4242
+ )
assert live.read_bytes() == b"new appimage"
- assert runner.spawned == [[str(live)]]
+ assert runner.spawned == [relaunch_after_exit_command(4242, [str(live)])]
assert "replaced" in message
# The staging file must not survive the atomic rename.
assert not (live.parent / f".{live.name}.new").exists()
@@ -376,3 +420,137 @@ def test_linux_handover_reports_a_failed_relaunch(tmp_path: Path) -> None:
# 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"
+
+
+def test_handover_waits_for_this_process_by_default(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()
+ apply_installer(downloaded, platform_name="linux", runner=runner, appimage_path=live)
+
+ assert runner.spawned[0][4] == str(os.getpid())
+
+
[email protected](os.name != "posix", reason="AppImages and exec bits exist on POSIX only")
+def test_linux_handover_leaves_the_appimage_executable(tmp_path: Path) -> None:
+ downloaded = tmp_path / "download.AppImage"
+ downloaded.write_bytes(b"new appimage")
+ downloaded.chmod(0o644)
+ live = tmp_path / "PersonalJarvis.AppImage"
+ live.write_bytes(b"old appimage")
+
+ apply_installer(
+ downloaded, platform_name="linux", runner=FakeCommandRunner(), appimage_path=live
+ )
+
+ assert live.stat().st_mode & stat.S_IXUSR
+
+
+ sys.platform == "win32",
+ reason="the .app swap only runs on macOS; Windows scanners can briefly lock a renamed dir",
+)
+def test_macos_handover_rolls_back_when_the_swap_fails(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> 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")
+
+ real_replace = os.replace
+
+ def _flaky_replace(src: object, dst: object) -> None:
+ # Moving the live bundle aside works; moving the new one in fails.
+ if Path(str(src)).name.endswith(".new"):
+ raise OSError("disk full")
+ real_replace(src, dst)
+
+ monkeypatch.setattr(os, "replace", _flaky_replace)
+ runner = _mounting_runner("Personal Jarvis.app", "new")
+
+ with pytest.raises(InstallerUpdateError, match="could not replace"):
+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app)
+
+ # The app is never left missing, and nothing was relaunched.
+ assert (app / "Contents" / "MacOS" / "PersonalJarvis").read_text(encoding="utf-8") == "old"
+ assert runner.spawned == []
+
+
+# --------------------------------------------------------------------------- #
+# The relaunch waiter, executed for real where a POSIX shell exists
+# --------------------------------------------------------------------------- #
+_HAS_SH = os.name == "posix" and Path("/bin/sh").exists()
+
+
+def test_relaunch_waiter_command_shape() -> None:
+ command = relaunch_after_exit_command(123, ["open", "-n", "/Applications/X.app"])
+ assert command[:2] == ["/bin/sh", "-c"]
+ assert command[3:] == ["jarvis-relaunch", "123", "open", "-n", "/Applications/X.app"]
+
+
[email protected](not _HAS_SH, reason="the waiter is a POSIX sh script (macOS/Linux)")
+def test_relaunch_waiter_starts_the_app_only_after_the_old_process_exits(
+ tmp_path: Path,
+) -> None:
+ marker = tmp_path / "launched"
+ old_app = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(1.5)"])
+ started = time.monotonic()
+ waiter = subprocess.Popen(
+ relaunch_after_exit_command(
+ old_app.pid, [sys.executable, "-c", f"open({str(marker)!r}, 'w').close()"]
+ )
+ )
+ try:
+ time.sleep(0.6)
+ assert not marker.exists(), "the new version started while the old one still ran"
+ old_app.wait(timeout=10)
+ waiter.wait(timeout=15)
+ finally:
+ for proc in (old_app, waiter):
+ if proc.poll() is None:
+ proc.kill()
+ assert marker.exists()
+ assert time.monotonic() - started >= 1.4
+
+
[email protected](not _HAS_SH, reason="the waiter is a POSIX sh script (macOS/Linux)")
+def test_relaunch_waiter_starts_at_once_when_the_old_process_is_gone(tmp_path: Path) -> None:
+ marker = tmp_path / "launched"
+ gone = subprocess.Popen([sys.executable, "-c", "pass"])
+ gone.wait(timeout=10)
+ waiter = subprocess.run(
+ relaunch_after_exit_command(
+ gone.pid, [sys.executable, "-c", f"open({str(marker)!r}, 'w').close()"]
+ ),
+ timeout=15,
+ check=False,
+ )
+ assert waiter.returncode == 0
+ assert marker.exists()
+
+
[email protected](not _HAS_SH, reason="the waiter is a POSIX sh script (macOS/Linux)")
+def test_relaunch_waiter_passes_paths_with_spaces_verbatim(tmp_path: Path) -> None:
+ target = tmp_path / "Personal Jarvis.app" / "argv.txt"
+ target.parent.mkdir()
+ script = tmp_path / "record argv.py"
+ script.write_text(
+ "import sys, pathlib\n"
+ "pathlib.Path(sys.argv[1]).write_text(sys.argv[2], encoding='utf-8')\n",
+ encoding="utf-8",
+ )
+ gone = subprocess.Popen([sys.executable, "-c", "pass"])
+ gone.wait(timeout=10)
+ subprocess.run(
+ relaunch_after_exit_command(
+ gone.pid, [sys.executable, str(script), str(target), "a b c"]
+ ),
+ timeout=15,
+ check=True,
+ )
+ assert target.read_text(encoding="utf-8") == "a b c"
diff --git a/tests/unit/ui/test_relauncher.py b/tests/unit/ui/test_relauncher.py
index 8119034c1b..ab77698e58 100644
--- a/tests/unit/ui/test_relauncher.py
+++ b/tests/unit/ui/test_relauncher.py
@@ -287,6 +287,14 @@ def test_main_spawns_branded_exe_with_the_loop_guard(monkeypatch, tmp_path):
monkeypatch.setattr(relauncher.sys, "executable", str(tmp_path / "python.exe"))
monkeypatch.setattr(relauncher.sys, "_base_executable", "", raising=False)
monkeypatch.delenv("LOCALAPPDATA", raising=False)
+ # Faking win32 must not reach the real registry: on a macOS or Linux runner
+ # there is no winreg module to read the persisted user environment from.
+ real_fresh_user_env = relauncher.fresh_user_env
+ monkeypatch.setattr(
+ relauncher,
+ "fresh_user_env",
+ lambda base=None: real_fresh_user_env(base, _read_persisted=lambda: None),
+ )
spawned: list[dict] = []
def fake_spawn(cmd, **kwargs):
diff --git a/tests/unit/ui/test_relauncher_frozen.py b/tests/unit/ui/test_relauncher_frozen.py
new file mode 100644
index 0000000000..b3157bad62
--- /dev/null
+++ b/tests/unit/ui/test_relauncher_frozen.py
@@ -0,0 +1,197 @@
+"""Restart and update relaunch of a FROZEN (natively installed) build.
+
+A PyInstaller build has no ``python -m``: its executable IS the app, and its
+argument parser rejects ``-m``. Before these paths existed, every Restart and
+every update restart of a native install spawned ``PersonalJarvis -m
+jarvis.ui.relauncher …``, which exited at once with a usage error — the app
+quit and never came back, on every OS.
+
+Everything here injects the platform, so the Windows, macOS and Linux shapes
+are all checked on whichever OS runs the suite.
+"""
+
+from __future__ import annotations
+
+import inspect
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+import jarvis.ui.relauncher as relauncher
+from jarvis.ui.relauncher import (
+ RELAUNCHER_FLAG,
+ build_launch_command,
+ frozen_self_command,
+ relauncher_command,
+)
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+
+# --------------------------------------------------------------------------- #
+# relauncher_command — how the detached restart helper is started
+# --------------------------------------------------------------------------- #
+def test_source_install_runs_the_helper_through_python_m() -> None:
+ argv = relauncher_command(
+ 42, "/repo", ("--port", "8000"), executable="/usr/bin/python3", frozen=False
+ )
+ assert argv == [
+ "/usr/bin/python3",
+ "-m",
+ "jarvis.ui.relauncher",
+ "42",
+ "/repo",
+ "--port",
+ "8000",
+ ]
+
+
+def test_frozen_windows_re_enters_its_own_exe_with_the_helper_flag() -> None:
+ exe = r"C:\Program Files\Personal Jarvis\PersonalJarvis.exe"
+ argv = relauncher_command(
+ 42,
+ r"C:\Program Files\Personal Jarvis\_internal",
+ ("--port", "8000"),
+ executable=exe,
+ frozen=True,
+ platform_name="win32",
+ environ={},
+ )
+ assert argv == [exe, RELAUNCHER_FLAG, "42", r"C:\Program Files\Personal Jarvis\_internal"]
+ # ``-m`` is exactly what the frozen parser rejects.
+ assert "-m" not in argv
+
+
+def test_frozen_linux_runs_the_helper_through_the_appimage() -> None:
+ """``sys.executable`` sits in the AppImage's private mount, which vanishes
+ with the old process — the helper must own a mount of its own."""
+ argv = relauncher_command(
+ 7,
+ "/run/appimage/.mount_abc/_internal",
+ executable="/run/appimage/.mount_abc/PersonalJarvis",
+ frozen=True,
+ platform_name="linux",
+ environ={"APPIMAGE": "/home/me/Apps/PersonalJarvis.AppImage"},
+ )
+ assert argv == [
+ "/home/me/Apps/PersonalJarvis.AppImage",
+ RELAUNCHER_FLAG,
+ "7",
+ "/run/appimage/.mount_abc/_internal",
+ ]
+
+
+def test_frozen_macos_runs_the_helper_binary_not_a_second_app(tmp_path: Path) -> None:
+ exe = tmp_path / "Personal Jarvis.app" / "Contents" / "MacOS" / "PersonalJarvis"
+ exe.parent.mkdir(parents=True)
+ exe.write_text("", encoding="utf-8")
+ argv = relauncher_command(
+ 7, "/x", executable=str(exe), frozen=True, platform_name="darwin", environ={}
+ )
+ assert argv[0] == str(exe)
+ assert argv[1] == RELAUNCHER_FLAG
+
+
+# --------------------------------------------------------------------------- #
+# frozen_self_command — how the fresh app is started
+# --------------------------------------------------------------------------- #
+def test_frozen_windows_relaunches_the_exe_itself() -> None:
+ exe = r"C:\Apps\PersonalJarvis.exe"
+ assert frozen_self_command(exe, platform_name="win32", environ={}) == [exe]
+
+
+def test_frozen_linux_relaunches_the_appimage_file() -> None:
+ assert frozen_self_command(
+ "/run/appimage/.mount_x/PersonalJarvis",
+ platform_name="linux",
+ environ={"APPIMAGE": "/opt/PersonalJarvis.AppImage"},
+ ) == ["/opt/PersonalJarvis.AppImage"]
+
+
+def test_frozen_linux_without_an_appimage_relaunches_the_binary() -> None:
+ """An unpacked tarball or .deb build has no $APPIMAGE; the binary is stable."""
+ assert frozen_self_command(
+ "/opt/jarvis/PersonalJarvis", platform_name="linux", environ={"APPIMAGE": " "}
+ ) == ["/opt/jarvis/PersonalJarvis"]
+
+
+def test_frozen_macos_relaunches_through_launch_services(tmp_path: Path) -> None:
+ app = tmp_path / "Personal Jarvis.app"
+ exe = app / "Contents" / "MacOS" / "PersonalJarvis"
+ exe.parent.mkdir(parents=True)
+ exe.write_text("", encoding="utf-8")
+ command = frozen_self_command(str(exe), platform_name="darwin", environ={})
+ # -n: a new instance even though the old one is still on its way out;
+ # -W: ``open`` stays alive with the app, so the helper can verify it is up.
+ assert command == ["/usr/bin/open", "-n", "-W", str(app.resolve())]
+
+
+def test_frozen_macos_outside_a_bundle_falls_back_to_the_binary(tmp_path: Path) -> None:
+ exe = tmp_path / "PersonalJarvis"
+ exe.write_text("", encoding="utf-8")
+ assert frozen_self_command(str(exe), platform_name="darwin", environ={}) == [str(exe)]
+
+
+def test_build_launch_command_never_uses_python_m_when_frozen(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(relauncher, "_frozen", lambda: True)
+ command = build_launch_command(sys.executable, launcher_args=("--port", "1"))
+ assert "-m" not in command
+ assert relauncher.LAUNCHER_MODULE not in command
+
+
+def test_desktop_restart_builds_its_helper_through_relauncher_command() -> None:
+ """The one place that spawns the helper must not hand-roll ``-m`` again."""
+ from jarvis.ui.desktop_app import DesktopApp
+
+ source = inspect.getsource(DesktopApp._schedule_restart)
+ assert "relauncher_command(" in source
+ assert '"-m"' not in source
+
+
+# --------------------------------------------------------------------------- #
+# The entry point really dispatches the helper flag
+# --------------------------------------------------------------------------- #
+def test_entry_point_dispatches_the_relauncher_flag() -> None:
+ """``jarvis --relauncher`` must reach relauncher.main, not argparse.
+
+ With a non-numeric PID relauncher.main returns 2 without spawning anything;
+ argparse would ALSO exit 2, but only argparse prints a usage line.
+ """
+ result = subprocess.run(
+ [sys.executable, "-m", "jarvis", RELAUNCHER_FLAG, "not-a-pid", str(REPO_ROOT)],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=120,
+ check=False,
+ )
+ assert result.returncode == 2
+ assert "usage:" not in result.stderr.lower()
+
+
+# --------------------------------------------------------------------------- #
+# restart_workdir — where the helper runs and reads jarvis.toml from
+# --------------------------------------------------------------------------- #
+def test_source_install_restarts_from_its_checkout() -> None:
+ assert relauncher.restart_workdir("/repo", frozen=False, environ={}) == "/repo"
+
+
+def test_frozen_build_restarts_from_the_config_directory(tmp_path: Path) -> None:
+ """An AppImage bundle is a mount that dies with the old process."""
+ config = tmp_path / "jarvis.toml"
+ config.write_text("", encoding="utf-8")
+ assert relauncher.restart_workdir(
+ "/run/appimage/.mount_abc", frozen=True, environ={"JARVIS_CONFIG": str(config)}
+ ) == str(tmp_path)
+
+
+def test_frozen_build_without_a_config_falls_back_to_home() -> None:
+ assert relauncher.restart_workdir("/run/appimage/.mount_abc", frozen=True, environ={}) == str(
+ Path.home()
+ )
diff --git a/tests/unit/ui/web/test_launcher_update_handoff.py b/tests/unit/ui/web/test_launcher_update_handoff.py
new file mode 100644
index 0000000000..6c59568f28
--- /dev/null
+++ b/tests/unit/ui/web/test_launcher_update_handoff.py
@@ -0,0 +1,108 @@
+"""A freshly installed native build takes over from the OLDER build it replaces.
+
+Native builds up to v2.4.x start the new version while they are still running
+(macOS ``open -n`` and the Linux AppImage respawn fire right after the swap).
+The new version used to find the lock held, focus the old window and exit —
+then the old app quit too, and nothing was left running. These tests pin the
+hand-off: an older holder is waited out, everything else falls through to the
+normal "already running" handling untouched.
+"""
+
+from __future__ import annotations
+
+from jarvis.ui import desktop_app
+from jarvis.ui.web import launcher
+
+
+class _Clock:
+ def __init__(self) -> None:
+ self.t = 0.0
+
+ def now(self) -> float:
+ return self.t
+
+ def sleep(self, seconds: float) -> None:
+ self.t += seconds
+
+
+def _acquire_after(attempts: int):
+ calls = {"n": 0}
+
+ def acquire():
+ calls["n"] += 1
+ if calls["n"] <= attempts:
+ raise desktop_app.SingleInstanceError("held")
+ return "LOCK"
+
+ return acquire, calls
+
+
+def _wait(**overrides):
+ clock = _Clock()
+ kwargs = {
+ "frozen": True,
+ "read_meta": lambda: {"port": 47821, "pid": 1},
+ "version_of": lambda _port: "2.4.4",
+ "running_version": "2.5.0",
+ "sleep": clock.sleep,
+ "now": clock.now,
+ "wait_s": 90.0,
+ }
+ kwargs.update(overrides)
+ return launcher._wait_out_an_older_holder(**kwargs), clock
+
+
+def test_an_older_holder_is_waited_out_and_the_lock_taken() -> None:
+ acquire, calls = _acquire_after(3)
+ lock, clock = _wait(acquire=acquire)
+ assert lock == "LOCK"
+ assert calls["n"] == 4
+ assert clock.t == 1.5
+
+
+def test_the_same_version_is_a_normal_second_launch() -> None:
+ acquire, calls = _acquire_after(0)
+ lock, _ = _wait(acquire=acquire, version_of=lambda _port: "2.5.0")
+ assert lock is None
+ assert calls["n"] == 0
+
+
+def test_a_newer_holder_is_never_replaced() -> None:
+ acquire, calls = _acquire_after(0)
+ lock, _ = _wait(acquire=acquire, version_of=lambda _port: "2.6.0")
+ assert lock is None
+ assert calls["n"] == 0
+
+
+def test_a_source_install_never_waits() -> None:
+ acquire, calls = _acquire_after(0)
+ lock, _ = _wait(acquire=acquire, frozen=False)
+ assert lock is None
+ assert calls["n"] == 0
+
+
+def test_a_silent_holder_falls_through_to_recovery() -> None:
+ acquire, calls = _acquire_after(0)
+ lock, _ = _wait(acquire=acquire, version_of=lambda _port: None)
+ assert lock is None
+ assert calls["n"] == 0
+
+
+def test_no_sidecar_means_no_hand_off() -> None:
+ acquire, calls = _acquire_after(0)
+ lock, _ = _wait(acquire=acquire, read_meta=lambda: None)
+ assert lock is None
+ assert calls["n"] == 0
+
+
+def test_an_older_holder_that_never_quits_gives_up_at_the_deadline() -> None:
+ acquire, _ = _acquire_after(10_000)
+ lock, clock = _wait(acquire=acquire, wait_s=5.0)
+ assert lock is None
+ assert clock.t >= 5.0
+
+
+def test_garbage_versions_are_not_older() -> None:
+ assert launcher._is_older("not-a-version", "2.5.0") is False
+ assert launcher._is_older("2.4.4", "2.5.0") is True
+ assert launcher._is_older("2.5.0", "2.5.0") is False
diff --git a/tests/unit/ui/web/test_update_routes.py b/tests/unit/ui/web/test_update_routes.py
index 2489288b41..91812bca23 100644
--- a/tests/unit/ui/web/test_update_routes.py
+++ b/tests/unit/ui/web/test_update_routes.py
@@ -194,7 +194,7 @@ def test_apply_happy_path_pulls_and_signals_restart(
},
)
- async def _fake_git(args, *, cwd, timeout_s=60.0):
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
calls.append(args)
return 0, "", ""
@@ -221,8 +221,11 @@ def test_apply_happy_path_pulls_and_signals_restart(
assert body["desktop_integration_pending"] is True
assert body["desktop_integration_ok"] is None
assert body["desktop_integration_warning"] is None
+ # ``--progress`` makes git report object counters through a pipe, which
+ # is what drives the download phase of the progress bar.
assert [
"fetch",
+ "--progress",
"--depth",
"1",
"origin",
@@ -246,7 +249,7 @@ def test_apply_git_fetch_failure_is_502(
monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")
_patch_latest(monkeypatch, {"version": "1.0.2", "tag": "v1.0.2"})
- async def _fake_git(args, *, cwd, timeout_s=60.0):
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
return 1, "", "network down"
async def _fake_git_output(args, *, cwd, timeout_s=15.0):
@@ -267,7 +270,7 @@ def test_apply_preserves_headless_profile_for_deferred_installer(
monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")
_patch_latest(monkeypatch, {"version": "1.0.2", "tag": "v1.0.2"})
- async def _fake_git(args, *, cwd, timeout_s=60.0):
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
return 0, "", ""
async def _fake_git_output(args, *, cwd, timeout_s=15.0):
@@ -340,7 +343,7 @@ def test_apply_falls_back_to_cached_release_when_refetch_fails(
_patch_latest(monkeypatch, None)
u._last_good_release = {"version": "1.0.2", "tag": "v1.0.2"}
- async def _fake_git(args, *, cwd, timeout_s=60.0):
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
return 0, "", ""
async def _fake_git_output(args, *, cwd, timeout_s=15.0):
@@ -487,7 +490,7 @@ def test_apply_invalidates_status_cache(
client.get("/api/update/status")
assert u._status_cache is not None
- async def _fake_git(args, *, cwd, timeout_s=60.0):
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
return 0, "", ""
async def _fake_git_output(args, *, cwd, timeout_s=15.0):
diff --git a/tests/unit/ui/web/test_update_routes_frozen.py b/tests/unit/ui/web/test_update_routes_frozen.py
index e702f99763..874a61e1c4 100644
--- a/tests/unit/ui/web/test_update_routes_frozen.py
+++ b/tests/unit/ui/web/test_update_routes_frozen.py
@@ -216,13 +216,16 @@ def _capture_install(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
path.write_bytes(b"verified installer")
return path
- async def _download(asset: Any, checksums: Any, *, dest_dir: Path) -> Path:
+ async def _download(
+ asset: Any, checksums: Any, *, dest_dir: Path, on_progress: Any = None
+ ) -> Path:
seen["asset"] = asset
seen["checksums"] = checksums
return _write_verified(dest_dir, asset.name)
- def _apply(installer: Path) -> str:
+ def _apply(installer: Path, **kwargs: Any) -> str:
seen["installer"] = installer
+ seen["relaunch"] = kwargs.get("relaunch", True)
return "the Windows installer is running"
monkeypatch.setattr(u, "download_and_verify", _download)
@@ -279,7 +282,7 @@ def test_apply_refuses_without_a_checksum_manifest(
),
)
- def _never(installer: Path) -> str:
+ def _never(installer: Path, **_kwargs: Any) -> str:
raise AssertionError("nothing may be executed without a checksum manifest")
monkeypatch.setattr(u, "apply_installer", _never)
@@ -305,10 +308,12 @@ def test_apply_surfaces_a_verification_failure(
_patch_frozen(monkeypatch)
_patch_latest(monkeypatch, _release("1.6.0"))
- async def _download(asset: Any, checksums: Any, *, dest_dir: Path) -> Path:
+ async def _download(
+ asset: Any, checksums: Any, *, dest_dir: Path, on_progress: Any = None
+ ) -> Path:
raise InstallerUpdateError("PersonalJarvis-Setup-x64.exe failed its SHA-256 check")
- def _never(installer: Path) -> str:
+ def _never(installer: Path, **_kwargs: Any) -> str:
raise AssertionError("a failed verification must never reach the handover")
monkeypatch.setattr(u, "download_and_verify", _download)
@@ -345,3 +350,180 @@ def test_apply_falls_back_to_the_last_good_release(
assert response.status_code == 200
assert seen["asset"].name == SETUP_NAME
+
+
+# --------------------------------------------------------------------------- #
+# The handover ends this app — mission guard first, quit after
+# --------------------------------------------------------------------------- #
+class _FakeKontrollierer:
+ def __init__(self, running: list[str]) -> None:
+ self._running = running
+
+ def running_mission_ids(self) -> list[str]:
+ return list(self._running)
+
+
+class _FakeDesktop:
+ def __init__(self, *, accepts: bool = True) -> None:
+ self.accepts = accepts
+ self.quit_calls = 0
+
+ def request_quit(self) -> bool:
+ self.quit_calls += 1
+ return self.accepts
+
+
+def _client_with(
+ *, missions: list[str] | None = None, desktop: _FakeDesktop | None = None
+) -> TestClient:
+ app = FastAPI()
+ app.include_router(update_router)
+ if missions is not None:
+ app.state.kontrollierer = _FakeKontrollierer(missions)
+ if desktop is not None:
+ app.state.desktop_app = desktop
+ return TestClient(app)
+
+
+def test_apply_refuses_before_downloading_while_missions_run(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _patch_frozen(monkeypatch)
+ _patch_latest(monkeypatch, _release("1.6.0"))
+
+ async def _never(*_args: Any, **_kwargs: Any) -> Path:
+ raise AssertionError("no download may start while a quit would kill missions")
+
+ monkeypatch.setattr(u, "download_and_verify", _never)
+ desktop = _FakeDesktop()
+
+ response = _client_with(missions=["m-1", "m-2"], desktop=desktop).post(
+ "/api/update/apply"
+ )
+
+ assert response.status_code == 409
+ detail = response.json()["detail"]
+ assert detail["error"] == "missions_running"
+ assert [m["id"] for m in detail["missions"]] == ["m-1", "m-2"]
+ assert desktop.quit_calls == 0
+
+
+def test_apply_with_force_overrides_the_mission_guard(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _patch_frozen(monkeypatch)
+ _patch_latest(monkeypatch, _release("1.6.0"))
+ seen = _capture_install(monkeypatch)
+ desktop = _FakeDesktop()
+
+ response = _client_with(missions=["m-1"], desktop=desktop).post(
+ "/api/update/apply?force=true"
+ )
+
+ assert response.status_code == 200
+ assert seen["installer"].name == SETUP_NAME
+ assert desktop.quit_calls == 1
+
+
+def test_apply_quits_the_app_after_a_successful_handover(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The new version only starts once this process is gone (single instance)."""
+ _patch_frozen(monkeypatch)
+ _patch_latest(monkeypatch, _release("1.6.0"))
+ _capture_install(monkeypatch)
+ desktop = _FakeDesktop()
+
+ body = _client_with(missions=[], desktop=desktop).post("/api/update/apply").json()
+
+ assert body["ok"] is True
+ assert body["quitting"] is True
+ assert body["restart_required"] is False
+ assert desktop.quit_calls == 1
+
+
+def test_apply_without_a_desktop_window_says_to_restart_by_hand(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _patch_frozen(monkeypatch)
+ _patch_latest(monkeypatch, _release("1.6.0"))
+ _capture_install(monkeypatch)
+
+ body = _client_with().post("/api/update/apply").json()
+
+ assert body["ok"] is True
+ assert body["quitting"] is False
+ assert "restart Personal Jarvis" in body["handover"]
+
+
+def test_apply_never_quits_when_the_handover_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _patch_frozen(monkeypatch)
+ _patch_latest(monkeypatch, _release("1.6.0"))
+ _capture_install(monkeypatch)
+
+ def _refuse(installer: Path, **_kwargs: Any) -> str:
+ raise InstallerUpdateError("could not replace the app")
+
+ monkeypatch.setattr(u, "apply_installer", _refuse)
+ desktop = _FakeDesktop()
+
+ response = _client_with(desktop=desktop).post("/api/update/apply")
+
+ assert response.status_code == 502
+ # A failed handover leaves the old version running — it must stay up.
+ assert desktop.quit_calls == 0
+
+
+def test_apply_without_a_desktop_window_skips_the_relaunch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Nothing will quit this process, so a relaunch would only bounce off the lock."""
+ _patch_frozen(monkeypatch)
+ _patch_latest(monkeypatch, _release("1.6.0"))
+ seen = _capture_install(monkeypatch)
+
+ _client_with().post("/api/update/apply")
+
+ assert seen["relaunch"] is False
+
+
+def test_apply_with_a_desktop_window_relaunches(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_frozen(monkeypatch)
+ _patch_latest(monkeypatch, _release("1.6.0"))
+ seen = _capture_install(monkeypatch)
+
+ _client_with(desktop=_FakeDesktop()).post("/api/update/apply")
+
+ assert seen["relaunch"] is True
+
+
+def test_a_mission_started_during_the_download_still_stops_the_handover(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _patch_frozen(monkeypatch)
+ _patch_latest(monkeypatch, _release("1.6.0"))
+ kontrollierer = _FakeKontrollierer([])
+ seen = _capture_install(monkeypatch)
+ real_download = u.download_and_verify
+
+ async def _download_then_mission(*args: Any, **kwargs: Any) -> Path:
+ path = await real_download(*args, **kwargs)
+ kontrollierer._running = ["m-late"]
+ return path
+
+ monkeypatch.setattr(u, "download_and_verify", _download_then_mission)
+ desktop = _FakeDesktop()
+ app = FastAPI()
+ app.include_router(update_router)
+ app.state.kontrollierer = kontrollierer
+ app.state.desktop_app = desktop
+
+ response = TestClient(app).post("/api/update/apply")
+
+ assert response.status_code == 409
+ assert "installer" not in seen
+ assert desktop.quit_calls == 0
+ progress = TestClient(app).get("/api/update/progress").json()
+ assert "missions are running" in str(progress["error"])
diff --git a/tests/unit/web/test_update_progress_route.py b/tests/unit/web/test_update_progress_route.py
index 916a7dcaa5..1be7bedcf9 100644
--- a/tests/unit/web/test_update_progress_route.py
+++ b/tests/unit/web/test_update_progress_route.py
@@ -97,7 +97,7 @@ def test_a_second_apply_is_refused_while_one_runs(client: TestClient) -> None:
task = asyncio.create_task(hold())
await asyncio.sleep(0.05)
try:
- await update_routes.update_apply()
+ await update_routes.update_apply(None)
except HTTPException as exc:
return exc.status_code
finally:
@@ -110,7 +110,7 @@ def test_a_second_apply_is_refused_while_one_runs(client: TestClient) -> None:
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]:
+ async def boom(*_args: object, **_kwargs: object) -> dict[str, object]:
_progress.begin(INSTALL_KIND_FROZEN)
_progress.advance(PHASE_DOWNLOADING, 0.42)
raise RuntimeError("the disk went away")
@@ -119,7 +119,7 @@ def test_a_failed_apply_always_leaves_a_verdict(monkeypatch: pytest.MonkeyPatch)
monkeypatch.setattr(update_routes, "_apply_frozen", boom)
with pytest.raises(RuntimeError):
- asyncio.run(update_routes.update_apply())
+ asyncio.run(update_routes.update_apply(None))
snapshot = _progress.snapshot()
assert snapshot["phase"] == PHASE_FAILED
@@ -130,14 +130,14 @@ def test_a_failed_apply_always_leaves_a_verdict(monkeypatch: pytest.MonkeyPatch)
def test_an_http_failure_records_the_servers_own_reason(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- async def refuse() -> dict[str, object]:
+ async def refuse(*_args: object, **_kwargs: object) -> 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())
+ asyncio.run(update_routes.update_apply(None))
assert "host unreachable" in str(_progress.snapshot()["error"])
@@ -145,7 +145,7 @@ def test_an_http_failure_records_the_servers_own_reason(
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]:
+ async def refuse(*_args: object, **_kwargs: object) -> dict[str, object]:
raise HTTPException(status_code=502, detail="nope")
monkeypatch.setattr(update_routes, "is_frozen", lambda: True)
@@ -153,7 +153,7 @@ def test_the_lock_is_released_after_a_failure(monkeypatch: pytest.MonkeyPatch) -
async def scenario() -> bool:
with pytest.raises(HTTPException):
- await update_routes.update_apply()
+ await update_routes.update_apply(None)
return update_routes._apply_lock.locked()
assert asyncio.run(scenario()) is False