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.

feat(realtime): supervise the managed local server and prewarm it

rubenluetke10-beep07ff273bca56
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.py
index d830e317dd..9fc6f19cb1 100644
--- a/jarvis/plugins/realtime/openai_realtime.py
+++ b/jarvis/plugins/realtime/openai_realtime.py
@@ -1526,11 +1526,11 @@ class LocalRealtimeProvider:
The reference stack's whole process dies silently under load (live
2026-08-06 19:57: its log ends mid-request, the call died with it,
- and nothing owned bringing it back). With a configured
- ``launch_command`` Jarvis owns that: spawn detached, window-less
- (AP-1), stderr into a log under the data dir so the NEXT crash
- finally leaves forensics. Rate-limited so a crash-looping server is
- not hammered (AP-24 doctrine).
+ and nothing owned bringing it back). The actual spawn lives in the
+ supervisor module — ONE code path shared with the boot-time prewarm,
+ so the two can never double-spawn. The provider-level rate limit
+ stays as the first gate (AP-24 doctrine: a crash-looping server is
+ not hammered).
"""
if not self._launch_command or not self._server_is_local_process():
return False
@@ -1539,77 +1539,19 @@ class LocalRealtimeProvider:
return False
LocalRealtimeProvider._last_launch_at = now
import importlib # lazy (AP-26)
- import subprocess # lazy (AP-26)
- from pathlib import Path
# importlib, not a literal ``from jarvis...``: the plugin-module
# contract (no jarvis imports, AST-checked) counts lazy imports too.
- NO_WINDOW_CREATIONFLAGS = importlib.import_module(
- "jarvis.core.process_utils"
- ).NO_WINDOW_CREATIONFLAGS # AP-1
-
- log_dir = Path(os.environ.get("JARVIS_DATA_DIR") or "data")
try:
- log_dir.mkdir(parents=True, exist_ok=True)
- server_log = open( # noqa: SIM115 — handed to the child for its lifetime
- log_dir / "local_realtime_server.log", "ab"
- )
- except OSError as exc:
- log.warning(
- "Local realtime server: could not open %s (%s); the child "
- "runs without a persisted server log.",
- log_dir / "local_realtime_server.log",
- exc,
+ supervisor = importlib.import_module(
+ "jarvis.realtime.local_server.supervisor"
)
- server_log = None
- try:
- if os.name == "nt":
- command: str | list[str] = self._launch_command
- else:
- import shlex
-
- command = shlex.split(self._launch_command)
- child_env = dict(os.environ)
- # The 2026-08-06 19:57 crash left NO trace: the server process
- # died without a Python traceback, which means the fault was
- # native (torch/onnx/ctranslate2 C code). faulthandler prints
- # the low-level stack to stderr on such deaths — and stderr goes
- # into the server log below — so the NEXT native crash finally
- # names its faulting module. Unbuffered output keeps the final
- # lines from dying in a lost buffer.
- child_env.setdefault("PYTHONFAULTHANDLER", "1")
- child_env.setdefault("PYTHONUNBUFFERED", "1")
- # Windows without the symlink privilege: huggingface_hub's
- # symlinked snapshot layout dies with WinError 1314 mid-download
- # (live 2026-08-07), which would brick the server's own model
- # fetches. Copies cost disk, not correctness.
- child_env.setdefault("HF_HUB_DISABLE_SYMLINKS", "1")
- # The managed install's cloud-brain path deliberately keeps the
- # OpenAI key OUT of the persisted launch command (secrets never
- # enter jarvis.toml); the server's OpenAI client reads it from
- # this spawn environment instead. Keyring-held keys are not in
- # os.environ, so inject here — otherwise every turn of a
- # cloud-brained managed server 401s although the install was
- # green (review 2026-08-07). Ollama-brained and keyless servers
- # simply never look at it.
- if not child_env.get("OPENAI_API_KEY"):
- try:
- get_secret = importlib.import_module("jarvis.core.config").get_secret # AP-1
- key = get_secret("openai_api_key", env_fallback="OPENAI_API_KEY") or ""
- if key:
- child_env["OPENAI_API_KEY"] = key
- except Exception: # noqa: BLE001 — a secretless host is a valid host
- log.debug(
- "local-realtime: OpenAI key lookup for spawn env failed",
- exc_info=True,
- )
- subprocess.Popen( # noqa: S603 — the maintainer configured this command
- command,
- stdin=subprocess.DEVNULL,
- stdout=server_log or subprocess.DEVNULL,
- stderr=subprocess.STDOUT,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- env=child_env,
+ outcome = str(
+ supervisor.ensure_running(
+ launch_command=self._launch_command,
+ base_url=self._base_url,
+ reason="connect-revive",
+ )
)
except Exception as exc: # noqa: BLE001 — a bad command must not kill the call
log.warning(
@@ -1619,14 +1561,60 @@ class LocalRealtimeProvider:
exc,
)
return False
- finally:
- if server_log is not None:
- server_log.close()
- log.info(
- "local-realtime: server unreachable — launched the configured "
- "server command; waiting for it to come up"
- )
- return True
+ if outcome == "spawned":
+ log.info(
+ "local-realtime: server unreachable — launched the configured "
+ "server command; waiting for it to come up"
+ )
+ return True
+ log.info("local-realtime: revive skipped (%s)", outcome)
+ return False
+
+ @classmethod
+ async def warm_transport(cls, cfg: Any) -> bool:
+ """Boot-time prewarm (called by the shared realtime warm worker).
+
+ Brings the self-hosted server up BEFORE the first call and makes the
+ Ollama brain model resident, so a warm connect costs a handshake
+ instead of a 45-90 s cold boot plus a multi-second model load. A
+ capability the warm worker discovers by name (AP-21); best-effort by
+ contract — no failure here may reach the caller.
+ """
+ try:
+ provider = cls.from_runtime_config(cfg)
+ if (
+ not provider._base_url
+ or not provider._launch_command
+ or not provider._server_is_local_process()
+ ):
+ return False
+ if _launch_command_target_state(provider._launch_command) == "missing":
+ log.info(
+ "local-realtime: prewarm skipped — the configured launch "
+ "command points at a program that does not exist "
+ "(reinstall or clear it)."
+ )
+ return False
+ import importlib # lazy (AP-26)
+
+ def _warm() -> bool:
+ supervisor = importlib.import_module(
+ "jarvis.realtime.local_server.supervisor"
+ )
+ outcome = str(
+ supervisor.ensure_running(
+ launch_command=provider._launch_command,
+ base_url=provider._base_url,
+ reason="prewarm",
+ )
+ )
+ supervisor.warm_brain(launch_command=provider._launch_command)
+ return outcome in ("spawned", "already-running")
+
+ return await asyncio.to_thread(_warm)
+ except Exception: # noqa: BLE001 — warming is best-effort by contract
+ log.debug("local-realtime: warm_transport failed", exc_info=True)
+ return False
async def open_session(self, cfg: Any) -> _OpenAIRealtimeSession:
if not self._base_url:
diff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.py
index cad8cb509d..e95c214009 100644
--- a/jarvis/realtime/local_server/install.py
+++ b/jarvis/realtime/local_server/install.py
@@ -139,6 +139,23 @@ def _fail(message: str) -> None:
_STATE.finished_at = time.time()
+def _reset_for_tests() -> None:
+ """Reset the module-level progress singleton between tests.
+
+ ``_STATE`` leaks across the pytest session otherwise: a test that drove
+ an install to "error" left every later test reading that phase.
+ """
+ with _LOCK:
+ _STATE.phase = "idle"
+ _STATE.percent = 0
+ _STATE.detail = ""
+ _STATE.error = ""
+ _STATE.started_at = 0.0
+ _STATE.finished_at = 0.0
+ _STATE.log_tail.clear()
+ _STATE.thread = None
+
+
def snapshot() -> dict[str, object]:
"""Poll-shaped view of the running (or last) install."""
with _LOCK:
@@ -344,13 +361,12 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:
with_port = f"{launch_command} --ws_port {_SMOKE_PORT}"
cmd: str | list[str] = with_port if os.name == "nt" else shlex.split(with_port)
smoke_log = install_root() / "smoke_boot.log"
- env = dict(os.environ)
- env.setdefault("PYTHONIOENCODING", "utf-8")
- env.setdefault("PYTHONFAULTHANDLER", "1")
- env.setdefault("PYTHONUNBUFFERED", "1")
- # Windows without the symlink privilege: huggingface_hub's symlinked
- # snapshot layout dies with WinError 1314 mid-download (live 2026-08-07).
- env.setdefault("HF_HUB_DISABLE_SYMLINKS", "1")
+ # The one shared hardening env (faulthandler, unbuffered, HF symlinks on
+ # Windows) — the same the supervisor gives the real server, so the smoke
+ # boot proves the environment the production spawn will actually use.
+ from jarvis.realtime.local_server.supervisor import hardened_child_env
+
+ env = hardened_child_env(inject_openai_key=False)
if brain.kind == "cloud-openai" and brain.api_key:
env.setdefault("OPENAI_API_KEY", brain.api_key)
with open(smoke_log, "ab") as sink:
@@ -434,6 +450,16 @@ def _run_install(confirmed_brain: str = "") -> None:
return
install_root().mkdir(parents=True, exist_ok=True)
+ # A live server holds file locks inside the venv (Windows) and the
+ # GPU everywhere; installing under it is the mid-tree abort of
+ # 2026-08-07. Stop OUR server first — a foreign listener stays.
+ try:
+ from jarvis.realtime.local_server import supervisor
+
+ supervisor.stop(owned_only=True, install_root=install_root())
+ except Exception: # noqa: BLE001 — best effort, the install continues
+ log.debug("install: pre-install server stop failed", exc_info=True)
+
if not _venv_python().exists():
_set("venv", 8, "creating the server's Python environment")
_run([sys.executable, "-m", "venv", str(_venv_dir())], timeout=300)
@@ -575,6 +601,13 @@ def uninstall() -> tuple[bool, str]:
if not root.exists():
_clear_managed_config(root)
return True, "nothing installed"
+ try:
+ from jarvis.realtime.local_server import supervisor
+
+ supervisor.stop(owned_only=True, install_root=root)
+ supervisor.clear_pidfile()
+ except Exception: # noqa: BLE001 — the needle scan below still runs
+ log.debug("uninstall: supervisor stop failed", exc_info=True)
_stop_managed_server(root)
try:
_rmtree_tolerant(root)
diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.py
new file mode 100644
index 0000000000..85871652e6
--- /dev/null
+++ b/jarvis/realtime/local_server/supervisor.py
@@ -0,0 +1,515 @@
+"""Lifecycle owner for the managed local realtime server.
+
+The ONE spawn/stop/warm/ownership path. Before this module existed the server
+was started in two racing places (the desktop warm worker and the provider's
+connect-revive), nothing recorded which process was OURS, nothing could stop
+it deliberately, and the Ollama brain model was evicted after five idle
+minutes so the first turn after a pause paid a cold model load.
+
+Design decisions (plan 2026-08-08):
+
+- **Ownership is the pidfile**, ``local_realtime_server.pid.json`` in the data
+ dir: ``{pid, create_time, port, command, spawned_at}`` — never environment
+ or secrets. A port probe answers "is something serving" (reachability) and
+ is NEVER a kill criterion: a foreign listener on our port must not die for
+ standing there.
+- **The server intentionally survives app exit.** Instant next connect is the
+ entire point of supervising it; ownership exists for deliberate stop /
+ uninstall / reinstall, not for exit cleanup.
+- **Spawns are refused, not queued**, whenever spawning cannot help: install
+ running, port already served, owned process alive, rate limit, non-loopback
+ target. The caller gets the reason as ``"refused:<why>"``.
+
+Everything here is read-only-safe to import (AP-26: no work at import time);
+heavy imports stay function-local.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import socket
+import subprocess
+import threading
+import time
+from pathlib import Path
+
+log = logging.getLogger(__name__)
+
+#: Never spawn more often than this — a crash-looping server is marked bad by
+#: its refusals, not hammered back up (AP-24 doctrine). Mirrors the provider's
+#: historical revive rate limit.
+SPAWN_MIN_INTERVAL_S = 60.0
+
+#: How long the Ollama brain model stays resident after a warm ping. Slides on
+#: every warm call (the desktop warm worker re-arms after each voice session),
+#: so only a genuinely idle multi-hour gap pays a reload.
+BRAIN_KEEP_ALIVE = "2h"
+
+_DEFAULT_PORT = 8765
+
+_LOCK = threading.Lock()
+_last_spawn_at: float = float("-inf")
+
+
+# ── Paths ────────────────────────────────────────────────────────────────
+
+
+def _data_dir() -> Path:
+ env_dir = os.environ.get("JARVIS_DATA_DIR")
+ if env_dir and env_dir.strip():
+ return Path(env_dir.strip()).resolve()
+ from jarvis.core.config import DATA_DIR # lazy (AP-26)
+
+ return DATA_DIR
+
+
+def _pidfile() -> Path:
+ return _data_dir() / "local_realtime_server.pid.json"
+
+
+def _server_log() -> Path:
+ return _data_dir() / "local_realtime_server.log"
+
+
+# ── Address handling ─────────────────────────────────────────────────────
+
+
+def _host_port(base_url: str) -> tuple[str, int]:
+ """Host and port of a configured server address, defaults preserved."""
+ text = (base_url or "").strip()
+ if "://" in text:
+ text = text.split("://", 1)[1]
+ text = text.split("/", 1)[0]
+ host, _, port_text = text.partition(":")
+ try:
+ port = int(port_text) if port_text else _DEFAULT_PORT
+ except ValueError:
+ port = _DEFAULT_PORT
+ return host or "localhost", port
+
+
+def _is_loopback(host: str) -> bool:
+ return host.lower() in {"localhost", "127.0.0.1", "::1"}
+
+
+def _port_open(port: int, timeout: float = 1.0) -> bool:
+ try:
+ with socket.create_connection(("127.0.0.1", port), timeout=timeout):
+ return True
+ except OSError:
+ return False
+
+
+# ── Ownership (pidfile) ──────────────────────────────────────────────────
+
+
+def _read_pidfile() -> dict[str, object] | None:
+ try:
+ raw = _pidfile().read_text(encoding="utf-8")
+ except OSError:
+ return None
+ try:
+ data = json.loads(raw)
+ except ValueError:
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _process_create_time(pid: int) -> float | None:
+ """The process's kernel start stamp, or ``None`` when unverifiable."""
+ try:
+ import psutil # type: ignore[import-untyped] # lazy, optional
+ except ImportError:
+ return None
+ try:
+ return float(psutil.Process(pid).create_time())
+ except Exception: # noqa: BLE001 — gone/denied both mean "not verifiable"
+ return None
+
+
+def _owned_process() -> tuple[int | None, bool]:
+ """(pid, alive) of the recorded server, PID-reuse safe.
+
+ ``create_time`` recorded at spawn is compared against the live process:
+ a machine reboot can hand the same pid to an innocent process, and a
+ match within a second is the difference between "our server" and
+ "somebody's browser". Without psutil the answer degrades to "recorded
+ but unverifiable" — reported as not alive so no kill path ever trusts it.
+ """
+ record = _read_pidfile()
+ if record is None:
+ return None, False
+ try:
+ pid = int(record.get("pid", 0) or 0)
+ except (TypeError, ValueError):
+ return None, False
+ if pid <= 0:
+ return None, False
+ live_created = _process_create_time(pid)
+ if live_created is None:
+ return pid, False
+ recorded = record.get("create_time")
+ try:
+ recorded_f = float(recorded) if recorded is not None else None
+ except (TypeError, ValueError):
+ recorded_f = None
+ if recorded_f is None:
+ return pid, False
+ return pid, abs(live_created - recorded_f) < 1.0
+
+
+def _write_pidfile(pid: int, port: int, command: str) -> None:
+ payload = {
+ "pid": pid,
+ "create_time": _process_create_time(pid),
+ "port": port,
+ "command": command,
+ "spawned_at": time.time(),
+ }
+ try:
+ _pidfile().parent.mkdir(parents=True, exist_ok=True)
+ _pidfile().write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ except OSError:
+ log.warning("local-realtime supervisor: pidfile write failed", exc_info=True)
+
+
+def clear_pidfile() -> None:
+ try:
+ _pidfile().unlink(missing_ok=True)
+ except OSError: # pragma: no cover — best effort
+ log.debug("local-realtime supervisor: pidfile unlink failed", exc_info=True)
+
+
+# ── Environment ──────────────────────────────────────────────────────────
+
+
+def hardened_child_env(*, inject_openai_key: bool) -> dict[str, str]:
+ """The spawn environment every managed-server child gets.
+
+ One place for the whole hardening story (previously duplicated between
+ the provider revive and the installer smoke boot):
+
+ - faulthandler + unbuffered output so a native crash finally names its
+ faulting module in the server log;
+ - ``HF_HUB_DISABLE_SYMLINKS`` on WINDOWS only — the symlinked snapshot
+ layout dies with WinError 1314 without the symlink privilege (live
+ 2026-08-07); on macOS/Linux symlinks work and save gigabytes;
+ - optionally the OpenAI key from the keyring for the cloud-brained
+ managed server (secrets never enter the persisted launch command).
+ """
+ env = dict(os.environ)
+ env.setdefault("PYTHONIOENCODING", "utf-8")
+ env.setdefault("PYTHONFAULTHANDLER", "1")
+ env.setdefault("PYTHONUNBUFFERED", "1")
+ if os.name == "nt":
+ env.setdefault("HF_HUB_DISABLE_SYMLINKS", "1")
+ if inject_openai_key and not env.get("OPENAI_API_KEY"):
+ try:
+ from jarvis.core.config import get_secret # lazy (AP-26)
+
+ key = get_secret("openai_api_key", env_fallback="OPENAI_API_KEY") or ""
+ if key:
+ env["OPENAI_API_KEY"] = key
+ except Exception: # noqa: BLE001 — a secretless host is a valid host
+ log.debug("supervisor: OpenAI key lookup failed", exc_info=True)
+ return env
+
+
+# ── Status ───────────────────────────────────────────────────────────────
+
+
+def status(base_url: str = "") -> dict[str, object]:
+ """Live runtime view: ``{reachable, port, pid, owned, stale}``.
+
+ ``reachable`` is the port probe (something answers), ``owned`` whether the
+ recorded pid verifiably runs, ``stale`` whether a pidfile exists whose
+ process is gone. ``reachable and not owned`` is the honest "another
+ process serves this port" signal the UI can render.
+ """
+ _host, port = _host_port(base_url)
+ pid, alive = _owned_process()
+ return {
+ "reachable": _port_open(port),
+ "port": port,
+ "pid": pid,
+ "owned": alive,
+ "stale": pid is not None and not alive,
+ }
+
+
+# ── Spawn ────────────────────────────────────────────────────────────────
+
+
+def ensure_running(*, launch_command: str, base_url: str, reason: str) -> str:
+ """Start the server if — and only if — starting can help.
+
+ Returns ``"already-running"`` (port served, or our recorded process is
+ alive and presumably booting), ``"spawned"``, or ``"refused:<why>"``.
+ The single spawn path for BOTH the boot-time prewarm and the connect-time
+ revive, which is what makes their race harmless.
+ """
+ command = (launch_command or "").strip()
+ if not command:
+ return "refused:no-launch-command"
+ host, port = _host_port(base_url)
+ if not _is_loopback(host):
+ return "refused:not-local"
+ with _LOCK:
+ if _port_open(port):
+ return "already-running"
+ pid, alive = _owned_process()
+ if alive:
+ # Our server process exists but has not bound its port yet: it is
+ # mid-boot (models loading). A second spawn would fight it for
+ # the GPU and the port.
+ return "already-running"
+ try:
+ from jarvis.realtime.local_server import install # lazy (AP-26)
+
+ if install.snapshot().get("running"):
+ # Spawning a half-installed venv mid-install proves nothing
+ # and locks files the installer is about to replace.
+ return "refused:install-running"
+ except Exception: # noqa: BLE001 — install state is advisory here
+ log.debug("supervisor: install snapshot unavailable", exc_info=True)
+ global _last_spawn_at
+ now = time.monotonic()
+ if now - _last_spawn_at < SPAWN_MIN_INTERVAL_S:
+ return "refused:rate-limited"
+ _last_spawn_at = now
+ spawned_pid = _spawn(command, reason=reason)
+ if spawned_pid is None:
+ return "refused:spawn-failed"
+ _write_pidfile(spawned_pid, port, command)
+ log.info(
+ "local-realtime supervisor: spawned server pid=%s (%s)",
+ spawned_pid,
+ reason,
+ )
+ return "spawned"
+
+
+def _spawn(command: str, *, reason: str) -> int | None:
+ """Detached, window-less, log-sinked spawn. ``None`` when it failed."""
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # lazy
+
+ try:
+ _server_log().parent.mkdir(parents=True, exist_ok=True)
+ sink = open(_server_log(), "ab") # noqa: SIM115 — handed to the child
+ except OSError as exc:
+ log.warning(
+ "supervisor: could not open %s (%s); child runs without a log",
+ _server_log(),
+ exc,
+ )
+ sink = None
+ try:
+ argv: str | list[str]
+ popen_kwargs: dict[str, object] = {}
+ if os.name == "nt":
+ argv = command
+ else:
+ import shlex
+
+ argv = shlex.split(command)
+ # Its own session/process group, so a deliberate stop can take the
+ # whole tree down with killpg instead of orphaning workers.
+ popen_kwargs["start_new_session"] = True
+ proc = subprocess.Popen( # noqa: S603 — the maintainer configured this command
+ argv,
+ stdin=subprocess.DEVNULL,
+ stdout=sink or subprocess.DEVNULL,
+ stderr=subprocess.STDOUT,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ env=hardened_child_env(inject_openai_key=True),
+ **popen_kwargs,
+ )
+ except Exception as exc: # noqa: BLE001 — a bad command must not kill the caller
+ log.warning(
+ "supervisor: spawning the server failed (%s: %s) — check "
+ "[brain.providers.local-realtime].launch_command (%s)",
+ type(exc).__name__,
+ exc,
+ reason,
+ )
+ return None
+ finally:
+ if sink is not None:
+ sink.close()
+ return proc.pid
+
+
+# ── Stop ─────────────────────────────────────────────────────────────────
+
+
+def stop(*, owned_only: bool = True, install_root: Path | None = None) -> tuple[bool, str]:
+ """Stop the server this install owns. ``(changed, message)``.
+
+ Kill order: the pidfile's verified pid (create_time match) first; when
+ that cannot answer and ``install_root`` is given, fall back to the
+ install-tree needle scan (kills only processes running out of the managed
+ venv). A port match is never a kill criterion. With ``owned_only`` there
+ is no further escalation — a foreign listener stays untouched.
+ """
+ pid, alive = _owned_process()
+ if alive and pid is not None:
+ ok = _kill_pid_tree(pid)
+ clear_pidfile()
+ return ok, f"stopped pid {pid}" if ok else f"could not stop pid {pid}"
+ if pid is not None and not alive:
+ clear_pidfile()
+ if install_root is not None:
+ killed = _kill_by_install_root(install_root)
+ if killed:
+ return True, f"stopped {killed} process(es) from {install_root}"
+ if not owned_only:
+ log.info("supervisor: no owned server process found to stop")
+ return False, "no owned server process found"
+
+
+def _kill_pid_tree(pid: int) -> bool:
+ try:
+ if os.name == "nt":
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # lazy
+
+ subprocess.run(
+ ["taskkill", "/PID", str(pid), "/T", "/F"],
+ capture_output=True,
+ timeout=30,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ return True
+ import signal
+
+ # The spawn used start_new_session, so the pid IS the group leader:
+ # SIGTERM the group, grace, then SIGKILL what remains.
+ try:
+ os.killpg(pid, signal.SIGTERM)
+ except ProcessLookupError:
+ return True
+ except (PermissionError, OSError):
+ os.kill(pid, signal.SIGTERM)
+ deadline = time.monotonic() + 5.0
+ while time.monotonic() < deadline:
+ if _process_create_time(pid) is None and not _pid_exists(pid):
+ return True
+ time.sleep(0.2)
+ try:
+ os.killpg(pid, signal.SIGKILL)
+ except ProcessLookupError:
+ return True
+ except (PermissionError, OSError):
+ os.kill(pid, signal.SIGKILL)
+ return True
+ except Exception: # noqa: BLE001 — best-effort teardown, reported honestly
+ log.warning("supervisor: kill of pid %s incomplete", pid, exc_info=True)
+ return False
+
+
+def _pid_exists(pid: int) -> bool:
+ if pid <= 0:
+ return False
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ except OSError:
+ return False
+ return True
+
+
+def _kill_by_install_root(root: Path) -> int:
+ """Kill processes running out of the managed tree. Needs psutil; else 0."""
+ try:
+ import psutil # type: ignore[import-untyped]
+ except ImportError:
+ log.debug("supervisor: psutil unavailable — skipping needle scan")
+ return 0
+ needle = str(root).lower()
+ killed = 0
+ for proc in psutil.process_iter(["pid", "exe", "cmdline"]):
+ try:
+ exe = (proc.info.get("exe") or "").lower()
+ cmdline = " ".join(proc.info.get("cmdline") or ()).lower()
+ if needle in exe or needle in cmdline:
+ proc.kill()
+ proc.wait(timeout=10)
+ killed += 1
+ except (psutil.Error, OSError): # pragma: no cover — best effort
+ continue
+ return killed
+
+
+# ── Brain warm-up ────────────────────────────────────────────────────────
+
+
+def warm_brain(*, launch_command: str, timeout: float = 5.0) -> bool:
+ """Make the Ollama brain model resident BEFORE the first turn needs it.
+
+ Reads the brain endpoint out of the launch command itself (a capability
+ of the configured artifact, never a provider-name check): with an
+ ``--responses_api_base_url`` pointing at an Ollama ``/v1`` root, one
+ ``/api/generate`` ping with ``keep_alive`` loads the model and keeps it
+ in memory. Without it, Ollama evicts after five idle minutes and the
+ first sentence after a pause pays a multi-second cold load. Best-effort:
+ a non-Ollama endpoint simply answers 404 and nothing changes.
+ """
+ model, brain_url = _brain_endpoint(launch_command)
+ if not model or not brain_url:
+ return False
+ root = brain_url[: -len("/v1")] if brain_url.endswith("/v1") else brain_url
+ payload = json.dumps(
+ {"model": model, "prompt": "", "keep_alive": BRAIN_KEEP_ALIVE, "stream": False}
+ ).encode("utf-8")
+ import urllib.error
+ import urllib.request
+
+ url = f"{root}/api/generate"
+ if not url.startswith(("http://", "https://")):
+ return False
+ request = urllib.request.Request( # noqa: S310 — scheme checked above
+ url, data=payload, headers={"Content-Type": "application/json"}
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=timeout): # noqa: S310
+ pass
+ except (urllib.error.URLError, OSError, ValueError):
+ log.debug("supervisor: brain warm ping failed for %s", url, exc_info=True)
+ return False
+ log.info(
+ "local-realtime supervisor: brain model %s warmed (keep_alive=%s)",
+ model,
+ BRAIN_KEEP_ALIVE,
+ )
+ return True
+
+
+def _brain_endpoint(launch_command: str) -> tuple[str, str]:
+ """(model, responses_api_base_url) parsed from a launch command."""
+ try:
+ import shlex
+
+ tokens = shlex.split(launch_command or "", posix=os.name != "nt")
+ except ValueError:
+ return "", ""
+ model = ""
+ base = ""
+ for index, flag in enumerate(tokens[:-1]):
+ if flag == "--model_name":
+ model = tokens[index + 1].strip('"')
+ elif flag == "--responses_api_base_url":
+ base = tokens[index + 1].strip('"').rstrip("/")
+ return model, base
+
+
+# ── Test support ─────────────────────────────────────────────────────────
+
+
+def _reset_for_tests() -> None:
+ """Reset module-level state (rate limit) between tests."""
+ global _last_spawn_at
+ _last_spawn_at = float("-inf")
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index ad28684888..dd5b786a77 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -2711,19 +2711,84 @@ async def managed_server_install(request: Request) -> dict[str, Any]:
return payload
+def _local_realtime_card(request: Request) -> tuple[str, str]:
+ """(base_url, launch_command) of the local-realtime card, defensively."""
+ cfg = getattr(request.app.state, "config", None) or getattr(
+ request.app.state, "cfg", None
+ )
+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}
+ getter = getattr(providers, "get", None)
+ card = getter("local-realtime") if callable(getter) else None
+ return (
+ str(getattr(card, "base_url", "") or ""),
+ str(getattr(card, "launch_command", "") or ""),
+ )
+
+
@router.get("/providers/local-realtime/managed-server/status")
-async def managed_server_status() -> dict[str, Any]:
- """Install progress AND the independent fail-closed readiness probe.
+async def managed_server_status(request: Request) -> dict[str, Any]:
+ """Install progress, the fail-closed readiness probe, AND the live runtime.
The on-disk probe is the authority (same doctrine as the on-device
speech installs): a tree installed by an earlier app run reads as ready,
and a finished install with a missing component reads as incomplete.
+ ``runtime`` adds what the disk cannot know: whether something is serving
+ the configured port right now and whether that process is OURS.
"""
+ from jarvis.realtime.local_server import supervisor
from jarvis.realtime.local_server.install import server_status, snapshot
+ base_url, _command = _local_realtime_card(request)
progress = snapshot()
status = await asyncio.to_thread(server_status)
- return {"progress": progress, "server": status}
+ runtime = await asyncio.to_thread(supervisor.status, base_url)
+ return {"progress": progress, "server": status, "runtime": runtime}
+
+
[email protected]("/providers/local-realtime/managed-server/start")
+async def managed_server_start(request: Request) -> dict[str, Any]:
+ """Start the managed server now (the same path the prewarm uses).
+
+ 409 with the supervisor's reason when starting cannot help: install in
+ flight, rate-limited, foreign listener on the port, spawn failure. A
+ server that is already up (or booting under our pid) answers ok.
+ """
+ from jarvis.realtime.local_server import supervisor
+
+ base_url, command = _local_realtime_card(request)
+ if not command:
+ raise HTTPException(
+ status_code=409,
+ detail="no launch command is configured — install the managed server first",
+ )
+ outcome = await asyncio.to_thread(
+ lambda: supervisor.ensure_running(
+ launch_command=command, base_url=base_url, reason="rest-start"
+ )
+ )
+ if outcome.startswith("refused:"):
+ raise HTTPException(status_code=409, detail=outcome)
+ # Make the brain model resident too — a started server whose brain still
+ # cold-loads on the first sentence is only half a start.
+ await asyncio.to_thread(lambda: supervisor.warm_brain(launch_command=command))
+ runtime = await asyncio.to_thread(supervisor.status, base_url)
+ return {"ok": True, "outcome": outcome, "runtime": runtime}
+
+
[email protected]("/providers/local-realtime/managed-server/stop")
+async def managed_server_stop(request: Request) -> dict[str, Any]:
+ """Stop the server THIS install owns (pidfile-verified; never a foreign one)."""
+ from jarvis.realtime.local_server import supervisor
+ from jarvis.realtime.local_server.install import install_root
+
+ base_url, _command = _local_realtime_card(request)
+ changed, message = await asyncio.to_thread(
+ lambda: supervisor.stop(owned_only=True, install_root=install_root())
+ )
+ if not changed:
+ raise HTTPException(status_code=409, detail=message)
+ runtime = await asyncio.to_thread(supervisor.status, base_url)
+ return {"ok": True, "message": message, "runtime": runtime}
@router.delete(
diff --git a/tests/unit/realtime/conftest.py b/tests/unit/realtime/conftest.py
new file mode 100644
index 0000000000..2de16ce847
--- /dev/null
+++ b/tests/unit/realtime/conftest.py
@@ -0,0 +1,24 @@
+"""Shared fixtures for the realtime test tree."""
+
+from __future__ import annotations
+
+import pytest
+
+
[email protected](autouse=True)
+def _reset_local_server_singletons():
+ """Start every test with fresh local-server module state.
+
+ The install engine keeps a module-singleton progress state and the
+ supervisor keeps a spawn rate-limit stamp. Without this reset, whichever
+ test spawned first would rate-limit every later spawn test in the same
+ pytest session, and an install driven to "error" would leak that phase
+ into unrelated tests.
+ """
+ from jarvis.realtime.local_server import install, supervisor
+
+ install._reset_for_tests()
+ supervisor._reset_for_tests()
+ yield
+ install._reset_for_tests()
+ supervisor._reset_for_tests()
diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.py
new file mode 100644
index 0000000000..cd2b8be473
--- /dev/null
+++ b/tests/unit/realtime/local_server/test_supervisor.py
@@ -0,0 +1,291 @@
+"""The lifecycle owner: one spawn path, pidfile ownership, honest refusals.
+
+What these tests pin is the safety story of supervising a process the app
+does not host: a spawn happens only when it can help (no port squatter, no
+mid-install venv, no crash-loop hammering), a stop only ever kills the
+process the pidfile PROVABLY owns (PID-reuse safe), and the Ollama brain
+warm-up parses its endpoint from the launch command instead of asking any
+provider registry (AP-21: the artifact's own capability).
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.realtime.local_server import supervisor
+
+
+def _spawn_ready(monkeypatch, tmp_path: Path) -> list[dict[str, Any]]:
+ """Common arrangement: closed port, no pidfile, fake Popen, tmp data dir."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)
+ spawned: list[dict[str, Any]] = []
+
+ def fake_popen(command: Any, **kwargs: Any) -> SimpleNamespace:
+ spawned.append({"command": command, **kwargs})
+ return SimpleNamespace(pid=4711)
+
+ monkeypatch.setattr(subprocess, "Popen", fake_popen)
+ return spawned
+
+
+# ── Address parsing ──────────────────────────────────────────────────────
+def test_host_port_parses_the_configured_address() -> None:
+ assert supervisor._host_port("http://localhost:8765") == ("localhost", 8765)
+ assert supervisor._host_port("http://127.0.0.1:9000/v1") == ("127.0.0.1", 9000)
+ assert supervisor._host_port("") == ("localhost", 8765)
+ assert supervisor._host_port("localhost") == ("localhost", 8765)
+ assert supervisor._host_port("http://gpu.lan:8443") == ("gpu.lan", 8443)
+
+
+# ── ensure_running: refusals ─────────────────────────────────────────────
+def test_no_launch_command_is_refused(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ outcome = supervisor.ensure_running(
+ launch_command="", base_url="http://localhost:8765", reason="test"
+ )
+ assert outcome == "refused:no-launch-command"
+
+
+def test_remote_targets_are_refused(tmp_path, monkeypatch) -> None:
+ """Launching a process because a LAN box went down would start a second
+ server on the wrong host."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ outcome = supervisor.ensure_running(
+ launch_command="serve", base_url="http://gpu.lan:8443", reason="test"
+ )
+ assert outcome == "refused:not-local"
+
+
+def test_a_served_port_means_already_running(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: True)
+ outcome = supervisor.ensure_running(
+ launch_command="serve", base_url="http://localhost:8765", reason="test"
+ )
+ assert outcome == "already-running"
+
+
+def test_an_alive_owned_process_is_not_double_spawned(monkeypatch, tmp_path) -> None:
+ """Mid-boot the server exists but has not bound its port yet — a second
+ spawn would fight it for the GPU and the port."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)
+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))
+ outcome = supervisor.ensure_running(
+ launch_command="serve", base_url="http://localhost:8765", reason="test"
+ )
+ assert outcome == "already-running"
+
+
+def test_a_running_install_blocks_the_spawn(monkeypatch, tmp_path) -> None:
+ """Spawning a half-installed venv proves nothing and locks files the
+ installer is about to replace."""
+ from jarvis.realtime.local_server import install
+
+ _spawn_ready(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ install, "snapshot", lambda: {"running": True, "phase": "deps"}
+ )
+ outcome = supervisor.ensure_running(
+ launch_command="serve", base_url="http://localhost:8765", reason="test"
+ )
+ assert outcome == "refused:install-running"
+
+
+def test_spawns_are_rate_limited(monkeypatch, tmp_path) -> None:
+ """AP-24 doctrine: a crash-looping server is marked bad, not hammered."""
+ spawned = _spawn_ready(monkeypatch, tmp_path)
+ first = supervisor.ensure_running(
+ launch_command="serve", base_url="http://localhost:8765", reason="test"
+ )
+ second = supervisor.ensure_running(
+ launch_command="serve", base_url="http://localhost:8765", reason="test"
+ )
+ assert first == "spawned"
+ assert second == "refused:rate-limited"
+ assert len(spawned) == 1
+
+
+def test_a_failing_spawn_is_reported_not_raised(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)
+
+ def broken_popen(command: Any, **kwargs: Any) -> SimpleNamespace:
+ raise FileNotFoundError(command)
+
+ monkeypatch.setattr(subprocess, "Popen", broken_popen)
+ outcome = supervisor.ensure_running(
+ launch_command="gone-program", base_url="http://localhost:8765", reason="test"
+ )
+ assert outcome == "refused:spawn-failed"
+
+
+# ── ensure_running: the spawn itself ─────────────────────────────────────
+def test_spawn_is_windowless_and_records_ownership(monkeypatch, tmp_path) -> None:
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ spawned = _spawn_ready(monkeypatch, tmp_path)
+ outcome = supervisor.ensure_running(
+ launch_command="serve --flag", base_url="http://localhost:8765", reason="test"
+ )
+ assert outcome == "spawned"
+ assert spawned[0]["creationflags"] == NO_WINDOW_CREATIONFLAGS # AP-1
+ record = json.loads(
+ (tmp_path / "local_realtime_server.pid.json").read_text(encoding="utf-8")
+ )
+ assert record["pid"] == 4711
+ assert record["port"] == 8765
+ assert record["command"] == "serve --flag"
+ assert "env" not in {k for k in record} # never environment, never secrets
+
+
+def test_pid_reuse_is_never_trusted(monkeypatch, tmp_path) -> None:
+ """A rebooted machine can hand the recorded pid to an innocent process;
+ a create_time mismatch must read as NOT ours."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ (tmp_path / "local_realtime_server.pid.json").write_text(
+ json.dumps({"pid": 4711, "create_time": 1000.0, "port": 8765}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 2000.0)
+ pid, alive = supervisor._owned_process()
+ assert pid == 4711
+ assert alive is False
+
+
+def test_matching_create_time_is_ownership(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ (tmp_path / "local_realtime_server.pid.json").write_text(
+ json.dumps({"pid": 4711, "create_time": 1000.0, "port": 8765}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.4)
+ assert supervisor._owned_process() == (4711, True)
+
+
+# ── stop ─────────────────────────────────────────────────────────────────
+def test_stop_without_ownership_changes_nothing(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ changed, message = supervisor.stop(owned_only=True)
+ assert changed is False
+ assert "no owned" in message
+
+
+def test_stop_kills_only_the_verified_pid(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ (tmp_path / "local_realtime_server.pid.json").write_text(
+ json.dumps({"pid": 4711, "create_time": 1000.0, "port": 8765}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.0)
+ killed: list[int] = []
+ monkeypatch.setattr(
+ supervisor, "_kill_pid_tree", lambda pid: killed.append(pid) or True
+ )
+ changed, message = supervisor.stop(owned_only=True)
+ assert changed is True
+ assert killed == [4711]
+ assert not (tmp_path / "local_realtime_server.pid.json").exists()
+
+
+def test_stop_clears_a_stale_pidfile(monkeypatch, tmp_path) -> None:
+ """A pidfile whose process is gone is bookkeeping debt, not a target."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ (tmp_path / "local_realtime_server.pid.json").write_text(
+ json.dumps({"pid": 4711, "create_time": 1000.0, "port": 8765}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: None)
+ changed, _message = supervisor.stop(owned_only=True)
+ assert changed is False
+ assert not (tmp_path / "local_realtime_server.pid.json").exists()
+
+
+# ── status ───────────────────────────────────────────────────────────────
+def test_status_reports_reachable_and_ownership(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: True)
+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (None, False))
+ status = supervisor.status("http://localhost:8765")
+ assert status == {
+ "reachable": True,
+ "port": 8765,
+ "pid": None,
+ "owned": False,
+ "stale": False,
+ }
+
+
+# ── brain warm-up ────────────────────────────────────────────────────────
+_COMMAND = (
+ '"C:\\tree\\venv\\Scripts\\speech-to-speech.exe" --mode realtime '
+ "--model_name qwen2.5:7b "
+ "--responses_api_base_url http://127.0.0.1:11434/v1 "
+ "--responses_api_api_key ollama"
+)
+
+
+def test_brain_endpoint_is_parsed_from_the_command() -> None:
+ model, base = supervisor._brain_endpoint(_COMMAND)
+ assert model == "qwen2.5:7b"
+ assert base == "http://127.0.0.1:11434/v1"
+
+
+def test_warm_brain_pings_ollama_with_keep_alive(monkeypatch) -> None:
+ import urllib.request
+
+ requests: list[tuple[str, dict[str, Any]]] = []
+
+ class _Response:
+ def __enter__(self) -> _Response:
+ return self
+
+ def __exit__(self, *args: Any) -> None:
+ return None
+
+ def fake_urlopen(request: Any, timeout: float = 0.0) -> _Response:
+ requests.append((request.full_url, json.loads(request.data.decode("utf-8"))))
+ return _Response()
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+ assert supervisor.warm_brain(launch_command=_COMMAND) is True
+ url, payload = requests[0]
+ assert url == "http://127.0.0.1:11434/api/generate"
+ assert payload["model"] == "qwen2.5:7b"
+ assert payload["keep_alive"] == supervisor.BRAIN_KEEP_ALIVE
+
+
+def test_warm_brain_without_a_brain_flag_is_a_noop() -> None:
+ assert supervisor.warm_brain(launch_command="serve --mode realtime") is False
+
+
+def test_warm_brain_swallows_a_dead_endpoint(monkeypatch) -> None:
+ import urllib.error
+ import urllib.request
+
+ def dead(request: Any, timeout: float = 0.0) -> None:
+ raise urllib.error.URLError("refused")
+
+ monkeypatch.setattr(urllib.request, "urlopen", dead)
+ assert supervisor.warm_brain(launch_command=_COMMAND) is False
+
+
+# ── environment hardening ────────────────────────────────────────────────
+def test_hf_symlink_workaround_is_windows_only(monkeypatch) -> None:
+ """The WinError 1314 workaround costs gigabytes of duplicated cache on
+ macOS/Linux where symlinks simply work."""
+ import os as os_module
+
+ monkeypatch.delenv("HF_HUB_DISABLE_SYMLINKS", raising=False)
+ env = supervisor.hardened_child_env(inject_openai_key=False)
+ if os_module.name == "nt":
+ assert env.get("HF_HUB_DISABLE_SYMLINKS") == "1"
+ else:
+ assert "HF_HUB_DISABLE_SYMLINKS" not in env
+ assert env.get("PYTHONFAULTHANDLER") == "1"
+ assert env.get("PYTHONUNBUFFERED") == "1"
diff --git a/tests/unit/realtime/test_local_realtime.py b/tests/unit/realtime/test_local_realtime.py
index 1e21d167c8..fb514553f5 100644
--- a/tests/unit/realtime/test_local_realtime.py
+++ b/tests/unit/realtime/test_local_realtime.py
@@ -373,9 +373,17 @@ def test_patience_is_earned_by_a_launch_command() -> None:
def _fresh_launch_state(monkeypatch) -> list[dict[str, Any]]:
- """Reset the class-level spawn stamp and capture Popen calls."""
+ """Reset the class-level spawn stamp and capture Popen calls.
+
+ The port probe is pinned closed: a REAL listener on 8765 (a live dev
+ server on this machine) would otherwise turn the spawn into an honest
+ "already-running" and fail the test for the wrong reason.
+ """
import subprocess
+ from jarvis.realtime.local_server import supervisor
+
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)
monkeypatch.setattr(LocalRealtimeProvider, "_last_launch_at", float("-inf"))
spawned: list[dict[str, Any]] = []
@@ -511,3 +519,73 @@ async def test_a_running_orphan_still_connects_despite_a_stale_command(
monkeypatch.setattr(provider, "_open_session_once", healthy)
assert await provider.open_session(SimpleNamespace(model="m")) == "session"
+
+
+# ── Boot-time prewarm (warm_transport capability) ────────────────────────
+def _warm_cfg(base_url: str, launch_command: str) -> SimpleNamespace:
+ provider = SimpleNamespace(
+ base_url=base_url, model="", launch_command=launch_command
+ )
+ return SimpleNamespace(
+ brain=SimpleNamespace(providers={"local-realtime": provider})
+ )
+
+
+async def test_warm_transport_prewarms_via_the_supervisor(
+ monkeypatch, tmp_path
+) -> None:
+ """The shared warm worker calls this after boot: server up + brain model
+ resident BEFORE the first call, which is what makes connects instant."""
+ from jarvis.realtime.local_server import supervisor
+
+ calls: list[str] = []
+ monkeypatch.setattr(
+ supervisor,
+ "ensure_running",
+ lambda **kwargs: calls.append(f"run:{kwargs['reason']}") or "spawned",
+ )
+ monkeypatch.setattr(
+ supervisor, "warm_brain", lambda **kwargs: calls.append("warm") or True
+ )
+ exe = tmp_path / "server"
+ exe.write_bytes(b"")
+ cfg = _warm_cfg("http://localhost:8765", f'"{exe}" --model_name m')
+ assert await LocalRealtimeProvider.warm_transport(cfg) is True
+ assert calls == ["run:prewarm", "warm"]
+
+
+async def test_warm_transport_skips_a_deleted_install(monkeypatch, tmp_path) -> None:
+ """Prewarming a deleted entry point would just burn the rate limit and
+ log noise at every boot."""
+ from jarvis.realtime.local_server import supervisor
+
+ spawned: list[str] = []
+ monkeypatch.setattr(
+ supervisor, "ensure_running", lambda **kwargs: spawned.append("x") or "spawned"
+ )
+ gone = tmp_path / "venv" / "Scripts" / "speech-to-speech.exe"
+ cfg = _warm_cfg("http://localhost:8765", f'"{gone}" --model_name m')
+ assert await LocalRealtimeProvider.warm_transport(cfg) is False
+ assert spawned == []
+
+
+async def test_warm_transport_requires_an_address_and_a_command() -> None:
+ assert await LocalRealtimeProvider.warm_transport(_warm_cfg("", "serve")) is False
+ assert (
+ await LocalRealtimeProvider.warm_transport(
+ _warm_cfg("http://localhost:8765", "")
+ )
+ is False
+ )
+ # A LAN endpoint is never spawned here — wrong host.
+ assert (
+ await LocalRealtimeProvider.warm_transport(
+ _warm_cfg("http://gpu.lan:8443", "serve")
+ )
+ is False
+ )
+
+
+async def test_warm_transport_never_raises(monkeypatch) -> None:
+ """Best-effort by contract: no failure may reach the warm worker."""
+ assert await LocalRealtimeProvider.warm_transport(None) is False
diff --git a/tests/unit/ui/web/test_managed_local_realtime_routes.py b/tests/unit/ui/web/test_managed_local_realtime_routes.py
index f708713a22..756d39a054 100644
--- a/tests/unit/ui/web/test_managed_local_realtime_routes.py
+++ b/tests/unit/ui/web/test_managed_local_realtime_routes.py
@@ -98,15 +98,108 @@ def test_install_accepts_an_empty_body(
assert resp.json()["started"] is True
-def test_status_pairs_progress_with_failclosed_probe(server: WebServer) -> None:
+def test_status_pairs_progress_with_failclosed_probe(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.realtime.local_server import supervisor
+
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)
with TestClient(server.app) as client:
resp = client.get("/api/providers/local-realtime/managed-server/status")
body = resp.json()
- assert set(body) == {"progress", "server"}
+ assert set(body) == {"progress", "server", "runtime"}
# Nothing is installed under the tmp data dir: readiness must be False
# with the exact not-installed sentence, never a guess.
assert body["server"]["ready"] is False
assert body["server"]["sentence"] == "Managed server not installed."
+ # The live half says what the disk cannot: nothing serves, nothing owned.
+ assert body["runtime"] == {
+ "reachable": False,
+ "port": 8765,
+ "pid": None,
+ "owned": False,
+ "stale": False,
+ }
+
+
+def test_start_without_a_launch_command_answers_409(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ resp = client.post("/api/providers/local-realtime/managed-server/start")
+ assert resp.status_code == 409
+ assert "launch command" in resp.json()["detail"]
+
+
+def test_start_forwards_the_supervisor_refusal(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.core.config import BrainProviderConfig
+ from jarvis.realtime.local_server import supervisor
+
+ server.app.state.config.brain.providers["local-realtime"] = BrainProviderConfig(
+ launch_command="serve --flag"
+ )
+ monkeypatch.setattr(
+ supervisor, "ensure_running", lambda **kwargs: "refused:rate-limited"
+ )
+ with TestClient(server.app) as client:
+ resp = client.post("/api/providers/local-realtime/managed-server/start")
+ assert resp.status_code == 409
+ assert resp.json()["detail"] == "refused:rate-limited"
+
+
+def test_start_spawns_and_warms_the_brain(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.core.config import BrainProviderConfig
+ from jarvis.realtime.local_server import supervisor
+
+ server.app.state.config.brain.providers["local-realtime"] = BrainProviderConfig(
+ launch_command="serve --flag"
+ )
+ calls: list[str] = []
+ monkeypatch.setattr(
+ supervisor,
+ "ensure_running",
+ lambda **kwargs: calls.append("start") or "spawned",
+ )
+ monkeypatch.setattr(
+ supervisor, "warm_brain", lambda **kwargs: calls.append("warm") or True
+ )
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: True)
+ with TestClient(server.app) as client:
+ resp = client.post("/api/providers/local-realtime/managed-server/start")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["ok"] is True
+ assert body["outcome"] == "spawned"
+ assert calls == ["start", "warm"]
+ assert body["runtime"]["reachable"] is True
+
+
+def test_stop_answers_409_when_nothing_is_owned(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.realtime.local_server import supervisor
+
+ monkeypatch.setattr(
+ supervisor, "stop", lambda **kwargs: (False, "no owned server process found")
+ )
+ with TestClient(server.app) as client:
+ resp = client.post("/api/providers/local-realtime/managed-server/stop")
+ assert resp.status_code == 409
+
+
+def test_stop_reports_success(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.realtime.local_server import supervisor
+
+ monkeypatch.setattr(supervisor, "stop", lambda **kwargs: (True, "stopped pid 4711"))
+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)
+ with TestClient(server.app) as client:
+ resp = client.post("/api/providers/local-realtime/managed-server/stop")
+ assert resp.status_code == 200
+ assert resp.json()["ok"] is True
def test_uninstall_refuses_while_running(