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.

perf(desktop): the health watchdog stops rebuilding its HTTP client

Harald2a1dbf46e82c
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 63ee1a420c..df6208e526 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -4787,6 +4787,36 @@ class DesktopApp:
time.sleep(0.25)
return False
+ def _health_probe_client(self) -> Any | None:
+ """The ONE client the health probe reuses. ``None`` when httpx is absent.
+
+ ``httpx.get()`` is a client per call, and building a client builds an
+ SSL context — ``ssl.create_default_context()`` reads and parses the
+ whole CA bundle — even when the URL is plain ``http://`` on loopback
+ and no certificate will ever be checked. At one probe a second that is
+ a CA bundle parsed 3600 times an hour for nothing.
+
+ Measured on the maintainer's laptop 2026-08-21: ``create_default_context``
+ was **54 % of all backend CPU time**, by a wide margin the single
+ hottest thing the process did while idle. Built once and reused, it is
+ paid once per run.
+ """
+ existing = getattr(self, "_health_http", None)
+ if existing is not None:
+ return existing
+ try:
+ import httpx
+ except Exception as exc: # noqa: BLE001
+ from loguru import logger
+
+ logger.debug("Health probe: httpx unavailable ({})", exc)
+ return None
+ # Annotated loosely on purpose: httpx is an optional import here, so
+ # the attribute must also be allowed to go back to None on shutdown.
+ client: Any = httpx.Client(timeout=1.0)
+ self._health_http = client
+ return client
+
def _backend_healthy(self) -> bool:
"""One quick ``/api/health`` probe — is the server answering right now?
@@ -4794,13 +4824,16 @@ class DesktopApp:
a second and needs the ANSWER, including the honest "no" while the loop
is frozen. ``_wait_for_backend``'s poll and the lock holder's four-try
probe both mean something else.
+
+ The client behind it is reused rather than rebuilt per call; see
+ ``_health_probe_client`` for what that costs otherwise.
"""
try:
- import httpx
-
- r = httpx.get(
+ client = self._health_probe_client()
+ if client is None:
+ return False
+ r = client.get(
f"http://127.0.0.1:{self.cfg.ui.admin_api_port}/api/health",
- timeout=1.0,
)
return bool(r.status_code == 200)
except Exception: # noqa: BLE001 — an unreachable server is the answer
@@ -5543,6 +5576,15 @@ class DesktopApp:
with suppress(Exception):
watchdog.stop()
+ # The watchdog's probe client outlives the watchdog itself; close it
+ # here so the connection it keeps to our own port does not hold a
+ # socket open while the server underneath is being torn down.
+ probe_client = getattr(self, "_health_http", None)
+ if probe_client is not None:
+ with suppress(Exception):
+ probe_client.close()
+ self._health_http = None
+
# Hide the orb overlay first — the event path (pipeline → supervisor
# → bus → OrbBridge) doesn't reliably reach the bridge anymore during a
# hard loop stop. A direct hide() guarantees the desktop icon
diff --git a/tests/unit/ui/test_desktop_health_probe.py b/tests/unit/ui/test_desktop_health_probe.py
new file mode 100644
index 0000000000..68a8d2cde0
--- /dev/null
+++ b/tests/unit/ui/test_desktop_health_probe.py
@@ -0,0 +1,166 @@
+"""The blank-window watchdog's health probe must not rebuild its client.
+
+The watchdog asks ``/api/health`` once a second, forever, and the first
+version asked through ``httpx.get()``. That is a fresh client per call, and
+building a client builds an SSL context — ``ssl.create_default_context()``
+reads and parses the entire CA bundle — even though the URL is plain
+``http://`` on loopback where no certificate is ever checked.
+
+Profiled on the maintainer's laptop 2026-08-21 while the app sat idle,
+``create_default_context`` was **54 % of all backend CPU time**: by a wide
+margin the hottest thing the process did, spent entirely on certificates for
+a connection to itself.
+
+These tests pin the client to one build per run, and pin the two behaviours
+that must survive that change: an unreachable server still answers "no", and
+a missing httpx still answers "no" instead of raising.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+from typing import Any
+
+import pytest
+
+from jarvis.ui.desktop_app import DesktopApp
+
+
+class _Cfg:
+ """Just the one config value the probe reads."""
+
+ def __init__(self, port: int = 47821) -> None:
+ self.ui = types.SimpleNamespace(admin_api_port=port)
+
+
+class _FakeApp:
+ """The attribute surface the probe actually touches.
+
+ A real ``DesktopApp`` would boot a log sink, a config load and a session
+ token; the probe needs a port and somewhere to cache a client.
+ """
+
+ def __init__(self, port: int = 47821) -> None:
+ self.cfg = _Cfg(port)
+
+ _health_probe_client = DesktopApp._health_probe_client
+ _backend_healthy = DesktopApp._backend_healthy
+
+
+class _Response:
+ def __init__(self, status_code: int) -> None:
+ self.status_code = status_code
+
+
+class _FakeClient:
+ """Counts its own construction, because that is the thing under test."""
+
+ built = 0
+
+ def __init__(self, **kwargs: Any) -> None:
+ type(self).built += 1
+ self.kwargs = kwargs
+ self.calls: list[str] = []
+ self.closed = False
+ self.status = 200
+ self.raises: Exception | None = None
+
+ def get(self, url: str, **_: Any) -> _Response:
+ self.calls.append(url)
+ if self.raises is not None:
+ raise self.raises
+ return _Response(self.status)
+
+ def close(self) -> None:
+ self.closed = True
+
+
+def fake_httpx(monkeypatch: pytest.MonkeyPatch) -> types.ModuleType:
+ """A stand-in ``httpx`` the probe's local import will find."""
+ _FakeClient.built = 0
+ module = types.ModuleType("httpx")
+ module.Client = _FakeClient # type: ignore[attr-defined]
+
+ def _forbidden(*_a: Any, **_kw: Any) -> None:
+ raise AssertionError("httpx.get() builds a client per call — use the reused one")
+
+ module.get = _forbidden # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "httpx", module)
+ return module
+
+
+def test_client_is_built_once_across_many_probes(fake_httpx: types.ModuleType) -> None:
+ app = _FakeApp()
+
+ for _ in range(50):
+ assert app._backend_healthy() is True
+
+ assert _FakeClient.built == 1, "one client per run, not one per probe"
+ assert len(app._health_http.calls) == 50
+
+
+def test_probe_hits_the_configured_port(fake_httpx: types.ModuleType) -> None:
+ app = _FakeApp(port=51234)
+
+ app._backend_healthy()
+
+ assert app._health_http.calls == ["http://127.0.0.1:51234/api/health"]
+
+
+def test_non_200_is_not_healthy(fake_httpx: types.ModuleType) -> None:
+ app = _FakeApp()
+ app._backend_healthy()
+ app._health_http.status = 503
+
+ assert app._backend_healthy() is False
+
+
+def test_unreachable_server_answers_no(fake_httpx: types.ModuleType) -> None:
+ """A refused connection is the answer, not an exception."""
+ app = _FakeApp()
+ app._backend_healthy()
+ app._health_http.raises = OSError("connection refused")
+
+ assert app._backend_healthy() is False
+
+
+def test_reused_client_survives_a_failed_probe(fake_httpx: types.ModuleType) -> None:
+ """One bad probe must not throw the client away and start rebuilding."""
+ app = _FakeApp()
+ app._backend_healthy()
+ app._health_http.raises = OSError("connection refused")
+ assert app._backend_healthy() is False
+
+ app._health_http.raises = None
+ assert app._backend_healthy() is True
+ assert _FakeClient.built == 1
+
+
+def test_missing_httpx_answers_no_without_raising(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A build without httpx must degrade, not crash the watchdog."""
+ import builtins
+
+ real_import = builtins.__import__
+
+ def _no_httpx(name: str, *args: Any, **kwargs: Any) -> Any:
+ if name == "httpx":
+ raise ImportError("no httpx in this build")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _no_httpx)
+ app = _FakeApp()
+
+ assert app._health_probe_client() is None
+ assert app._backend_healthy() is False
+
+
+def test_timeout_is_carried_by_the_client(fake_httpx: types.ModuleType) -> None:
+ """The per-call timeout moved onto the client; it must not be lost."""
+ app = _FakeApp()
+ app._backend_healthy()
+
+ assert app._health_http.kwargs.get("timeout") == 1.0