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(desktop): reopen cleanly while the previous instance quits (#441)

Ruben Lütke0bc7a0cfed4e
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 33abc2dd63..7890ef6fa6 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -507,6 +507,44 @@ def _read_meta() -> dict[str, Any] | None:
return data
+def _mark_instance_quitting() -> None:
+ """Publish a quit before its window and HTTP endpoint disappear."""
+ meta = _read_meta()
+ if not meta or meta.get("pid") != os.getpid() or "quitting_at" in meta:
+ return
+ meta["quitting_at"] = time.time()
+ path = META_FILE_PATH
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.quitting.tmp")
+ try:
+ tmp.write_text(json.dumps(meta), encoding="utf-8")
+ os.replace(tmp, path)
+ except OSError as exc:
+ logging.getLogger(__name__).warning("Could not mark the instance as quitting: %s", exc)
+ finally:
+ try:
+ tmp.unlink(missing_ok=True)
+ except OSError as exc:
+ logging.getLogger(__name__).debug("Could not remove quit marker tempfile: %s", exc)
+
+
+def _quitting_grace_remaining(meta: Any, pid: int) -> float:
+ """The owned quit's remaining exit budget; stale or invalid markers get none.
+
+ Share the desktop's force-exit bound, plus five seconds for OS handle
+ release. A missing window during this interval is expected. The timestamp
+ is written once, so repeated launches cannot extend the deadline.
+ """
+ if not isinstance(meta, dict) or meta.get("pid") != pid:
+ return 0.0
+ try:
+ age = time.time() - float(meta["quitting_at"])
+ except (KeyError, TypeError, ValueError, OverflowError): # Invalid quit metadata grants no wait.
+ return 0.0
+ grace = _SHUTDOWN_FORCE_EXIT_MIN_S + 5.0
+ # The chained comparison also rejects NaN and either infinity.
+ return grace - age if 0.0 <= age < grace else 0.0
+
+
def _fallback_admin_port() -> int:
"""The port a missing sidecar still has to probe.
@@ -1525,6 +1563,11 @@ def acquire_single_instance_lock(
f"Jarvis is already running (port={int(probe_port)} answering, pid unknown)."
)
if pid is not None and _pid_alive(pid):
+ # Closing removes the window and port before the process releases its
+ # lock. Let the launcher await that deliberate handover, not evict a
+ # process still flushing its state because its health endpoint closed.
+ if _quitting_grace_remaining(meta, pid) > 0:
+ raise SingleInstanceError(f"Jarvis is already running (pid={pid}).")
# Holder is alive. Is it actually FUNCTIONAL (serving its port)? A
# healthy instance, the own pid, or a holder with no recorded port is
# respected; only a live-but-non-serving lock-zombie is evicted.
@@ -6746,6 +6789,7 @@ class DesktopApp:
if getattr(self, "_quit_requested_at", None) is not None:
return
self._quit_requested_at = time.monotonic()
+ _mark_instance_quitting()
backstop = getattr(self, "_webview_running", False)
logger.info(
"Main window closed — quitting{}.",
@@ -6958,10 +7002,11 @@ class DesktopApp:
finish()
def shutdown(self) -> int:
- """Idempotent. Stops the server + backend loop, cleans the meta file."""
+ """Idempotent. Stops the server and schedules the backend loop's drain."""
if self._shutdown_done:
return 0
self._shutdown_done = True
+ _mark_instance_quitting()
self._window_visible = False
self._destroy_background_keeper()
@@ -7214,15 +7259,11 @@ class DesktopApp:
"Tray command bridge did not stop within two seconds",
)
- try:
- META_FILE_PATH.unlink(missing_ok=True)
- except Exception as exc: # noqa: BLE001
- # A sidecar left behind makes the NEXT start believe an instance is
- # already running, so it refuses to launch or tries to focus a dead
- # window. Silence here costs the user the next start.
- from loguru import logger as _logger
-
- _logger.warning("Could not remove the instance sidecar: {}", exc)
+ # Keep the quit marker until the OS releases our lock. Cleanup may
+ # continue after this bounded GUI wait, and deleting the sidecar here
+ # makes a reopening launcher lose the only evidence of that handover.
+ # A dead PID never blocks acquisition; the next holder replaces the
+ # sidecar through _write_meta once its backend is ready.
return 0
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 02ff9893e0..80abb94f57 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -1650,7 +1650,12 @@ def _recover_from_already_running(
pid = None
with contextlib.suppress(Exception):
pid = discover(error, meta)
- if pid is not None and pid != os.getpid() and booting_grace > 0:
+ if (
+ pid is not None
+ and pid != os.getpid()
+ and booting_grace > 0
+ and _desktop_app._quitting_grace_remaining(meta, pid) <= 0
+ ):
age = None
with contextlib.suppress(Exception):
age = process_age(pid)
@@ -1714,6 +1719,12 @@ def _recover_from_already_running(
pid,
replacement_pid,
)
+ # Closing the desktop may spawn its background service before
+ # this launch can acquire the lock. That service has no window;
+ # use its existing local handover instead of waiting for one.
+ service_lock = _take_over_from_background_service(expected_pid=replacement_pid)
+ if service_lock is not None:
+ return True, service_lock
# A relauncher can win the lock while this launch is waiting for
# consent. Let its shell appear, even before backend health is up.
# Consent for the old PID does not authorize killing this one.
@@ -1741,6 +1752,24 @@ def _recover_from_already_running(
if handled:
return lock
+ # A user can close and reopen before cleanup has released the old lock.
+ # Its missing window is intentional, not evidence of a stuck process.
+ # The sidecar survives HTTP teardown and ties the bounded wait to this PID.
+ quitting_grace = _desktop_app._quitting_grace_remaining(meta, pid)
+ if quitting_grace > 0:
+ deadline = now() + quitting_grace
+ logger.info(
+ "launcher: holder pid={} is quitting; waiting up to {:.1f}s for its lock",
+ pid,
+ quitting_grace,
+ )
+ while now() < deadline:
+ sleep(min(0.5, max(0.0, deadline - now())))
+ handled, lock = _recheck_lock()
+ if handled:
+ return lock
+ logger.warning("launcher: quitting holder pid={} exceeded its exit budget", pid)
+
if frozen_window:
stuck_detail = (
f"{APP_DISPLAY_NAME} is already running (process {pid}), but its "
@@ -1823,17 +1852,22 @@ def _recover_from_already_running(
return lock
-def _take_over_from_background_service():
+def _take_over_from_background_service(*, expected_pid: int | None = None):
"""The lock, handed back by a running background service — else ``None``."""
try:
- from jarvis.core.background_service import take_over_from_service
+ from jarvis.core.background_service import service_pid, take_over_from_service
from jarvis.ui import desktop_app as _desktop_app
+ def find_service():
+ candidate = service_pid()
+ return candidate if expected_pid is None or candidate == expected_pid else None
+
return take_over_from_service(
lambda: _desktop_app.acquire_single_instance_lock(
timeout=0.5, terminate=lambda _pid: False
),
busy_error=_desktop_app.SingleInstanceError,
+ find_pid=find_service,
)
except Exception: # noqa: BLE001 — fall through to the normal lock handling
import logging as _logging
diff --git a/tests/unit/ui/test_instance_quit_handoff.py b/tests/unit/ui/test_instance_quit_handoff.py
new file mode 100644
index 0000000000..7d46cdaf45
--- /dev/null
+++ b/tests/unit/ui/test_instance_quit_handoff.py
@@ -0,0 +1,192 @@
+"""Reopening during an orderly desktop quit must wait, not offer to kill it."""
+
+import json
+import os
+
+import pytest
+from filelock import FileLock
+
+from jarvis.ui import desktop_app
+from jarvis.ui.web import launcher
+
+
+def test_closing_marks_the_owned_instance_before_teardown(monkeypatch, tmp_path):
+ path = tmp_path / ".jarvis-running"
+ original = {"pid": os.getpid(), "port": 47821, "started_at": 10.0}
+ path.write_text(json.dumps(original), encoding="utf-8")
+ monkeypatch.setattr(desktop_app, "META_FILE_PATH", path)
+ app = desktop_app.DesktopApp.__new__(desktop_app.DesktopApp)
+ app._begin_quit_from_close()
+ marked = json.loads(path.read_text(encoding="utf-8"))
+ assert marked.items() >= original.items()
+ assert marked["quitting_at"] > 0
+ app._begin_quit_from_close()
+ assert json.loads(path.read_text(encoding="utf-8")) == marked
+
+
+def test_quit_does_not_mark_another_instances_sidecar(monkeypatch, tmp_path):
+ path = tmp_path / ".jarvis-running"
+ original = {"pid": os.getpid() + 1, "port": 47821}
+ path.write_text(json.dumps(original), encoding="utf-8")
+ monkeypatch.setattr(desktop_app, "META_FILE_PATH", path)
+ desktop_app.DesktopApp.__new__(desktop_app.DesktopApp)._begin_quit_from_close()
+ assert json.loads(path.read_text(encoding="utf-8")) == original
+
+
+def test_shutdown_retains_quit_marker_until_the_process_releases_its_lock(monkeypatch, tmp_path):
+ path = tmp_path / ".jarvis-running"
+ original = {"pid": os.getpid(), "port": 47821}
+ path.write_text(json.dumps(original), encoding="utf-8")
+ monkeypatch.setattr(desktop_app, "META_FILE_PATH", path)
+ app = desktop_app.DesktopApp.__new__(desktop_app.DesktopApp)
+ app._shutdown_done = False
+ app._destroy_background_keeper = lambda: None
+ app._stop_overlay = lambda: None
+ app._virtual_cursor = app._jarvis_cursor = None
+ app._backend_loop = app._server = app._backend_thread = app._tray = None
+ assert app.shutdown() == 0
+ assert json.loads(path.read_text(encoding="utf-8"))["quitting_at"] > 0
+ # Sidecar state is advisory: only the OS lock authorizes a fresh start.
+ lock = desktop_app.acquire_single_instance_lock(
+ lock_path=tmp_path / "free-lock", meta_path=path,
+ )
+ lock.release()
+ desktop_app._write_meta(47821, os.getpid(), meta_path=path)
+ assert "quitting_at" not in json.loads(path.read_text(encoding="utf-8"))
+
+
+def test_silent_quitting_holder_is_never_automatically_evicted(monkeypatch, tmp_path):
+ lock_path, meta_path = tmp_path / "lock", tmp_path / "meta"
+ meta_path.write_text(json.dumps({"pid": 4242, "port": 47821, "quitting_at": 99.0}))
+ monkeypatch.setattr(desktop_app.time, "time", lambda: 100.0)
+ monkeypatch.setattr(desktop_app, "_pid_alive", lambda _pid: True)
+ killed = []
+ with FileLock(str(lock_path)):
+ with pytest.raises(desktop_app.SingleInstanceError, match="pid=4242"):
+ desktop_app.acquire_single_instance_lock(
+ lock_path=lock_path, meta_path=meta_path,
+ health_probe=lambda _port: False,
+ terminate=lambda pid: killed.append(pid) or False,
+ )
+ assert killed == []
+
+
[email protected]("replacement", [False, True])
[email protected]("process_age", [1.0, 1000.0])
+def test_reopen_waits_for_quit_and_follows_a_replacement(monkeypatch, replacement, process_age):
+ monkeypatch.setattr(desktop_app.time, "time", lambda: 100.0)
+ clock = {"t": 0.0}
+ asked, killed = [], []
+ lock = object()
+
+ def acquire():
+ if clock["t"] < 2.0:
+ raise desktop_app.SingleInstanceError("already running (pid=4242)")
+ if replacement:
+ raise desktop_app.SingleInstanceError("already running (pid=4243)")
+ return lock
+
+ result = launcher._recover_from_already_running(
+ desktop_app.SingleInstanceError("already running (pid=4242)"),
+ focus=lambda: replacement and clock["t"] >= 2.0,
+ read_meta=lambda: {"pid": 4242, "port": 47821, "quitting_at": 99.0},
+ acquire=acquire, ask=lambda *a, **kw: asked.append(a) or False,
+ terminate=lambda pid: killed.append(pid) or True,
+ process_age=lambda _pid: process_age,
+ sleep=lambda seconds: clock.__setitem__("t", clock["t"] + seconds),
+ now=lambda: clock["t"],
+ )
+ assert result is (None if replacement else lock)
+ assert clock["t"] == 2.0
+ assert asked == killed == []
+
+
+def test_background_service_winning_during_quit_hands_back_to_the_desktop(monkeypatch):
+ monkeypatch.setattr(desktop_app.time, "time", lambda: 100.0)
+ clock = {"t": 0.0}
+ handed_back, asked = [], []
+ lock = object()
+
+ def acquire():
+ holder = 4242 if clock["t"] < 2.0 else 4243
+ raise desktop_app.SingleInstanceError(f"already running (pid={holder})")
+
+ def takeover(*, expected_pid=None):
+ handed_back.append(expected_pid)
+ return lock
+
+ monkeypatch.setattr(launcher, "_take_over_from_background_service", takeover)
+ result = launcher._recover_from_already_running(
+ desktop_app.SingleInstanceError("already running (pid=4242)"),
+ focus=lambda: False,
+ read_meta=lambda: {"pid": 4242, "quitting_at": 99.0},
+ acquire=acquire, ask=lambda *a, **kw: asked.append(a) or False,
+ process_age=lambda _pid: 1000.0,
+ sleep=lambda seconds: clock.__setitem__("t", clock["t"] + seconds),
+ now=lambda: clock["t"],
+ )
+ assert result is lock
+ assert handed_back == [4243]
+ assert asked == []
+
+
+def test_service_handover_does_not_target_a_different_replacement(monkeypatch):
+ from jarvis.core import background_service
+
+ monkeypatch.setattr(background_service, "service_pid", lambda: 4243)
+
+ def takeover(acquire, *, busy_error, find_pid):
+ assert find_pid() is None
+ return None
+
+ monkeypatch.setattr(background_service, "take_over_from_service", takeover)
+ assert launcher._take_over_from_background_service(expected_pid=4244) is None
+
+
+ {"pid": 4242},
+ {"pid": 4243, "quitting_at": 99.0},
+ {"pid": 4242, "quitting_at": 1.0},
+ {"pid": 4242, "quitting_at": 101.0},
+ {"pid": 4242, "quitting_at": "bad"},
+ {"pid": 4242, "quitting_at": float("nan")},
+ {"pid": 4242, "quitting_at": float("inf")},
+])
+def test_stale_or_invalid_quit_metadata_does_not_delay_recovery(monkeypatch, meta):
+ monkeypatch.setattr(desktop_app.time, "time", lambda: 100.0)
+ monkeypatch.setattr(launcher, "_holder_alive", lambda _pid: True)
+ asked, slept = [], []
+
+ def acquire():
+ raise desktop_app.SingleInstanceError("already running (pid=4242)")
+
+ launcher._recover_from_already_running(
+ desktop_app.SingleInstanceError("already running (pid=4242)"),
+ focus=lambda: False, read_meta=lambda: meta, acquire=acquire,
+ ask=lambda *a, **kw: asked.append(a) or False,
+ process_age=lambda _pid: 1000.0, sleep=slept.append,
+ )
+ assert len(asked) == 1
+ assert slept == []
+
+
+def test_quitting_holder_that_never_exits_still_reaches_bounded_recovery(monkeypatch):
+ monkeypatch.setattr(desktop_app.time, "time", lambda: 100.0)
+ monkeypatch.setattr(launcher, "_holder_alive", lambda _pid: True)
+ clock = {"t": 0.0}
+ asked = []
+
+ def acquire():
+ raise desktop_app.SingleInstanceError("already running (pid=4242)")
+
+ launcher._recover_from_already_running(
+ desktop_app.SingleInstanceError("already running (pid=4242)"),
+ focus=lambda: False,
+ read_meta=lambda: {"pid": 4242, "quitting_at": 99.0},
+ acquire=acquire, ask=lambda *a, **kw: asked.append(a) or False,
+ process_age=lambda _pid: 1000.0,
+ sleep=lambda seconds: clock.__setitem__("t", clock["t"] + seconds),
+ now=lambda: clock["t"],
+ )
+ assert 40.0 <= clock["t"] <= 50.0
+ assert len(asked) == 1