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(realtime): keep managed local runtime ready
rubenluetke10-beepeb7d54916156
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex 24030d1651..74f8aef546 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1846,6 +1846,22 @@ class LocalRealtimeProvider:"was ready")return False+ install = importlib.import_module(+ "jarvis.realtime.local_server.install"+ )+ if not bool(+ install.repair_smoke_marker_from_live_runtime(+ provider._base_url+ )+ ):+ log.warning(+ "local-realtime: server is ready but its managed-install "+ "smoke proof could not be repaired"+ )+ supervisor.start_runtime_monitor(+ launch_command=provider._launch_command,+ base_url=provider._base_url,+ )# Only the pinned managed stack promises /v1/pool. A BYO# OpenAI-compatible server remains valid without that private# endpoint. For managed launches, the wait above also ensuresdiff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.pyindex ed07d66522..13b216e24d 100644--- a/jarvis/realtime/local_server/install.py+++ b/jarvis/realtime/local_server/install.py@@ -27,6 +27,7 @@ import timefrom collections import dequefrom dataclasses import dataclass, fieldfrom pathlib import Path+from typing import Anyfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSfrom jarvis.realtime.local_server.brain_link import BrainResolution@@ -115,13 +116,18 @@ def _smoke_marker() -> Path:return install_root() / "smoke_ok.json"-def _smoke_marker_valid() -> bool:- """Validate the durable proof for this exact pinned server build."""+def _read_smoke_marker_payload() -> dict[str, object] | None:try:payload = json.loads(_smoke_marker().read_text(encoding="utf-8"))except (OSError, ValueError):- return False- if not isinstance(payload, dict):+ return None+ return payload if isinstance(payload, dict) else None+++def _smoke_marker_valid() -> bool:+ """Validate the durable proof for this exact pinned server build."""+ payload = _read_smoke_marker_payload()+ if payload is None:return Falseat = payload.get("at")valid_at = (@@ -151,6 +157,65 @@ def _write_smoke_marker(payload: dict[str, object]) -> None:raise OSError("could not atomically write the managed-server smoke marker")+def repair_smoke_marker_from_live_runtime(base_url: str) -> bool:+ """Recover missing or legacy proof from a verified live managed runtime.++ A ready pool owned by this exact patched install is stronger smoke evidence+ than a marker written by an older Jarvis version. Foreign listeners,+ partial installs, failed preflight, and drifted patches remain fail-closed.+ """+ if _smoke_marker_valid():+ return True+ from jarvis.realtime.local_server import supervisor++ # Marker publication must be serialized with install/uninstall. Otherwise+ # a warm worker could restore a valid marker after a failed reinstall had+ # deliberately invalidated it, falsely advertising a half-mutated venv.+ with supervisor.lifecycle_guard() as guarded:+ if not guarded:+ return False+ return _repair_smoke_marker_from_live_runtime_unlocked(base_url)+++def _repair_smoke_marker_from_live_runtime_unlocked(base_url: str) -> bool:+ """Repair proof while the caller owns the server lifecycle lease."""+ if _smoke_marker_valid():+ return True+ if (+ not _venv_python().exists()+ or not _server_entrypoint().exists()+ or patch_state(_site_packages()) != "patched"+ ):+ return False+ try:+ from jarvis.realtime.local_server import supervisor++ runtime = supervisor.status(base_url)+ if not bool(runtime.get("ready")) or not bool(runtime.get("owned")):+ return False+ report = run_preflight(install_root())+ if not report.ok or report.tier is None or report.brain is None:+ return False+ if report.brain.kind not in {"ollama", "cloud-openai"}:+ return False+ _write_smoke_marker(+ {+ "schema": _SMOKE_MARKER_SCHEMA,+ "patch_version": PATCH_TARGET_VERSION,+ "at": time.time(),+ "tier": report.tier.key,+ "brain": report.brain.kind,+ "preflight": report_payload(report),+ "repair_source": "owned-live-runtime",+ }+ )+ except Exception: # noqa: BLE001 - readiness repair is advisory, never fatal+ log.warning("local-realtime: live smoke-proof repair failed", exc_info=True)+ return False+ log.info("local-realtime: repaired smoke proof from the owned live runtime")+ return True++@dataclassclass _State:phase: str = "idle"@@ -329,7 +394,7 @@ def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:"""env = dict(os.environ)env.setdefault("PYTHONIOENCODING", "utf-8")- popen_kwargs: dict[str, object] = {}+ popen_kwargs: dict[str, Any] = {}if os.name != "nt":# The timeout path kills this process group. Without a fresh session,# pip's build-backend children can outlive the launcher and continue@@ -345,7 +410,7 @@ def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:cwd=str(cwd) if cwd else None,env=env,creationflags=NO_WINDOW_CREATIONFLAGS,- **popen_kwargs, # type: ignore[arg-type]+ **popen_kwargs,)def _pump() -> None:@@ -396,14 +461,14 @@ def _kill_tree(proc: subprocess.Popen) -> bool:import signaltry:- os.killpg(proc.pid, signal.SIGTERM)+ os.killpg(proc.pid, signal.SIGTERM) # type: ignore[attr-defined]except (ProcessLookupError, PermissionError, OSError):proc.terminate()try:proc.wait(timeout=10)except subprocess.TimeoutExpired:try:- os.killpg(proc.pid, signal.SIGKILL)+ os.killpg(proc.pid, signal.SIGKILL) # type: ignore[attr-defined]except (ProcessLookupError, PermissionError, OSError):proc.kill()proc.wait(timeout=10)@@ -454,7 +519,7 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None: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)- popen_kwargs: dict[str, object] = {}+ popen_kwargs: dict[str, Any] = {}if os.name != "nt":# Its own process group so _kill_tree's killpg reaches every worker.popen_kwargs["start_new_session"] = True@@ -466,7 +531,7 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:stderr=sink,env=env,creationflags=NO_WINDOW_CREATIONFLAGS,- **popen_kwargs, # type: ignore[arg-type]+ **popen_kwargs,)try:deadline = time.monotonic() + _SMOKE_TIMEOUT_S@@ -618,6 +683,23 @@ def _setup_local_brain() -> None:def _run_install_guarded(confirmed_brain: str = "") -> None:try:+ # Marker-schema upgrades are metadata debt, not grounds to tear down a+ # healthy multi-gigabyte runtime. Only this exact patched install's+ # owned, fully-ready pool may take the non-destructive repair path.+ if not _smoke_marker_valid() and _repair_smoke_marker_from_live_runtime_unlocked(+ f"http://127.0.0.1:{SERVE_PORT}"+ ):+ marker = _read_smoke_marker_payload() or {}+ repaired_brain = str(marker.get("brain") or "")+ if not confirmed_brain or repaired_brain == confirmed_brain:+ with _LOCK:+ _STATE.phase = "done"+ _STATE.percent = 100+ _STATE.detail = "installed; smoke proof repaired from the live server"+ _STATE.error = ""+ _STATE.finished_at = time.time()+ log.info("local-realtime: install proof repaired without server teardown")+ return_set("preflight", 2, "checking hardware, disk, and brain")report: PreflightReport = run_preflight(install_root())if (diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.pyindex 1f6ea54413..4c61f926c9 100644--- a/jarvis/realtime/local_server/supervisor.py+++ b/jarvis/realtime/local_server/supervisor.py@@ -39,7 +39,7 @@ import uuidfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom pathlib import Path-from typing import BinaryIO+from typing import Any, BinaryIOfrom urllib.parse import SplitResult, urlsplit, urlunsplitlog = logging.getLogger(__name__)@@ -55,6 +55,14 @@ RUNTIME_READY_TIMEOUT_S = 120.0RUNTIME_READY_POLL_S = 0.5OWNED_STARTUP_TIMEOUT_S = RUNTIME_READY_TIMEOUT_S+# The managed process is meant to be warm before a user calls. Poll its+# ownership cheaply once a second so an idle native crash starts recovering+# immediately; probe the full model pool less often to catch a live-but-wedged+# child without filling the server log with health requests.+RUNTIME_MONITOR_POLL_S = 1.0+RUNTIME_MONITOR_POOL_INTERVAL_S = 30.0+RUNTIME_MONITOR_UNREADY_GRACE_S = 30.0+_MAX_POOL_RESPONSE_BYTES = 64 * 1024#: How long the Ollama brain model stays resident after a warm ping. Slides on@@ -64,8 +72,18 @@ BRAIN_KEEP_ALIVE = "2h"_DEFAULT_PORT = 8765+_WINDOWS_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)+_WINDOWS_DETACHED_PROCESS = getattr(subprocess, "DETACHED_PROCESS", 0x00000008)+_WINDOWS_BREAKAWAY_FROM_JOB = getattr(+ subprocess, "CREATE_BREAKAWAY_FROM_JOB", 0x01000000+)+_LOCK = threading.Lock()_last_spawn_at: float = float("-inf")+_MONITOR_LOCK = threading.Lock()+_monitor_thread: threading.Thread | None = None+_monitor_stop: threading.Event | None = None+_monitor_key: tuple[str, str] | None = None# ── Paths ────────────────────────────────────────────────────────────────@@ -697,7 +715,11 @@ def ensure_running(*, launch_command: str, base_url: str, reason: str) -> str:owned_root = (managed_install_root(owned_command) if owned_command is not None else None)- if owned_root is not None and not _uses_loopback_bind(owned_command):+ if (+ owned_root is not None+ and owned_command is not None+ and not _uses_loopback_bind(owned_command)+ ):# Managed servers survive app exits, so an upgrade can inherit# a healthy but LAN-bound legacy generation. Only a verified# owned process is eligible for this one-time migration.@@ -774,9 +796,22 @@ def ensure_running(*, launch_command: str, base_url: str, reason: str) -> str:return "spawned"+def _server_creationflags(*, platform_name: str | None = None) -> int:+ """Windowless flags that let the managed server survive an app restart."""+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # lazy++ platform = os.name if platform_name is None else platform_name+ if platform != "nt":+ return NO_WINDOW_CREATIONFLAGS+ return (+ _WINDOWS_NO_WINDOW+ | _WINDOWS_DETACHED_PROCESS+ | _WINDOWS_BREAKAWAY_FROM_JOB+ )++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 # lazytry:_server_log().parent.mkdir(parents=True, exist_ok=True)@@ -800,15 +835,36 @@ def _spawn(command: str, *, reason: str) -> int | None:# 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),+ creationflags = _server_creationflags()+ common_kwargs: dict[str, Any] = {+ "stdin": subprocess.DEVNULL,+ "stdout": sink or subprocess.DEVNULL,+ "stderr": subprocess.STDOUT,+ "env": hardened_child_env(inject_openai_key=True),**popen_kwargs,- )+ }+ try:+ proc = subprocess.Popen( # noqa: S603+ argv,+ creationflags=creationflags,+ **common_kwargs,+ )+ except PermissionError as exc:+ if not creationflags & _WINDOWS_BREAKAWAY_FROM_JOB:+ raise+ # Some Windows hosts forbid explicit job breakaway. Keep the+ # server usable, but report the degraded survive-parent guarantee.+ fallback_flags = creationflags & ~_WINDOWS_BREAKAWAY_FROM_JOB+ log.warning(+ "supervisor: server breakaway was denied (%s); retrying without "+ "CREATE_BREAKAWAY_FROM_JOB",+ exc,+ )+ proc = subprocess.Popen( # noqa: S603+ argv,+ creationflags=fallback_flags,+ **common_kwargs,+ )except Exception as exc: # noqa: BLE001 — a bad command must not kill the callerlog.warning("supervisor: spawning the server failed (%s: %s) — check "@@ -824,6 +880,197 @@ def _spawn(command: str, *, reason: str) -> int | None:return proc.pid+def start_runtime_monitor(*, launch_command: str, base_url: str) -> bool:+ """Keep one verified managed runtime warm for this Jarvis process.++ The server still survives app exit. This lightweight daemon only closes+ the gap while Jarvis is running: an idle native crash is otherwise noticed+ only when the next user starts a call and pays the whole model cold boot.+ Returns ``True`` when a new monitor was armed and ``False`` when the same+ generation is already covered or cannot be owned safely.+ """+ command = (launch_command or "").strip()+ host, _port = _host_port(base_url)+ if managed_install_root(command) is None or not _is_loopback(host):+ return False+ try:+ from jarvis.realtime.local_server import install++ if not bool(install.server_status().get("ready")):+ return False+ except Exception: # noqa: BLE001 - no proof means no autonomous monitor+ log.warning("supervisor: runtime monitor could not verify the install", exc_info=True)+ return False+ _pid, alive = _owned_process()+ if not alive:+ return False+ key = (command, _pool_url(base_url))++ global _monitor_thread, _monitor_stop, _monitor_key+ with _MONITOR_LOCK:+ if (+ _monitor_thread is not None+ and _monitor_thread.is_alive()+ and _monitor_key == key+ ):+ return False+ if _monitor_stop is not None:+ _monitor_stop.set()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=_runtime_monitor,+ args=(command, base_url, stop_event, key),+ name="local-realtime-monitor",+ daemon=True,+ )+ _monitor_stop = stop_event+ _monitor_thread = thread+ _monitor_key = key+ thread.start()+ log.info("local-realtime supervisor: continuous runtime monitor armed")+ return True+++def _revive_from_monitor(+ *,+ launch_command: str,+ base_url: str,+ reason: str,+ cancel_event: threading.Event,+) -> str:+ """Run one generation-bound revive and return its explicit outcome."""+ try:+ from jarvis.realtime.local_server import install++ if not bool(install.server_status().get("ready")):+ return "refused:install-unproven"+ except Exception: # noqa: BLE001 - fail closed before an autonomous spawn+ log.warning("supervisor: monitor revive could not verify the install", exc_info=True)+ return "refused:install-unproven"+ outcome = ensure_running(+ launch_command=launch_command,+ base_url=base_url,+ reason=reason,+ )+ if outcome != "spawned":+ return outcome+ ready = wait_until_ready(+ base_url,+ timeout=RUNTIME_READY_TIMEOUT_S,+ launch_command=launch_command,+ cleanup_on_timeout=True,+ cancel_event=cancel_event,+ )+ if not ready:+ return "cancelled" if cancel_event.is_set() else "readiness-timeout"+ try:+ install.repair_smoke_marker_from_live_runtime(base_url)+ except Exception: # noqa: BLE001 - runtime recovery remains usable+ log.warning("supervisor: smoke-proof repair after revive failed", exc_info=True)+ warm_brain(launch_command=launch_command)+ return "ready"+++def _runtime_monitor(+ launch_command: str,+ base_url: str,+ stop_event: threading.Event,+ key: tuple[str, str],+) -> None:+ """Detect an idle process exit promptly and a wedged pool conservatively."""+ next_pool_probe = time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S+ unready_since: float | None = None+ last_outcome = ""+ try:+ while not stop_event.wait(RUNTIME_MONITOR_POLL_S):+ try:+ if managed_install_root(launch_command) is None:+ return+ _pid, alive = _owned_process()+ if not alive:+ # A healthy listener without our ownership is foreign. Do+ # not fight it or keep trying to adopt it.+ if probe_runtime(base_url, timeout=0.25) is not None:+ log.warning(+ "local-realtime monitor stopped: ready listener is no "+ "longer owned by this install"+ )+ return+ outcome = _revive_from_monitor(+ launch_command=launch_command,+ base_url=base_url,+ reason="watchdog-exit",+ cancel_event=stop_event,+ )+ if outcome == "ready":+ log.info("local-realtime monitor: crashed runtime recovered")+ unready_since = None+ next_pool_probe = (+ time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S+ )+ elif outcome != last_outcome:+ log.warning(+ "local-realtime monitor: crash recovery deferred (%s)",+ outcome,+ )+ last_outcome = outcome+ continue++ now = time.monotonic()+ if now < next_pool_probe:+ continue+ next_pool_probe = now + RUNTIME_MONITOR_POOL_INTERVAL_S+ if probe_runtime(base_url, timeout=0.75) is not None:+ unready_since = None+ last_outcome = ""+ continue+ if unready_since is None:+ unready_since = now+ log.warning(+ "local-realtime monitor: owned process stopped reporting "+ "a ready model pool; waiting for a second failed probe"+ )+ continue+ if now - unready_since < RUNTIME_MONITOR_UNREADY_GRACE_S:+ continue+ outcome = _revive_from_monitor(+ launch_command=launch_command,+ base_url=base_url,+ reason="watchdog-unready",+ cancel_event=stop_event,+ )+ if outcome == "ready":+ log.info("local-realtime monitor: wedged runtime recovered")+ unready_since = None+ next_pool_probe = (+ time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S+ )+ elif outcome != last_outcome:+ log.warning(+ "local-realtime monitor: unready recovery deferred (%s)",+ outcome,+ )+ last_outcome = outcome+ except Exception: # noqa: BLE001 - a monitor must survive one bad probe+ log.warning("local-realtime monitor iteration failed", exc_info=True)+ finally:+ global _monitor_thread, _monitor_stop, _monitor_key+ with _MONITOR_LOCK:+ if _monitor_stop is stop_event:+ _monitor_thread = None+ _monitor_stop = None+ _monitor_key = None+++def _request_runtime_monitor_stop() -> bool:+ """Disarm autonomous recovery before a deliberate lifecycle stop."""+ with _MONITOR_LOCK:+ if _monitor_stop is None:+ return False+ _monitor_stop.set()+ return True++# ── Stop ─────────────────────────────────────────────────────────────────@@ -832,6 +1079,7 @@ def stop(*, owned_only: bool = True, install_root: Path | None = None) -> tuple[with lifecycle_guard() as guarded:if not guarded:return False, "server lifecycle operation already in progress"+ _request_runtime_monitor_stop()return _stop_owned_unlocked(owned_only=owned_only, install_root=install_root)@@ -932,7 +1180,7 @@ def _kill_pid_tree(pid: int) -> bool:# 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)+ os.killpg(pid, signal.SIGTERM) # type: ignore[attr-defined]except ProcessLookupError:return Trueexcept (PermissionError, OSError):@@ -943,11 +1191,11 @@ def _kill_pid_tree(pid: int) -> bool:return Truetime.sleep(0.2)try:- os.killpg(pid, signal.SIGKILL)+ os.killpg(pid, signal.SIGKILL) # type: ignore[attr-defined]except ProcessLookupError:return Trueexcept (PermissionError, OSError):- os.kill(pid, signal.SIGKILL)+ os.kill(pid, signal.SIGKILL) # type: ignore[attr-defined]return Trueexcept Exception: # noqa: BLE001 — best-effort teardown, reported honestlylog.warning("supervisor: kill of pid %s incomplete", pid, exc_info=True)@@ -957,6 +1205,41 @@ def _kill_pid_tree(pid: int) -> bool:def _pid_exists(pid: int) -> bool:if pid <= 0:return False+ if os.name == "nt":+ # ``os.kill(pid, 0)`` only proves that Windows can still open the+ # process object. A terminated object remains open while another+ # handle references it, which made a successful taskkill look alive+ # and aborted repair installs. A signalled handle is the real test.+ try:+ import ctypes+ from ctypes import wintypes++ synchronize = 0x00100000+ wait_timeout = 0x00000102+ wait_failed = 0xFFFFFFFF+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.OpenProcess.argtypes = [+ wintypes.DWORD,+ wintypes.BOOL,+ wintypes.DWORD,+ ]+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]+ kernel32.WaitForSingleObject.restype = wintypes.DWORD+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ handle = kernel32.OpenProcess(synchronize, False, pid)+ if not handle:+ # Access denied proves an object exists but not that it is safe+ # to call dead. Every other error is the normal gone-PID case.+ return ctypes.get_last_error() == 5+ try:+ result = int(kernel32.WaitForSingleObject(handle, 0))+ finally:+ kernel32.CloseHandle(handle)+ return result in {wait_timeout, wait_failed}+ except Exception: # noqa: BLE001 - unknown must fail safe as possibly alive+ log.debug("supervisor: Windows pid-state probe failed", exc_info=True)+ return Truetry:os.kill(pid, 0)except ProcessLookupError:@@ -1124,6 +1407,12 @@ def _brain_endpoint(launch_command: str) -> tuple[str, str]:def _reset_for_tests() -> None:- """Reset module-level state (rate limit) between tests."""- global _last_spawn_at+ """Reset module-level rate-limit and monitor state between tests."""+ global _last_spawn_at, _monitor_thread, _monitor_stop, _monitor_key_last_spawn_at = float("-inf")+ with _MONITOR_LOCK:+ if _monitor_stop is not None:+ _monitor_stop.set()+ _monitor_thread = None+ _monitor_stop = None+ _monitor_key = Nonediff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 9657bd5df1..304f83a65d 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -2735,8 +2735,8 @@ async def _finish_managed_server_warm(command: str,cancel_event: threading.Event,) -> None:- """Wait off-request for managed readiness, then warm its brain."""- from jarvis.realtime.local_server import supervisor+ """Wait off-request for readiness, prove it, monitor it, then warm its brain."""+ from jarvis.realtime.local_server import install, supervisortry:managed = await asyncio.to_thread(@@ -2755,9 +2755,26 @@ async def _finish_managed_server_warm())if ready and not cancel_event.is_set():- await asyncio.to_thread(- lambda: supervisor.warm_brain(launch_command=command)- )+ def _finish_ready_runtime() -> None:+ if cancel_event.is_set():+ return+ proven = install.repair_smoke_marker_from_live_runtime(base_url)+ if cancel_event.is_set():+ return+ if proven:+ supervisor.start_runtime_monitor(+ launch_command=command,+ base_url=base_url,+ )+ else:+ log.warning(+ "managed local-realtime server is ready but its install "+ "proof could not be repaired"+ )+ if not cancel_event.is_set():+ supervisor.warm_brain(launch_command=command)++ await asyncio.to_thread(_finish_ready_runtime)except asyncio.CancelledError:cancel_event.set()raisediff --git a/tests/unit/realtime/local_server/test_engine.py b/tests/unit/realtime/local_server/test_engine.pyindex 821ebbe5dc..745e8130e0 100644--- a/tests/unit/realtime/local_server/test_engine.py+++ b/tests/unit/realtime/local_server/test_engine.py@@ -1,5 +1,6 @@"""Install engine, tier ladder, preflight, and brain resolution contracts."""+import jsonfrom pathlib import Pathimport pytest@@ -238,6 +239,99 @@ class TestServerStatusFailClosed:)assert install._smoke_marker_valid() is False+ def test_owned_live_runtime_repairs_a_missing_smoke_marker(+ self, monkeypatch, tmp_path: Path+ ) -> None:+ """A schema upgrade must not demand a destructive multi-GB reinstall.++ A ready server owned by this exact patched install is stronger smoke+ evidence than the marker that an older Jarvis version wrote.+ """+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ install._venv_python().parent.mkdir(parents=True)+ install._venv_python().write_bytes(b"")+ install._server_entrypoint().write_bytes(b"")+ monkeypatch.setattr(install, "patch_state", lambda path: "patched")+ monkeypatch.setattr(+ supervisor,+ "status",+ lambda base_url: {"ready": True, "owned": True},+ )+ report = preflight.PreflightReport(+ ok=True,+ usable_gb=16.0,+ memory_source="nvidia-smi",+ disk_free_gb=100.0,+ tier=tiers.TIERS[1],+ stack_sentence="x",+ brain=brain_link.BrainResolution(kind="ollama", model="qwen2.5:7b"),+ )+ monkeypatch.setattr(install, "run_preflight", lambda root: report)++ assert install.repair_smoke_marker_from_live_runtime(+ "http://127.0.0.1:8765"+ )++ payload = json.loads(install._smoke_marker().read_text(encoding="utf-8"))+ assert payload["schema"] == install._SMOKE_MARKER_SCHEMA+ assert payload["patch_version"] == install.PATCH_TARGET_VERSION+ assert payload["repair_source"] == "owned-live-runtime"+ assert install._smoke_marker_valid()++ def test_foreign_runtime_cannot_repair_the_smoke_marker(+ self, monkeypatch, tmp_path: Path+ ) -> None:+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ install._venv_python().parent.mkdir(parents=True)+ install._venv_python().write_bytes(b"")+ install._server_entrypoint().write_bytes(b"")+ monkeypatch.setattr(install, "patch_state", lambda path: "patched")+ monkeypatch.setattr(+ supervisor,+ "status",+ lambda base_url: {"ready": True, "owned": False},+ )++ assert not install.repair_smoke_marker_from_live_runtime(+ "http://127.0.0.1:8765"+ )+ assert not install._smoke_marker().exists()++ def test_smoke_marker_repair_refuses_during_another_lifecycle_operation(+ self, monkeypatch, tmp_path: Path+ ) -> None:+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))++ class _BusyLifecycle:+ def __enter__(self) -> bool:+ return False++ def __exit__(self, *args: object) -> None:+ return None++ monkeypatch.setattr(+ supervisor,+ "lifecycle_guard",+ lambda: _BusyLifecycle(),+ )+ monkeypatch.setattr(+ install,+ "_repair_smoke_marker_from_live_runtime_unlocked",+ lambda base_url: (_ for _ in ()).throw(+ AssertionError("repair must not race an install")+ ),+ )++ assert not install.repair_smoke_marker_from_live_runtime(+ "http://127.0.0.1:8765"+ )+def test_stale_config_earns_the_repair_sentence(self, monkeypatch, tmp_path: Path) -> None:@@ -366,6 +460,37 @@ class TestReviewFixes:assert not install._smoke_marker().exists()assert install.snapshot()["phase"] == "error"+ def test_install_repairs_live_proof_without_stopping_the_server(+ self, monkeypatch, tmp_path+ ) -> None:+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ monkeypatch.setattr(install, "_smoke_marker_valid", lambda: False)+ monkeypatch.setattr(+ install,+ "_repair_smoke_marker_from_live_runtime_unlocked",+ lambda base_url: True,+ )+ monkeypatch.setattr(+ install,+ "_read_smoke_marker_payload",+ lambda: {"brain": "ollama"},+ )++ def forbidden(*args, **kwargs):+ raise AssertionError("a healthy server must not be stopped for marker repair")++ monkeypatch.setattr(install, "run_preflight", forbidden)+ monkeypatch.setattr(supervisor, "_stop_owned_unlocked", forbidden)++ install._run_install_guarded("ollama")++ state = install.snapshot()+ assert state["phase"] == "done"+ assert state["percent"] == 100+ assert "proof repaired" in str(state["detail"])+def test_smoke_boot_always_tears_down_its_child(self, monkeypatch, tmp_path) -> None:monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))install.install_root().mkdir(parents=True)diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.pyindex 0a26a5ce35..ba2daa4b34 100644--- a/tests/unit/realtime/local_server/test_supervisor.py+++ b/tests/unit/realtime/local_server/test_supervisor.py@@ -14,11 +14,15 @@ import jsonimport osimport subprocessimport sys+import threadingimport timefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any+import pytest++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSfrom jarvis.realtime.local_server import supervisor@@ -437,7 +441,12 @@ def test_spawn_is_windowless_and_records_ownership(monkeypatch, tmp_path) -> Nonlaunch_command="serve --flag", base_url="http://localhost:8765", reason="test")assert outcome == "spawned"- assert spawned[0]["creationflags"] == NO_WINDOW_CREATIONFLAGS # AP-1+ creationflags = int(spawned[0]["creationflags"])+ if os.name == "nt":+ assert creationflags & NO_WINDOW_CREATIONFLAGS # AP-1+ assert creationflags & supervisor._WINDOWS_BREAKAWAY_FROM_JOB+ else:+ assert creationflags == 0record = json.loads((tmp_path / "local_realtime_server.pid.json").read_text(encoding="utf-8"))@@ -670,6 +679,167 @@ def test_windows_taskkill_success_code_is_not_enough_if_pid_survives(monkeypatchassert supervisor._kill_pid_tree(4711) is False[email protected](os.name != "nt", reason="Windows process-object semantics")+def test_windows_pid_probe_rejects_an_exited_but_still_referenced_process() -> None:+ """A signalled process object is dead even while Python retains its handle."""+ proc = subprocess.Popen(+ [sys.executable, "-c", "pass"],+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ proc.wait(timeout=10)++ assert supervisor._pid_exists(proc.pid) is False+++def test_managed_server_windows_flags_detach_and_break_away() -> None:+ flags = supervisor._server_creationflags(platform_name="nt")++ assert flags & supervisor._WINDOWS_NO_WINDOW+ assert flags & supervisor._WINDOWS_DETACHED_PROCESS+ assert flags & supervisor._WINDOWS_BREAKAWAY_FROM_JOB+++def test_spawn_retries_without_breakaway_when_the_host_job_forbids_it(+ monkeypatch, tmp_path+) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ attempts: list[int] = []++ class _Process:+ pid = 4711++ def popen(*args, **kwargs):+ attempts.append(int(kwargs["creationflags"]))+ if len(attempts) == 1:+ raise PermissionError("breakaway denied")+ return _Process()++ flags = NO_WINDOW_CREATIONFLAGS | supervisor._WINDOWS_BREAKAWAY_FROM_JOB+ monkeypatch.setattr(supervisor, "_server_creationflags", lambda: flags)+ monkeypatch.setattr(supervisor.subprocess, "Popen", popen)++ assert supervisor._spawn("server --mode realtime", reason="test") == 4711+ assert attempts == [flags, flags & ~supervisor._WINDOWS_BREAKAWAY_FROM_JOB]+++def test_runtime_monitor_restarts_and_rewarms_a_dead_owned_server(+ monkeypatch, tmp_path+) -> None:+ from jarvis.realtime.local_server import install++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ calls: list[str] = []+ monkeypatch.setattr(install, "server_status", lambda: {"ready": True})+ monkeypatch.setattr(+ supervisor,+ "ensure_running",+ lambda **kwargs: calls.append(f"ensure:{kwargs['reason']}") or "spawned",+ )+ monkeypatch.setattr(+ supervisor,+ "wait_until_ready",+ lambda *args, **kwargs: calls.append("ready") or True,+ )+ monkeypatch.setattr(+ install,+ "repair_smoke_marker_from_live_runtime",+ lambda base_url: calls.append("marker") or True,+ )+ monkeypatch.setattr(+ supervisor,+ "warm_brain",+ lambda **kwargs: calls.append("brain") or True,+ )++ outcome = supervisor._revive_from_monitor(+ launch_command="serve --model_name m",+ base_url="http://127.0.0.1:8765",+ reason="watchdog-exit",+ cancel_event=threading.Event(),+ )++ assert outcome == "ready"+ assert calls == ["ensure:watchdog-exit", "ready", "marker", "brain"]+++def test_runtime_monitor_is_singleton_for_one_managed_generation(+ monkeypatch, tmp_path+) -> None:+ from jarvis.realtime.local_server import install++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ root = tmp_path / "local_realtime"+ root.mkdir()+ command = f'"{root / "server.exe"}" --mode realtime'+ monkeypatch.setattr(install, "server_status", lambda: {"ready": True})+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))+ started: list[tuple[object, tuple[object, ...]]] = []++ class _Thread:+ def __init__(self, *, target, args, **kwargs):+ del kwargs+ self._target = target+ self._args = args+ self._alive = False++ def start(self) -> None:+ self._alive = True+ started.append((self._target, self._args))++ def is_alive(self) -> bool:+ return self._alive++ monkeypatch.setattr(supervisor.threading, "Thread", _Thread)++ assert supervisor.start_runtime_monitor(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ )+ assert not supervisor.start_runtime_monitor(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ )+ assert len(started) == 1+++def test_runtime_monitor_never_revives_an_unproven_failed_install(monkeypatch) -> None:+ from jarvis.realtime.local_server import install++ monkeypatch.setattr(install, "server_status", lambda: {"ready": False})++ def forbidden(**kwargs):+ raise AssertionError("an invalidated install must not be spawned")++ monkeypatch.setattr(supervisor, "ensure_running", forbidden)++ assert (+ supervisor._revive_from_monitor(+ launch_command="serve --model_name m",+ base_url="http://127.0.0.1:8765",+ reason="watchdog-exit",+ cancel_event=threading.Event(),+ )+ == "refused:install-unproven"+ )+++def test_deliberate_stop_disarms_the_runtime_monitor(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ supervisor._reset_for_tests()+ monitor_stop = threading.Event()+ monkeypatch.setattr(supervisor, "_monitor_stop", monitor_stop)+ monkeypatch.setattr(+ supervisor,+ "_stop_owned_unlocked",+ lambda **kwargs: (True, "stopped pid 4711"),+ )++ changed, _message = supervisor.stop(owned_only=True)++ assert changed is True+ assert monitor_stop.is_set()++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))diff --git a/tests/unit/realtime/test_local_realtime.py b/tests/unit/realtime/test_local_realtime.pyindex c2f69378b1..1aace74bfc 100644--- a/tests/unit/realtime/test_local_realtime.py+++ b/tests/unit/realtime/test_local_realtime.py@@ -434,7 +434,11 @@ def test_revive_spawns_windowless_and_rate_limited(monkeypatch, tmp_path) -> Non# Immediately again: rate-limited, a crash-looping server is not hammered.assert provider._maybe_launch_server() is Falseassert len(spawned) == 1- assert spawned[0]["creationflags"] == NO_WINDOW_CREATIONFLAGS # AP-1+ creationflags = int(spawned[0]["creationflags"])+ if NO_WINDOW_CREATIONFLAGS:+ assert creationflags & NO_WINDOW_CREATIONFLAGS # AP-1+ else:+ assert creationflags == 0def test_transient_lifecycle_refusal_is_immediately_retryable(monkeypatch) -> None:@@ -644,7 +648,7 @@ async def test_warm_transport_prewarms_via_the_supervisor() -> None:"""The shared warm worker calls this after boot: server up + brain modelresident BEFORE the first call, which is what makes connects instant."""- from jarvis.realtime.local_server import supervisor+ from jarvis.realtime.local_server import install, supervisorcalls: list[str] = []monkeypatch.setattr(@@ -661,11 +665,21 @@ async def test_warm_transport_prewarms_via_the_supervisor(monkeypatch.setattr(supervisor, "warm_brain", lambda **kwargs: calls.append("warm") or True)+ monkeypatch.setattr(+ install,+ "repair_smoke_marker_from_live_runtime",+ lambda base_url: calls.append("marker") or True,+ )+ monkeypatch.setattr(+ supervisor,+ "start_runtime_monitor",+ lambda **kwargs: calls.append("monitor") 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", "ready", "warm"]+ assert calls == ["run:prewarm", "ready", "marker", "monitor", "warm"]async def test_warm_transport_never_warms_the_brain_before_speech_is_ready(diff --git a/tests/unit/ui/web/test_managed_local_realtime_routes.py b/tests/unit/ui/web/test_managed_local_realtime_routes.pyindex c72d5ba994..2d4f1a7859 100644--- a/tests/unit/ui/web/test_managed_local_realtime_routes.py+++ b/tests/unit/ui/web/test_managed_local_realtime_routes.py@@ -233,6 +233,16 @@ async def test_background_warm_waits_for_managed_pool_before_brain(return Truemonkeypatch.setattr(supervisor, "wait_until_ready", ready)+ monkeypatch.setattr(+ install,+ "repair_smoke_marker_from_live_runtime",+ lambda base_url: calls.append(("marker", base_url)) or True,+ )+ monkeypatch.setattr(+ supervisor,+ "start_runtime_monitor",+ lambda **kwargs: calls.append(("monitor", kwargs)) or True,+ )monkeypatch.setattr(supervisor,"warm_brain",@@ -245,7 +255,12 @@ async def test_background_warm_waits_for_managed_pool_before_brain(threading.Event(),)- assert [name for name, _payload in calls] == ["ready", "brain"]+ assert [name for name, _payload in calls] == [+ "ready",+ "marker",+ "monitor",+ "brain",+ ]ready_kwargs = calls[0][1]assert isinstance(ready_kwargs, dict)assert ready_kwargs["cleanup_on_timeout"] is True