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(desktop): follow replacement instance during startup recovery
rubenluetke10-beepd3cc3c9d69f9
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.pyindex 42c70aecd8..e1b5511406 100644--- a/jarvis/ui/web/launcher.py+++ b/jarvis/ui/web/launcher.py@@ -1061,18 +1061,19 @@ def _holder_pid_from_error(error: Exception) -> int | None:def _discover_holder_pid(error: Exception, meta) -> int | None:"""Name the process that is blocking this desktop launch.- Order: sidecar, the lock-error text, then whoever is bound to the admin- port. A headless boot that never wrote the sidecar still has a pid on+ Order: the lock-error text, sidecar, then whoever is bound to the admin+ port. The lock check may already have rejected a stale sidecar. A headless+ boot that never wrote the sidecar still has a pid onthe port; without this the user got "running process is unknown" andno window."""- pid = None- with contextlib.suppress(Exception):- if meta and meta.get("pid") is not None:- pid = int(meta["pid"])+ pid = _holder_pid_from_error(error)if pid is None:with contextlib.suppress(Exception):- pid = _holder_pid_from_error(error)+ if meta and meta.get("pid") is not None:+ candidate = int(meta["pid"])+ if candidate > 0:+ pid = candidateif pid is None:with contextlib.suppress(Exception):from jarvis.ui.desktop_app import (@@ -1173,7 +1174,13 @@ def _recover_from_already_running(focus = focus or _desktop_app.focus_existing_instance_robustread_meta = read_meta or _desktop_app._read_metaterminate = terminate or _desktop_app._terminate_pid- acquire = acquire or _desktop_app.acquire_single_instance_lock+ # Recovery rechecks ownership around a potentially long-lived dialog.+ # Those checks must never evict a replacement process without its consent.+ if acquire is None:++ def acquire():+ return _desktop_app.acquire_single_instance_lock(terminate=lambda _pid: False)+process_age = process_age or _process_age_secondssleep = sleep or time.sleepnow = now or time.monotonic@@ -1275,6 +1282,46 @@ def _recover_from_already_running()return None+ def _recheck_lock() -> tuple[bool, object]:+ """Take a released lock or follow a replacement; never kill on a probe."""+ try:+ return True, acquire()+ except _desktop_app.SingleInstanceError as latest_error:+ replacement_pid = _holder_pid_from_error(latest_error)+ if replacement_pid is None or replacement_pid == pid:+ return False, None+ logger.info(+ "launcher: holder changed from pid={} to pid={} during recovery",+ pid,+ replacement_pid,+ )+ # 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.+ deadline = now() + max(0.0, booting_grace)+ while True:+ try:+ if focus():+ return True, None+ except Exception as exc: # noqa: BLE001+ logger.warning("launcher: focusing the replacement instance failed: {}", exc)+ if now() >= deadline:+ break+ sleep(min(0.5, max(0.0, deadline - now())))+ _report_startup_failure(+ f"{APP_DISPLAY_NAME} is now running in process {replacement_pid}, "+ "but its window could not be brought forward. "+ "Give it a moment to finish starting, then open the app again."+ )+ return True, None+ except Exception as exc: # noqa: BLE001 — lock I/O failure+ _report_startup_failure(f"{APP_DISPLAY_NAME} could not acquire its start lock: {exc}")+ return True, None++ handled, lock = _recheck_lock()+ if handled:+ return lock+if frozen_window:stuck_detail = (f"{APP_DISPLAY_NAME} is already running (process {pid}), but its "@@ -1305,21 +1352,25 @@ def _recover_from_already_running(if not consented:return None+ handled, lock = _recheck_lock()+ if handled:+ return lock+if not terminate(pid):_report_startup_failure(f"{APP_DISPLAY_NAME} could not stop the running process {pid}. ""End it in the task manager, then start the app again.")return None- try:- lock = acquire()- except Exception as exc: # noqa: BLE001 — SingleInstanceError or lock I/O+ handled, lock = _recheck_lock()+ if not handled:_report_startup_failure(f"{APP_DISPLAY_NAME} stopped process {pid}, but the start lock is still "- f"held. Start the app again in a few seconds.\n\nDetail: {exc}"+ "held. Start the app again in a few seconds.")return None- logger.info("launcher: evicted stuck holder pid={} and took the lock", pid)+ if lock is not None:+ logger.info("launcher: evicted stuck holder pid={} and took the lock", pid)return lockdiff --git a/tests/unit/ui/test_launcher_boot_trace.py b/tests/unit/ui/test_launcher_boot_trace.pyindex e8e85162fd..37179e1f81 100644--- a/tests/unit/ui/test_launcher_boot_trace.py+++ b/tests/unit/ui/test_launcher_boot_trace.py@@ -15,6 +15,7 @@ from pathlib import Pathimport pytest+from jarvis.ui.desktop_app import SingleInstanceErrorfrom jarvis.ui.web import launcher@@ -65,6 +66,8 @@ class _Calls:def acquire(self):self.acquired += 1+ if not self.terminated or not self.killed:+ raise SingleInstanceError("Jarvis is already running (pid=4242).")return _Lock()@@ -249,7 +252,7 @@ def test_a_holder_without_a_window_is_evicted_only_on_yes(monkeypatch):lock = _recover(calls)assert isinstance(lock, _Lock)assert calls.terminated == [4242]- assert calls.acquired == 1+ assert calls.acquired == 3title, message = calls.asked[0]assert "4242" in message and "stuck" in message@@ -258,7 +261,7 @@ def test_declining_the_dialog_keeps_the_holder_alive():calls = _Calls(focused=False, meta={"pid": 4242, "port": 47821}, consent=False)assert _recover(calls) is Noneassert calls.terminated == []- assert calls.acquired == 0+ assert calls.acquired == 1def test_an_unknown_holder_is_reported_not_killed(monkeypatch):@@ -312,10 +315,140 @@ def test_a_kill_that_did_not_take_is_reported(monkeypatch):monkeypatch.setattr(launcher, "_report_startup_failure", seen.append)calls = _Calls(focused=False, meta={"pid": 4242}, consent=True, killed=False)assert _recover(calls) is None- assert calls.acquired == 0+ assert calls.acquired == 2assert seen and "4242" in seen[0]+def test_lock_error_pid_takes_precedence_over_stale_sidecar():+ assert (+ launcher._discover_holder_pid(+ SingleInstanceError("Jarvis is already running (pid=47896)."),+ {"pid": 36580, "port": 47821},+ )+ == 47896+ )++[email protected]("released_on", [1, 2])+def test_released_lock_is_taken_without_terminating_old_holder(released_on):+ calls = _Calls(focused=False, meta={"pid": 4242}, consent=True)++ def acquire():+ calls.acquired += 1+ if calls.acquired < released_on:+ raise SingleInstanceError("Jarvis is already running (pid=4242).")+ return _Lock()++ calls.acquire = acquire+ assert isinstance(_recover(calls), _Lock)+ assert calls.terminated == []+ assert len(calls.asked) == released_on - 1++[email protected]("replaced_on", [1, 2, 3])+def test_replacement_during_recovery_is_focused_without_reusing_consent(monkeypatch, replaced_on):+ calls = _Calls(focused=False, meta={"pid": 4242}, consent=True)+ monkeypatch.setattr(launcher, "_report_startup_failure", calls.reported.append)+ clock = {"t": 0.0}+ focus_times = []++ def acquire():+ calls.acquired += 1+ holder = 47896 if calls.acquired >= replaced_on else 4242+ raise SingleInstanceError(f"Jarvis is already running (pid={holder}).")++ def focus():+ focus_times.append(clock["t"])+ return clock["t"] >= 1.0++ result = launcher._recover_from_already_running(+ SingleInstanceError("Jarvis is already running (pid=4242)."),+ focus=focus,+ read_meta=calls.read_meta,+ ask=calls.ask,+ terminate=calls.terminate,+ acquire=acquire,+ process_age=lambda _pid: None,+ sleep=lambda seconds: clock.__setitem__("t", clock["t"] + seconds),+ now=lambda: clock["t"],+ booting_grace=2.0,+ health=lambda _port: False,+ )+ assert result is None+ assert calls.terminated == ([4242] if replaced_on == 3 else [])+ assert len(calls.asked) == (0 if replaced_on == 1 else 1)+ assert calls.reported == []+ assert focus_times[-1] == 1.0+++def test_default_recovery_acquisition_disables_automatic_eviction(monkeypatch):+ from jarvis.ui import desktop_app++ calls = _Calls(focused=False, meta={"pid": 4242}, consent=False)++ def acquire(*, terminate):+ assert terminate(47896) is False+ return _Lock()++ monkeypatch.setattr(desktop_app, "acquire_single_instance_lock", acquire)+ lock = launcher._recover_from_already_running(+ SingleInstanceError("Jarvis is already running (pid=4242)."),+ focus=calls.focus,+ read_meta=calls.read_meta,+ ask=calls.ask,+ terminate=calls.terminate,+ process_age=lambda _pid: None,+ )+ assert isinstance(lock, _Lock)+ assert calls.asked == []+ assert calls.terminated == []+++def test_replacement_without_window_has_a_bounded_wait_and_is_not_killed(monkeypatch):+ calls = _Calls(focused=False, meta={"pid": 4242}, consent=True)+ monkeypatch.setattr(launcher, "_report_startup_failure", calls.reported.append)+ clock = {"t": 0.0}++ def acquire():+ raise SingleInstanceError("Jarvis is already running (pid=47896).")++ assert (+ launcher._recover_from_already_running(+ SingleInstanceError("Jarvis is already running (pid=4242)."),+ focus=calls.focus,+ read_meta=calls.read_meta,+ ask=calls.ask,+ terminate=calls.terminate,+ acquire=acquire,+ process_age=lambda _pid: None,+ sleep=lambda seconds: clock.__setitem__("t", clock["t"] + seconds),+ now=lambda: clock["t"],+ booting_grace=1.0,+ )+ is None+ )+ assert clock["t"] == 1.0+ assert calls.terminated == []+ assert calls.asked == []+ assert len(calls.reported) == 1+ assert "47896" in calls.reported[0]+ assert "stopped process" not in calls.reported[0]+++def test_lock_io_failure_is_reported_without_terminating_holder(monkeypatch):+ calls = _Calls(focused=False, meta={"pid": 4242}, consent=True)+ monkeypatch.setattr(launcher, "_report_startup_failure", calls.reported.append)++ def acquire():+ raise OSError("lock directory is unavailable")++ calls.acquire = acquire+ assert _recover(calls) is None+ assert calls.asked == []+ assert calls.terminated == []+ assert "lock directory is unavailable" in calls.reported[0]++def test_run_desktop_bounces_with_exit_3_when_recovery_declines(monkeypatch):from jarvis.ui import desktop_app