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): close the gaps review found in the native handover

rubenluetke10-beep22a0ce4bc57b
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 82c6b42d67..2a90e62528 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -3793,6 +3793,7 @@ class DesktopApp:
detached_creationflags,
fresh_user_env,
relauncher_command,
+ restart_workdir,
run_restart_quit_sequence,
spawn_detached,
)
@@ -3805,7 +3806,9 @@ class DesktopApp:
try:
import jarvis as _jarvis
- repo_root = str(Path(_jarvis.__file__).resolve().parent.parent)
+ # 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())
diff --git a/jarvis/ui/relauncher.py b/jarvis/ui/relauncher.py
index b90e430e96..0323754c42 100644
--- a/jarvis/ui/relauncher.py
+++ b/jarvis/ui/relauncher.py
@@ -136,6 +136,30 @@ def frozen_self_command(
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,
diff --git a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
index ac87276c0f..5b31c5569d 100644
--- a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
+++ b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
@@ -454,4 +454,54 @@ describe("TopBar update button", () => {
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/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
index d7d1b9277d..2217c5059b 100644
--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
@@ -493,8 +493,8 @@ function UpdateButton() {
}, [busy]);
// The panel closes on a click outside it or on Escape, like every other
- // floating layer — but never mid-update by accident: the progress lives
- // there, and the ring on the button keeps reporting either way.
+ // 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) => {
@@ -585,6 +585,8 @@ function UpdateButton() {
const applyBody = (await applyRes.json().catch(() => ({}))) as {
detail?: unknown;
restart_required?: boolean;
+ quitting?: boolean;
+ handover?: string | null;
deps_warning?: string | null;
desktop_integration_warning?: string | null;
};
@@ -620,6 +622,19 @@ 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
diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.py
index f9b12c07c8..054b1b7ca8 100644
--- a/jarvis/ui/web/update_routes.py
+++ b/jarvis/ui/web/update_routes.py
@@ -925,6 +925,29 @@ def _running_missions(request: Request | None) -> list[str]:
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.
@@ -960,16 +983,7 @@ async def _apply_frozen(
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],
- },
- )
+ _refuse_if_missions_run(request, force=force)
current = _running_version()
asset_name = _frozen_asset_name()
if asset_name is None:
@@ -1042,10 +1056,23 @@ async def _apply_frozen(
# 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))
@@ -1066,9 +1093,12 @@ async def _apply_frozen(
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
- # directory; deleting it here would kill the update mid-flight.
+ # 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
@@ -1227,7 +1257,10 @@ async def update_apply(request: Request, force: bool = False) -> dict[str, objec
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/tests/unit/ui/test_relauncher_frozen.py b/tests/unit/ui/test_relauncher_frozen.py
index 3f98d7210c..b3157bad62 100644
--- a/tests/unit/ui/test_relauncher_frozen.py
+++ b/tests/unit/ui/test_relauncher_frozen.py
@@ -173,3 +173,25 @@ def test_entry_point_dispatches_the_relauncher_flag() -> None:
)
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_update_routes_frozen.py b/tests/unit/ui/web/test_update_routes_frozen.py
index 501e5c72c2..874a61e1c4 100644
--- a/tests/unit/ui/web/test_update_routes_frozen.py
+++ b/tests/unit/ui/web/test_update_routes_frozen.py
@@ -223,8 +223,9 @@ def _capture_install(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
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)
@@ -281,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)
@@ -312,7 +313,7 @@ def test_apply_surfaces_a_verification_failure(
) -> 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)
@@ -462,7 +463,7 @@ def test_apply_never_quits_when_the_handover_fails(
_patch_latest(monkeypatch, _release("1.6.0"))
_capture_install(monkeypatch)
- def _refuse(installer: Path) -> str:
+ def _refuse(installer: Path, **_kwargs: Any) -> str:
raise InstallerUpdateError("could not replace the app")
monkeypatch.setattr(u, "apply_installer", _refuse)
@@ -473,3 +474,56 @@ def test_apply_never_quits_when_the_handover_fails(
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"])