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): recover a frozen window instead of raising the corpse

rubenluetke10-beep4106d9dc6767
diff --git a/jarvis/speech/warmup_prefetch.py b/jarvis/speech/warmup_prefetch.py
index 70ba9fe4f7..018a044e25 100644
--- a/jarvis/speech/warmup_prefetch.py
+++ b/jarvis/speech/warmup_prefetch.py
@@ -28,6 +28,7 @@ itself — never slower than today, only faster. A missing openWakeWord (headles
VPS base install with no ``[desktop]`` extra) is a logged no-op, never an error,
so the cloud-first boot is unaffected.
"""
+
from __future__ import annotations
import os
@@ -41,6 +42,8 @@ __all__ = [
"start_wake_import_prefetch",
"prefetch_tts_imports",
"start_tts_import_prefetch",
+ "prefetch_anthropic_imports",
+ "start_anthropic_import_prefetch",
]
# Mirror the gate the speech stack itself uses (``_start_speech_and_orb``):
@@ -144,3 +147,48 @@ def start_tts_import_prefetch(
)
thread.start()
return thread
+
+
+def prefetch_anthropic_imports(importer: Callable[[], None] | None = None) -> bool:
+ """Eagerly import the Anthropic SDK, off the first-turn path.
+
+ Why: ``claude_api._ensure_client`` does ``from anthropic import
+ AsyncAnthropic`` on a worker thread (BUG-189 moved it off the event
+ loop). The import still holds the GIL for pydantic model generation.
+ On 2026-08-28 that worker sat in the SDK's datetime regex compile
+ long enough that the in-process Jarvis Bar stopped pumping, Windows
+ marked the process not-responding, and every HTTP route including
+ ``/api/health`` timed out — a frozen window with no Restart that
+ still worked.
+
+ Firing the import once, early, in a daemon thread collapses the later
+ ``_ensure_client`` to a ``sys.modules`` hit. Fail-closed: a host
+ without the optional SDK is a logged no-op. Not gated on
+ ``JARVIS_VOICE`` — recap, wiki and the consolidator reach this
+ import with voice off.
+ """
+
+ def _default_import() -> None:
+ from anthropic import AsyncAnthropic # noqa: F401, PLC0415 — eager warm import
+
+ do_import = importer or _default_import
+ try:
+ do_import()
+ return True
+ except Exception as exc: # noqa: BLE001 — a prefetch must never break boot
+ logger.debug("Anthropic-import prefetch skipped (SDK unavailable): {}", exc)
+ return False
+
+
+def start_anthropic_import_prefetch(
+ *, importer: Callable[[], None] | None = None
+) -> threading.Thread:
+ """Run :func:`prefetch_anthropic_imports` in a daemon thread."""
+ thread = threading.Thread(
+ target=prefetch_anthropic_imports,
+ args=(importer,),
+ name="anthropic-import-prefetch",
+ daemon=True,
+ )
+ thread.start()
+ return thread
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 37683f8fef..ada371632d 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -1650,6 +1650,7 @@ class DesktopApp:
# The wake-critical Phase-A warm-up gates VoiceBootStatus(ready=True) on
# this import; prefetching still overlaps all subsequent backend work.
from jarvis.speech.warmup_prefetch import (
+ start_anthropic_import_prefetch,
start_tts_import_prefetch,
start_wake_import_prefetch,
)
@@ -1659,6 +1660,12 @@ class DesktopApp:
# from the wake import and remains a logged no-op for another provider
# or a headless host without the optional dependency.
start_tts_import_prefetch()
+ # Anthropic SDK import is the GIL stall that froze the desktop
+ # window on 2026-08-28 (worker thread in ``from anthropic import
+ # AsyncAnthropic``; Tk bar stopped pumping; health timed out).
+ # Prefetch here so the first recap/wiki/claude-api turn is a cache
+ # hit. Not voice-gated: those callers run with voice off too.
+ start_anthropic_import_prefetch()
# Start the audio-device settle after the shell paint too. Phase A then
# reuses the result instead of re-paying the blocking stability poll.
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 1a04e6e243..5a1813aba9 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -1092,6 +1092,30 @@ def _process_age_seconds(pid: int) -> float | None:
return None
+def _health_answers(port: int, *, timeout: float = 2.0) -> bool:
+ """True only when ``/api/health`` returns 200. A timeout is False.
+
+ Deliberately stricter than ``desktop_app._default_lock_holder_health``,
+ which treats a bound-but-silent port as alive so a GIL hitch during boot
+ is not evicted. Recovery needs the opposite: a window we raised whose
+ server never answers is the frozen-screen case (live 2026-08-28: title
+ focus succeeded, health timed out, every further click just raised the
+ corpse).
+ """
+ try:
+ import httpx
+ except Exception: # noqa: BLE001 — cannot probe → do not claim a freeze
+ return True
+ try:
+ response = httpx.get(
+ f"http://127.0.0.1:{int(port)}/api/health",
+ timeout=timeout,
+ )
+ except Exception: # noqa: BLE001 — connect fail, timeout, reset
+ return False
+ return response.status_code == 200
+
+
def _recover_from_already_running(
error: Exception,
*,
@@ -1105,6 +1129,7 @@ def _recover_from_already_running(
now=None,
booting_grace: float = 20.0,
discover_pid=None,
+ health=None,
):
"""The lock is held. Bring the holder forward — or, with consent, evict it.
@@ -1112,18 +1137,21 @@ def _recover_from_already_running(
and the lock could then be taken, else ``None`` (the caller exits 3).
The honest case — a healthy instance with a window — is handled by focusing
- it, exactly as before. The case that used to be a silent exit is a holder
- that is alive but has NO window to bring forward (a previous instance whose
- teardown wedged, or a lock the eviction logic could not reclaim): the user
- clicked, nothing happened, and every further click did the same until the
- stuck process died on its own. Now that turns into one native Yes/No box,
- and Yes terminates the holder and takes the lock. No consent, no kill: the
- default button is No and any failure to ask counts as No.
-
- A holder that is only a few seconds old and has no window yet is not
- stuck — it is still booting (the Restart helper used to spawn extras that
- landed here and offered to kill the copy that was about to appear). Wait
- out the remaining boot grace and try to focus again before asking.
+ it, exactly as before. Two stuck cases used to be silent:
+
+ * a holder that is alive but has NO window to bring forward (teardown
+ wedged, or a lock the eviction logic could not reclaim);
+ * a holder whose window IS still on screen but whose server no longer
+ answers (a GIL stall, a hung overlay thread). Focusing that window
+ is not recovery — it is the frozen screen the user already has.
+
+ Both turn into one native Yes/No box, and Yes terminates the holder and
+ takes the lock. No consent, no kill: the default button is No and any
+ failure to ask counts as No.
+
+ A holder that is only a few seconds old and has no window yet (or has a
+ window that has not answered health yet) is not stuck — it is still
+ booting. Wait out the remaining boot grace before asking.
"""
from loguru import logger
@@ -1146,17 +1174,39 @@ def _recover_from_already_running(
focused = bool(focus())
except Exception as exc: # noqa: BLE001
logger.warning("launcher: focusing the running instance failed: {}", exc)
+
+ meta = None
+ with contextlib.suppress(Exception):
+ meta = read_meta()
+ port = None
+ if isinstance(meta, dict) and meta.get("port") is not None:
+ with contextlib.suppress(Exception):
+ port = int(meta["port"])
+
+ def _answers() -> bool | None:
+ """None = not probed (no port / no checker). False = frozen."""
+ if health is None or port is None:
+ return None
+ try:
+ return bool(health(port))
+ except Exception: # noqa: BLE001 — a probe crash is not a freeze
+ return None
+
+ answering = _answers()
+ frozen_window = bool(focused) and answering is False
logger.warning(
"launcher: {} — {}",
error,
- "brought its window forward" if focused else "NO window found",
+ "window is frozen (raised, health silent)"
+ if frozen_window
+ else ("brought its window forward" if focused else "NO window found"),
)
- if focused:
+ # A raised window is recovery only when the holder still answers, or
+ # when we did not probe (tests / no port). A silent health check is
+ # the frozen desktop: keep going so we can ask.
+ if focused and not frozen_window:
return None
- meta = None
- with contextlib.suppress(Exception):
- meta = read_meta()
discover = discover_pid or _discover_holder_pid
pid = None
with contextlib.suppress(Exception):
@@ -1178,27 +1228,32 @@ def _recover_from_already_running(
while now() < deadline:
sleep(0.5)
try:
- if focus():
- logger.info(
- "launcher: booting holder pid={} grew a window — focusing it",
- pid,
- )
- return None
+ focused = bool(focus())
except Exception as exc: # noqa: BLE001
- logger.warning(
- "launcher: focusing the booting instance failed: {}", exc
+ logger.warning("launcher: focusing the booting instance failed: {}", exc)
+ focused = False
+ answering = _answers()
+ frozen_window = bool(focused) and answering is False
+ if focused and not frozen_window:
+ logger.info(
+ "launcher: booting holder pid={} grew a window — focusing it",
+ pid,
)
- # keep waiting; a transient focus miss is not "stuck"
+ return None
try:
focused = bool(focus())
except Exception as exc: # noqa: BLE001
- logger.warning(
- "launcher: final focus of booting holder failed: {}", exc
- )
+ logger.warning("launcher: final focus of booting holder failed: {}", exc)
focused = False
- if focused:
+ answering = _answers()
+ frozen_window = bool(focused) and answering is False
+ if focused and not frozen_window:
return None
- logger.info("launcher: booting holder pid={} never grew a window", pid)
+ logger.info(
+ "launcher: booting holder pid={} {}",
+ pid,
+ "grew a frozen window" if frozen_window else "never grew a window",
+ )
if pid is None or pid == os.getpid():
_report_startup_failure(
f"{APP_DISPLAY_NAME} reports that it is already running, but no window "
@@ -1207,14 +1262,24 @@ def _recover_from_already_running(
)
return None
+ if frozen_window:
+ stuck_detail = (
+ f"{APP_DISPLAY_NAME} is already running (process {pid}), but its "
+ "window is frozen and not answering. It is probably stuck.\n\n"
+ "Stop that process and start fresh?"
+ )
+ else:
+ stuck_detail = (
+ f"{APP_DISPLAY_NAME} is already running (process {pid}), but it has no "
+ "window that could be brought to the front. It is probably stuck.\n\n"
+ "Stop that process and start fresh?"
+ )
consented = False
try:
consented = bool(
ask(
f"{APP_DISPLAY_NAME} is already running",
- f"{APP_DISPLAY_NAME} is already running (process {pid}), but it has no "
- "window that could be brought to the front. It is probably stuck.\n\n"
- "Stop that process and start fresh?",
+ stuck_detail,
)
)
except Exception as exc: # noqa: BLE001
@@ -1266,7 +1331,11 @@ def _run_desktop(cfg, use_lock: bool) -> int:
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)
+ lock = _recover_from_already_running(
+ exc,
+ focus=focus_existing_instance_robust,
+ health=_health_answers,
+ )
if lock is None:
return 3
diff --git a/tests/unit/speech/test_warmup_prefetch.py b/tests/unit/speech/test_warmup_prefetch.py
index c1de35fc61..3c4f189812 100644
--- a/tests/unit/speech/test_warmup_prefetch.py
+++ b/tests/unit/speech/test_warmup_prefetch.py
@@ -8,12 +8,15 @@ Pins the contract:
* the starter spawns a daemon thread when voice is enabled;
* the starter is a no-op when ``JARVIS_VOICE`` disables voice.
"""
+
from __future__ import annotations
import threading
from jarvis.speech.warmup_prefetch import (
+ prefetch_anthropic_imports,
prefetch_wake_imports,
+ start_anthropic_import_prefetch,
start_wake_import_prefetch,
)
@@ -58,3 +61,26 @@ def test_start_noop_for_off_and_false_tokens(monkeypatch) -> None:
for token in ("off", "FALSE", " 0 "):
monkeypatch.setenv("JARVIS_VOICE", token)
assert start_wake_import_prefetch(importer=lambda: None) is None
+
+
+def test_anthropic_prefetch_returns_true_on_successful_import() -> None:
+ called: list[int] = []
+ assert prefetch_anthropic_imports(lambda: called.append(1)) is True
+ assert called == [1]
+
+
+def test_anthropic_prefetch_swallows_import_error() -> None:
+ def _boom() -> None:
+ raise ImportError("no anthropic on this host")
+
+ assert prefetch_anthropic_imports(_boom) is False
+
+
+def test_anthropic_prefetch_is_not_gated_on_voice(monkeypatch) -> None:
+ monkeypatch.setenv("JARVIS_VOICE", "0")
+ done = threading.Event()
+ thread = start_anthropic_import_prefetch(importer=done.set)
+ assert thread is not None
+ assert thread.daemon is True
+ thread.join(timeout=2)
+ assert done.is_set()
diff --git a/tests/unit/ui/test_desktop_backend_start_order.py b/tests/unit/ui/test_desktop_backend_start_order.py
index 963b369988..a8cf8f8a39 100644
--- a/tests/unit/ui/test_desktop_backend_start_order.py
+++ b/tests/unit/ui/test_desktop_backend_start_order.py
@@ -184,6 +184,7 @@ def test_desktop_voice_start_does_not_wait_for_brain_ready(monkeypatch, tmp_path
"jarvis.speech.warmup_prefetch",
start_wake_import_prefetch=lambda: None,
start_tts_import_prefetch=lambda: None,
+ start_anthropic_import_prefetch=lambda: None,
)
_install_fake_module(
monkeypatch,
@@ -204,12 +205,19 @@ def test_desktop_voice_start_does_not_wait_for_brain_ready(monkeypatch, tmp_path
monkeypatch,
"jarvis.state.chat_store",
ChatStore=_FakeChatStore,
+ ChatMessage=type("ChatMessage", (), {}),
default_chats_db_path=lambda _data_dir: tmp_path / "chats.db",
)
_install_fake_module(
monkeypatch,
"jarvis.state.supervisor",
Supervisor=_FakeSupervisor,
+ SupervisorState=type("SupervisorState", (), {}),
+ )
+ _install_fake_module(
+ monkeypatch,
+ "jarvis.state.turn_trace",
+ TurnTraceCollector=lambda _bus: SimpleNamespace(),
)
_install_fake_module(
monkeypatch,
diff --git a/tests/unit/ui/test_launcher_boot_trace.py b/tests/unit/ui/test_launcher_boot_trace.py
index 8a120ff58f..e8e85162fd 100644
--- a/tests/unit/ui/test_launcher_boot_trace.py
+++ b/tests/unit/ui/test_launcher_boot_trace.py
@@ -87,6 +87,24 @@ def _recover(calls: _Calls):
)
+def test_health_answers_treats_a_timeout_as_dead(monkeypatch):
+ """A bound port that never replies is the frozen desktop, not 'alive'."""
+ import sys
+ from types import ModuleType
+
+ class _Timeout(Exception):
+ pass
+
+ fake = ModuleType("httpx")
+
+ def _get(url, timeout=2.0):
+ raise _Timeout("read timeout")
+
+ fake.get = _get # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "httpx", fake)
+ assert launcher._health_answers(47821) is False
+
+
def test_a_healthy_holder_is_focused_and_never_asked_about(monkeypatch):
calls = _Calls(focused=True, meta={"pid": 4242, "port": 47821}, consent=True)
assert _recover(calls) is None
@@ -94,6 +112,83 @@ def test_a_healthy_holder_is_focused_and_never_asked_about(monkeypatch):
assert calls.terminated == []
+def test_a_frozen_window_is_asked_about_not_just_raised():
+ """A window we can raise is not recovery when the server is silent.
+
+ Live 2026-08-28: the GIL-stalled desktop still had a title, so the
+ second click brought the frozen window forward and exited. The user
+ kept staring at a corpse.
+ """
+ calls = _Calls(focused=True, meta={"pid": 4242, "port": 47821}, consent=False)
+ result = launcher._recover_from_already_running(
+ RuntimeError("Jarvis is already running (pid=4242)."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=calls.ask,
+ terminate=calls.terminate,
+ acquire=calls.acquire,
+ process_age=lambda _pid: None,
+ discover_pid=_meta_pid,
+ health=lambda _port: False,
+ )
+ assert result is None
+ assert calls.asked
+ assert calls.terminated == []
+ title, message = calls.asked[0]
+ assert "frozen" in message
+ assert "4242" in message
+
+
+def test_a_frozen_window_is_evicted_on_yes():
+ calls = _Calls(focused=True, meta={"pid": 4242, "port": 47821}, consent=True)
+ lock = launcher._recover_from_already_running(
+ RuntimeError("Jarvis is already running (pid=4242)."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=calls.ask,
+ terminate=calls.terminate,
+ acquire=calls.acquire,
+ process_age=lambda _pid: None,
+ discover_pid=_meta_pid,
+ health=lambda _port: False,
+ )
+ assert isinstance(lock, _Lock)
+ assert calls.terminated == [4242]
+
+
+def test_a_young_frozen_window_is_waited_for_until_health_returns():
+ """Boot can miss a 2 s health check. Do not offer to kill it yet."""
+
+ class _Booting(_Calls):
+ def __init__(self):
+ super().__init__(focused=True, meta={"pid": 4242, "port": 47821}, consent=True)
+ self.health_n = 0
+
+ def health(self, _port):
+ self.health_n += 1
+ return self.health_n >= 4
+
+ calls = _Booting()
+ clock = {"t": 0.0}
+ result = launcher._recover_from_already_running(
+ RuntimeError("Jarvis is already running (pid=4242)."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=calls.ask,
+ terminate=calls.terminate,
+ acquire=calls.acquire,
+ process_age=lambda _pid: 2.0,
+ sleep=lambda s: clock.__setitem__("t", clock["t"] + s),
+ now=lambda: clock["t"],
+ booting_grace=5.0,
+ health=calls.health,
+ )
+ assert result is None
+ assert calls.asked == []
+ assert calls.terminated == []
+ assert calls.health_n >= 4
+
+
def test_a_young_holder_is_waited_for_not_killed():
"""A restart sibling that lands here while the real copy is still booting
must not offer to kill it. Wait until a window appears, then focus it."""