Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(update): bring a natively installed app back after an update or restart
rubenluetke10-beep7dc07b47e47b
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex cf72156ab5..6f9a884a44 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -689,6 +689,24 @@ mount that disappears when the app exits — and the uninstall path would deleteshortcuts 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__.pyindex 67c4623ae3..00756b5acd 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.pyindex 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 thehandover could not be completed — the running app then keeps working on theold 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_nameactive_runner = SubprocessCommandRunner() if runner is None else runner+ old_pid = os.getpid() if wait_for_pid is None else wait_for_pidif 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 exclog.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 exclog.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.pyindex 9e13869b5a..82c6b42d67 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -3792,6 +3792,7 @@ class DesktopApp:desktop_launch_args,detached_creationflags,fresh_user_env,+ relauncher_command,run_restart_quit_sequence,spawn_detached,)@@ -3805,14 +3806,9 @@ class DesktopApp:import jarvis as _jarvisrepo_root = str(Path(_jarvis.__file__).resolve().parent.parent)- argv = [- sys.executable,- "-m",- "jarvis.ui.relauncher",- str(os.getpid()),- repo_root,- *desktop_launch_args(),- ]+ # ``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_unelevateddiff --git a/jarvis/ui/relauncher.py b/jarvis/ui/relauncher.pyindex 48b392ab51..b90e430e96 100644--- a/jarvis/ui/relauncher.py+++ b/jarvis/ui/relauncher.py@@ -84,6 +84,88 @@ def _desktop_overrides(*, port: int | None, dev: bool, no_lock: bool) -> tuple[sreturn 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 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 +177,13 @@ def build_launch_command(never attach TCC access to a raw Python interpreter. A missing or invalidbundle therefore fails closed; the managed installer/repair path ownsrecreating 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_instanceidentity = current_instance()diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.pyindex 93dfced50f..f9b12c07c8 100644--- a/jarvis/ui/web/update_routes.py+++ b/jarvis/ui/web/update_routes.py@@ -71,7 +71,7 @@ from collections.abc import Callablefrom pathlib import Pathfrom typing import Any, Literal-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, HTTPException, Requestfrom jarvis.core.branding import (MANAGED_INSTALL_MARKER,@@ -910,14 +910,66 @@ 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 _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, amissing or mismatching SHA-256 all raise before anything is executed. Therunning 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)+ if not force:+ running = _running_missions(request)+ if running:+ raise HTTPException(+ status_code=409,+ detail={+ "error": "missions_running",+ "missions": [{"id": mid, "title": ""} for mid in running],+ },+ )current = _running_version()asset_name = _frozen_asset_name()if asset_name is None:@@ -1009,6 +1061,10 @@ 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 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"# 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@@ -1021,11 +1077,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 +1205,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,7 +1224,7 @@ 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))diff --git a/packaging/windows/PersonalJarvis.iss b/packaging/windows/PersonalJarvis.issindex c30c582a6f..58c9b3b198 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,9 @@ beginif CurUninstallStep = usPostUninstall thenRemoveDirFromUserPath(ExpandConstant('{app}'));end;++{ True when the in-app updater passed /RELAUNCH=1 (see the [Run] section). }+function RelaunchRequested: Boolean;+begin+ Result := ExpandConstant('{param:RELAUNCH|0}') = '1';+end;diff --git a/scripts/ci/test-baseline-linux.json b/scripts/ci/test-baseline-linux.jsonindex b350577aea..2dc1239a97 100644--- a/scripts/ci/test-baseline-linux.json+++ b/scripts/ci/test-baseline-linux.json@@ -151,7 +151,6 @@"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",diff --git a/tests/unit/core/test_installer_update.py b/tests/unit/core/test_installer_update.pyindex 92775618ea..104918dc3d 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 annotationsimport hashlib+import os+import stat+import subprocess+import sys+import timefrom pathlib import Pathimport pytestfrom 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,40 @@ 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]++def test_handover_refuses_a_missing_file(tmp_path: Path) -> None:with pytest.raises(InstallerUpdateError, match="does not exist"):apply_installer(@@ -276,10 +309,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 +380,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 +415,133 @@ 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+++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.pyindex 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.pynew file mode 100644index 0000000000..3f98d7210c--- /dev/null+++ b/tests/unit/ui/test_relauncher_frozen.py@@ -0,0 +1,175 @@+"""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()diff --git a/tests/unit/ui/web/test_update_routes_frozen.py b/tests/unit/ui/web/test_update_routes_frozen.pyindex badf65e88f..501e5c72c2 100644--- a/tests/unit/ui/web/test_update_routes_frozen.py+++ b/tests/unit/ui/web/test_update_routes_frozen.py@@ -349,3 +349,127 @@ def test_apply_falls_back_to_the_last_good_release(assert response.status_code == 200assert 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) -> 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 == 0diff --git a/tests/unit/web/test_update_progress_route.py b/tests/unit/web/test_update_progress_route.pyindex 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_codefinally:@@ -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