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): harden managed server lifecycle
rubenluetke10-beep66b81c6ee5c5
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex e5554d5377..80ce993b5e 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1504,6 +1504,26 @@ class LocalRealtimeProvider:"""if self._model:return self._model+ if self._launch_command:+ import importlib # lazy (AP-26)++ try:+ supervisor = importlib.import_module(+ "jarvis.realtime.local_server.supervisor"+ )+ if supervisor.is_managed_launch_command(self._launch_command):+ # The pinned speech-to-speech server implements the+ # realtime protocol and /v1/pool, but not /v1/models.+ # Probing a known-unsupported route delayed every cold+ # connect and turned an expected 404 into misleading log+ # noise.+ LocalRealtimeProvider._model_cache[self._base_url] = (+ _MODEL,+ time.monotonic() + LocalRealtimeProvider._MODEL_CACHE_TTL_S,+ )+ return _MODEL+ except Exception: # noqa: BLE001 - generic BYO discovery remains available+ log.debug("local-realtime: managed-command detection failed", exc_info=True)cached = LocalRealtimeProvider._model_cache.get(self._base_url)if cached is not None and cached[1] > time.monotonic():return cached[0]@@ -1588,16 +1608,15 @@ class LocalRealtimeProvider:2026-08-06 19:57: its log ends mid-request, the call died with it,and nothing owned bringing it back). The actual spawn lives in thesupervisor 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).+ so the two can never double-spawn. This cheap provider gate advances+ only after a real spawn; transient lifecycle contention must remain+ immediately retryable. The supervisor owns the durable rate limit."""if not self._launch_command or not self._server_is_local_process():return Falsenow = time.monotonic()if now - LocalRealtimeProvider._last_launch_at < _LOCAL_LAUNCH_MIN_INTERVAL_S:return False- LocalRealtimeProvider._last_launch_at = nowimport importlib # lazy (AP-26)# importlib, not a literal ``from jarvis...``: the plugin-module@@ -1622,6 +1641,7 @@ class LocalRealtimeProvider:)return Falseif outcome == "spawned":+ LocalRealtimeProvider._last_launch_at = nowlog.info("local-realtime: server unreachable — launched the configured ""server command; waiting for it to come up"@@ -1661,6 +1681,9 @@ class LocalRealtimeProvider:supervisor = importlib.import_module("jarvis.realtime.local_server.supervisor")+ managed = bool(+ supervisor.is_managed_launch_command(provider._launch_command)+ )outcome = str(supervisor.ensure_running(launch_command=provider._launch_command,@@ -1668,8 +1691,29 @@ class LocalRealtimeProvider:reason="prewarm",))+ if outcome not in ("spawned", "already-running"):+ return False+ if managed:+ ready = bool(+ supervisor.wait_until_ready(+ provider._base_url,+ timeout=provider._connect_retry_window_s(),+ launch_command=provider._launch_command,+ cleanup_on_timeout=True,+ )+ )+ if not ready:+ log.warning(+ "local-realtime: prewarm timed out before the model pool "+ "was ready"+ )+ return False+ # 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 ensures+ # the speech pipeline loads before Ollama competes for VRAM.supervisor.warm_brain(launch_command=provider._launch_command)- return outcome in ("spawned", "already-running")+ return Truewarmed = await asyncio.to_thread(_warm)if warmed:@@ -1688,7 +1732,7 @@ class LocalRealtimeProvider:if not self._base_url:raise RuntimeError("No server URL configured for the self-hosted realtime provider "- "— set it on the provider card first (e.g. http://localhost:8080)."+ "— set it on the provider card first (e.g. http://127.0.0.1:8080).")deadline = time.monotonic() + self._connect_retry_window_s()attempt = 0diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.pyindex 85871652e6..1f6ea54413 100644--- a/jarvis/realtime/local_server/supervisor.py+++ b/jarvis/realtime/local_server/supervisor.py@@ -8,11 +8,12 @@ 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.+- **Ownership is an atomically replaced pidfile** plus an exclusive+ cross-process spawn lock. A thread lock cannot serialize two Jarvis+ processes. Neither file stores environment variables or secrets.+- **Readiness is the model-pool probe**, not a TCP accept. ``/v1/pool`` exists+ only after the speech pipelines are constructed. Port reachability remains+ diagnostic and is NEVER a kill criterion.- **The server intentionally survives app exit.** Instant next connect is theentire point of supervising it; ownership exists for deliberate stop /uninstall / reinstall, not for exit cleanup.@@ -29,11 +30,17 @@ from __future__ import annotationsimport jsonimport loggingimport os+import reimport socketimport subprocessimport threadingimport time+import uuid+from collections.abc import Iterator+from contextlib import contextmanagerfrom pathlib import Path+from typing import BinaryIO+from urllib.parse import SplitResult, urlsplit, urlunsplitlog = logging.getLogger(__name__)@@ -42,6 +49,14 @@ log = logging.getLogger(__name__)#: historical revive rate limit.SPAWN_MIN_INTERVAL_S = 60.0+# Installed checkpoints are already local after the mandatory smoke boot;+# 120 seconds still covers the measured 90-second CUDA graph cold start.+RUNTIME_READY_TIMEOUT_S = 120.0+RUNTIME_READY_POLL_S = 0.5+OWNED_STARTUP_TIMEOUT_S = RUNTIME_READY_TIMEOUT_S++_MAX_POOL_RESPONSE_BYTES = 64 * 1024+#: 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.@@ -73,21 +88,31 @@ def _server_log() -> Path:return _data_dir() / "local_realtime_server.log"+def _spawn_lock() -> Path:+ return _data_dir() / "local_realtime_server.spawn.lock"++# ── Address handling ─────────────────────────────────────────────────────+def _split_base_url(base_url: str) -> SplitResult:+ """Parse a local endpoint without DNS work and normalize WS schemes."""+ text = (base_url or "").strip() or f"http://127.0.0.1:{_DEFAULT_PORT}"+ if "://" not in text:+ text = f"http://{text}"+ parsed = urlsplit(text)+ scheme = {"ws": "http", "wss": "https"}.get(parsed.scheme.lower(), parsed.scheme.lower())+ return parsed._replace(scheme=scheme or "http")++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(":")+ """Host and port of a configured server address, IPv6-safe."""+ parsed = _split_base_url(base_url)try:- port = int(port_text) if port_text else _DEFAULT_PORT+ port = parsed.port or _DEFAULT_PORTexcept ValueError:port = _DEFAULT_PORT- return host or "localhost", port+ return parsed.hostname or "127.0.0.1", portdef _is_loopback(host: str) -> bool:@@ -102,6 +127,153 @@ def _port_open(port: int, timeout: float = 1.0) -> bool:return False+def _pool_url(base_url: str) -> str:+ """Return the pinned server's HTTP model-pool endpoint."""+ parsed = _split_base_url(base_url)+ host = parsed.hostname or "127.0.0.1"+ if host.lower() == "localhost":+ host = "127.0.0.1"+ host_text = f"[{host}]" if ":" in host else host+ try:+ port = parsed.port or _DEFAULT_PORT+ except ValueError:+ port = _DEFAULT_PORT+ default_port = 443 if parsed.scheme == "https" else 80+ netloc = host_text if port == default_port else f"{host_text}:{port}"+ path = parsed.path.rstrip("/")+ if path.endswith("/realtime"):+ path = path[: -len("/realtime")].rstrip("/")+ if not path.endswith("/v1"):+ path = f"{path}/v1" if path else "/v1"+ return urlunsplit((parsed.scheme, netloc, f"{path}/pool", "", ""))+++def probe_runtime(base_url: str, timeout: float = 0.75) -> dict[str, int] | None:+ """Return a sanitized live pool snapshot, or ``None`` when not ready.++ A TCP accept only proves that a socket exists. The pinned server mounts+ ``/v1/pool`` after constructing every speech pipeline, so a valid response+ is the first point at which a realtime handshake can actually succeed.+ Session identifiers and arbitrary server payload fields are deliberately+ discarded before anything reaches logs or the UI.+ """+ parsed = _split_base_url(base_url)+ host, _port = _host_port(base_url)+ if parsed.scheme not in {"http", "https"} or not _is_loopback(host):+ return None+ import http.client++ url = _pool_url(base_url)+ target = urlsplit(url)+ target_host = target.hostname+ if target_host is None:+ return None+ connection_type = (+ http.client.HTTPSConnection+ if target.scheme == "https"+ else http.client.HTTPConnection+ )+ connection = connection_type(+ target_host,+ target.port,+ timeout=max(0.05, timeout),+ )+ try:+ connection.request("GET", target.path, headers={"Accept": "application/json"})+ response = connection.getresponse()+ if response.status != 200:+ return None+ raw = response.read(_MAX_POOL_RESPONSE_BYTES + 1)+ except (http.client.HTTPException, OSError, TimeoutError, ValueError):+ return None+ finally:+ connection.close()+ if len(raw) > _MAX_POOL_RESPONSE_BYTES:+ return None+ try:+ payload = json.loads(raw.decode("utf-8"))+ except (UnicodeDecodeError, ValueError):+ return None+ if not isinstance(payload, dict):+ return None+ size = payload.get("size")+ in_use = payload.get("in_use")+ units = payload.get("units")+ if (+ type(size) is not int+ or type(in_use) is not int+ or size < 1+ or not 0 <= in_use <= size+ or not isinstance(units, list)+ or len(units) != size+ ):+ return None+ allowed_states = {"idle", "active", "draining", "stuck"}+ states: list[str] = []+ for unit in units:+ if not isinstance(unit, dict):+ return None+ state = unit.get("state")+ if not isinstance(state, str) or state not in allowed_states:+ return None+ states.append(state)+ return {+ "size": size,+ "in_use": in_use,+ "available": size - in_use,+ "stuck": states.count("stuck"),+ }+++def wait_until_ready(+ base_url: str,+ *,+ timeout: float = RUNTIME_READY_TIMEOUT_S,+ poll_interval: float = RUNTIME_READY_POLL_S,+ launch_command: str = "",+ cleanup_on_timeout: bool = False,+ cancel_event: threading.Event | None = None,+) -> bool:+ """Wait until the managed model pool, not merely TCP, answers.++ A timed-out managed child is torn down when requested so it cannot remain+ as an owned-but-never-ready zombie. Cancellation is different from a+ timeout: callers stopping the server set ``cancel_event`` and no second+ lifecycle operation is started from this waiter.+ """+ cleanup_root = managed_install_root(launch_command) if cleanup_on_timeout else None+ expected_generation = _owned_generation() if cleanup_root is not None else None+ deadline = time.monotonic() + max(0.0, timeout)+ while True:+ if cancel_event is not None and cancel_event.is_set():+ return False+ if probe_runtime(base_url, timeout=min(0.75, max(0.05, timeout))) is not None:+ return True+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ if cancel_event is not None and cancel_event.is_set():+ return False+ if cleanup_root is not None and expected_generation is not None:+ outcome, message = _cleanup_timed_out_generation(+ base_url=base_url,+ install_root=cleanup_root,+ expected_generation=expected_generation,+ )+ if outcome == "ready":+ return True+ log.warning(+ "local-realtime supervisor: readiness timed out; cleanup %s (%s)",+ outcome,+ message,+ )+ return False+ delay = min(max(0.01, poll_interval), remaining)+ if cancel_event is None:+ time.sleep(delay)+ elif cancel_event.wait(delay):+ return False++# ── Ownership (pidfile) ──────────────────────────────────────────────────@@ -117,6 +289,24 @@ def _read_pidfile() -> dict[str, object] | None:return data if isinstance(data, dict) else None+def _json_int(value: object) -> int | None:+ if isinstance(value, bool) or not isinstance(value, (int, str)):+ return None+ try:+ return int(value)+ except ValueError:+ return None+++def _json_float(value: object) -> float | None:+ if isinstance(value, bool) or not isinstance(value, (int, float, str)):+ return None+ try:+ return float(value)+ except ValueError:+ return None++def _process_create_time(pid: int) -> float | None:"""The process's kernel start stamp, or ``None`` when unverifiable."""try:@@ -141,38 +331,173 @@ def _owned_process() -> tuple[int | None, bool]:record = _read_pidfile()if record is None:return None, False- try:- pid = int(record.get("pid", 0) or 0)- except (TypeError, ValueError):+ pid = _json_int(record.get("pid"))+ if pid is None:return None, Falseif pid <= 0:return None, Falselive_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+ recorded_f = _json_float(record.get("create_time"))if recorded_f is None:return pid, Falsereturn pid, abs(live_created - recorded_f) < 1.0-def _write_pidfile(pid: int, port: int, command: str) -> None:+def _owned_generation() -> tuple[int, float, str] | None:+ """Verified identity of the exact child generation in the pidfile."""+ record = _read_pidfile()+ if record is None:+ return None+ pid = _json_int(record.get("pid"))+ created = _json_float(record.get("create_time"))+ token = record.get("spawn_token")+ if pid is None or pid <= 0 or created is None or not isinstance(token, str) or not token:+ return None+ live_created = _process_create_time(pid)+ if live_created is None or abs(live_created - created) >= 1.0:+ return None+ return pid, created, token+++def _verified_owned_command() -> str | None:+ """Launch command for the exact live process recorded in the pidfile."""+ record = _read_pidfile()+ if record is None:+ return None+ pid = _json_int(record.get("pid"))+ created = _json_float(record.get("create_time"))+ command = record.get("command")+ if (+ pid is None+ or pid <= 0+ or created is None+ or not isinstance(command, str)+ or not command.strip()+ ):+ return None+ live_created = _process_create_time(pid)+ if live_created is None or abs(live_created - created) >= 1.0:+ return None+ return command.strip()+++def _atomic_write_json(path: Path, payload: dict[str, object]) -> bool:+ """Durably replace one small ownership file without partial JSON."""+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ with temporary.open("x", encoding="utf-8") as handle:+ json.dump(payload, handle, indent=2)+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary, path)+ return True+ except OSError:+ log.warning("local-realtime supervisor: atomic ownership write failed", exc_info=True)+ return False+ finally:+ try:+ temporary.unlink(missing_ok=True)+ except OSError:+ log.debug("supervisor: temporary ownership cleanup failed", exc_info=True)+++def _write_pidfile(pid: int, port: int, command: str) -> bool:+ create_time = _process_create_time(pid)+ if create_time is None:+ log.error(+ "local-realtime supervisor: cannot verify create time for spawned pid %s",+ pid,+ )+ return Falsepayload = {"pid": pid,- "create_time": _process_create_time(pid),+ "create_time": create_time,"port": port,"command": command,"spawned_at": time.time(),+ "spawn_token": uuid.uuid4().hex,}+ return _atomic_write_json(_pidfile(), payload)+++def _try_lock_file(handle: BinaryIO) -> bool:+ """Acquire one non-blocking OS lock, automatically released on death."""try:- _pidfile().parent.mkdir(parents=True, exist_ok=True)- _pidfile().write_text(json.dumps(payload, indent=2), encoding="utf-8")+ handle.seek(0, os.SEEK_END)+ if handle.tell() == 0:+ handle.write(b"\0")+ handle.flush()+ os.fsync(handle.fileno())+ handle.seek(0)+ if os.name == "nt":+ import msvcrt # lazy, Windows only++ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)+ else:+ import fcntl # lazy, POSIX only++ fcntl.flock( # type: ignore[attr-defined]+ handle.fileno(),+ fcntl.LOCK_EX | fcntl.LOCK_NB, # type: ignore[attr-defined]+ )+ return Trueexcept OSError:- log.warning("local-realtime supervisor: pidfile write failed", exc_info=True)+ return False+++def _unlock_file(handle: BinaryIO) -> None:+ handle.seek(0)+ if os.name == "nt":+ import msvcrt # lazy, Windows only++ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ import fcntl # lazy, POSIX only++ fcntl.flock( # type: ignore[attr-defined]+ handle.fileno(),+ fcntl.LOCK_UN, # type: ignore[attr-defined]+ )+++@contextmanager+def _exclusive_spawn_guard() -> Iterator[bool]:+ """Cross-process lifecycle lease backed by a kernel-held file lock."""+ path = _spawn_lock()+ handle: BinaryIO | None = None+ acquired = False+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ handle = path.open("a+b")+ acquired = _try_lock_file(handle)+ except OSError:+ log.warning("supervisor: lifecycle lease creation failed", exc_info=True)+ try:+ yield acquired+ finally:+ if handle is not None:+ if acquired:+ try:+ _unlock_file(handle)+ except OSError:+ log.warning("supervisor: lifecycle lease release failed", exc_info=True)+ handle.close()+++@contextmanager+def lifecycle_guard() -> Iterator[bool]:+ """Non-blocking in-process and cross-process lifecycle single-flight."""+ if not _LOCK.acquire(blocking=False):+ yield False+ return+ try:+ with _exclusive_spawn_guard() as acquired:+ yield acquired+ finally:+ _LOCK.release()def clear_pidfile() -> None:@@ -221,17 +546,16 @@ def hardened_child_env(*, inject_openai_key: bool) -> dict[str, str]: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)+ """Live ownership plus distinct TCP and model-readiness verdicts."""+ host, port = _host_port(base_url)pid, alive = _owned_process()+ reachable = _is_loopback(host) and _port_open(port, timeout=0.25)+ pool = probe_runtime(base_url, timeout=0.5) if reachable else Nonereturn {- "reachable": _port_open(port),+ "reachable": reachable,+ "ready": pool is not None,+ "available": bool(pool and pool["available"] > 0),+ "pool": pool,"port": port,"pid": pid,"owned": alive,@@ -242,6 +566,98 @@ def status(base_url: str = "") -> dict[str, object]:# ── Spawn ────────────────────────────────────────────────────────────────+def _recorded_spawn_age() -> float | None:+ record = _read_pidfile()+ if record is None:+ return None+ started_at = _json_float(record.get("spawned_at"))+ if started_at is None:+ started_at = _json_float(record.get("create_time"))+ if started_at is None:+ return None+ age = time.time() - started_at+ return age if age >= 0.0 else None+++def _recorded_spawn_is_recent() -> bool:+ age = _recorded_spawn_age()+ return age is not None and age < SPAWN_MIN_INTERVAL_S+++def _command_references_root(command: str, root: Path) -> bool:+ """Whether a launch token resolves inside the managed install tree."""+ try:+ import shlex++ tokens = shlex.split(command, posix=os.name != "nt")+ resolved_root = root.resolve()+ except (OSError, ValueError):+ return False+ for token in tokens:+ candidate = token.split("=", 1)[-1].strip("\"'")+ if not candidate or not Path(candidate).is_absolute():+ continue+ try:+ if Path(candidate).resolve().is_relative_to(resolved_root):+ return True+ except OSError:+ continue+ return False+++def managed_install_root(launch_command: str) -> Path | None:+ """Return the managed install root referenced by a launch command."""+ command = (launch_command or "").strip()+ if not command:+ return None+ try:+ from jarvis.realtime.local_server import install # lazy (AP-26)++ root = install.install_root()+ except Exception: # noqa: BLE001 - optional install state is advisory+ log.debug("supervisor: managed install root unavailable", exc_info=True)+ return None+ return root if _command_references_root(command, root) else None+++def is_managed_launch_command(launch_command: str) -> bool:+ """Whether the command belongs to Jarvis's pinned managed server."""+ return managed_install_root(launch_command) is not None+++_WS_HOST_FLAG = re.compile(+ r"(?<!\S)--ws_host(?:\s+|=)(?:\"[^\"]*\"|'[^']*'|\S+)",+ re.IGNORECASE,+)+++def _force_loopback_bind(command: str) -> str:+ """Migrate legacy managed commands to a loopback-only server bind."""+ if _WS_HOST_FLAG.search(command):+ return _WS_HOST_FLAG.sub("--ws_host 127.0.0.1", command)+ return f"{command.rstrip()} --ws_host 127.0.0.1"+++def _uses_loopback_bind(command: str) -> bool:+ """Whether the effective managed-server bind is explicitly loopback-only."""+ try:+ import shlex++ tokens = shlex.split(command, posix=os.name != "nt")+ except ValueError:+ return False+ host: str | None = None+ for index, token in enumerate(tokens):+ lowered = token.lower()+ if lowered == "--ws_host":+ if index + 1 >= len(tokens):+ return False+ host = tokens[index + 1]+ elif lowered.startswith("--ws_host="):+ host = token.split("=", 1)[1]+ return host is not None and _is_loopback(host.strip().strip("[]"))++def ensure_running(*, launch_command: str, base_url: str, reason: str) -> str:"""Start the server if — and only if — starting can help.@@ -256,33 +672,100 @@ def ensure_running(*, launch_command: str, base_url: str, reason: str) -> str:host, port = _host_port(base_url)if not _is_loopback(host):return "refused:not-local"- with _LOCK:- if _port_open(port):+ with lifecycle_guard() as guarded:+ if not guarded:+ return "refused:spawn-in-progress"++ managed_root = managed_install_root(command)+ if managed_root is not None:+ # Existing installs predate the loopback flag. Normalize at the+ # actual spawn boundary so they become safe without a reinstall.+ command = _force_loopback_bind(command)+ try:+ from jarvis.realtime.local_server import install # lazy (AP-26)++ if install.snapshot().get("running"):+ return "refused:install-running"+ except Exception: # noqa: BLE001 - install state is advisory here+ log.debug("supervisor: install snapshot unavailable", exc_info=True)++ pool = probe_runtime(base_url, timeout=0.25)+ port_open = pool is not None or _port_open(port, timeout=0.25)+ _pid, alive = _owned_process()+ if managed_root is not None and alive:+ owned_command = _verified_owned_command()+ 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):+ # 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.+ changed, message = _stop_owned_unlocked(+ owned_only=True,+ install_root=owned_root,+ )+ if not changed:+ log.warning(+ "local-realtime supervisor: unsafe legacy bind migration failed (%s)",+ message,+ )+ return "refused:stuck-process"+ pool = None+ alive = False+ port_open = _port_open(port, timeout=0.25)+ if pool is not None: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)+ age = _recorded_spawn_age()+ if managed_root is None or age is None or age < OWNED_STARTUP_TIMEOUT_S:+ # The child may still be loading. A second process would fight+ # it for GPU memory and corrupt the readiness signal.+ return "already-running"+ changed, message = _stop_owned_unlocked(+ owned_only=True,+ install_root=managed_root,+ )+ if not changed:+ log.warning(+ "local-realtime supervisor: stale owned process cleanup failed (%s)",+ message,+ )+ return "refused:stuck-process"+ port_open = _port_open(port, timeout=0.25)+ if port_open:+ # The managed stack has a pinned readiness contract, so an+ # unowned non-protocol listener is a collision. Bring-your-own+ # servers are not required to implement /v1/pool.+ return "refused:port-in-use" if managed_root is not None else "already-running"+global _last_spawn_atnow = time.monotonic()- if now - _last_spawn_at < SPAWN_MIN_INTERVAL_S:+ if now - _last_spawn_at < SPAWN_MIN_INTERVAL_S or _recorded_spawn_is_recent():return "refused:rate-limited"- _last_spawn_at = now++ # A crash between Popen and the old non-atomic pidfile write left an+ # untracked model process. Sweep only OUR managed install tree and+ # only while the cross-process guard is held.+ if managed_root is not None:+ killed, survivors = _kill_by_install_root(managed_root)+ if survivors:+ return "refused:managed-process-survived"+ if killed:+ log.warning(+ "local-realtime supervisor: removed %s orphan process(es) before spawn",+ killed,+ )+ clear_pidfile()spawned_pid = _spawn(command, reason=reason)if spawned_pid is None:return "refused:spawn-failed"- _write_pidfile(spawned_pid, port, command)+ _last_spawn_at = now+ if not _write_pidfile(spawned_pid, port, command):+ _kill_pid_tree(spawned_pid)+ if managed_root is not None:+ _kill_by_install_root(managed_root)+ return "refused:ownership-failed"log.info("local-realtime supervisor: spawned server pid=%s (%s)",spawned_pid,@@ -345,42 +828,105 @@ def _spawn(command: str, *, reason: str) -> int | None:def stop(*, owned_only: bool = True, install_root: Path | None = None) -> tuple[bool, str]:+ """Serialize a deliberate stop against every start and cleanup."""+ with lifecycle_guard() as guarded:+ if not guarded:+ return False, "server lifecycle operation already in progress"+ return _stop_owned_unlocked(owned_only=owned_only, install_root=install_root)+++def _stop_owned_unlocked(+ *,+ 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.+ Kill order: the pidfile's verified pid tree (create-time match) first,+ followed by an install-root sweep even when that kill succeeded. The+ second step catches a model process orphaned before ownership was written.+ A port match is never a kill criterion, so a foreign listener survives."""pid, alive = _owned_process()+ owner_stopped = Falseif alive and pid is not None:- ok = _kill_pid_tree(pid)+ owner_stopped = _kill_pid_tree(pid)+ elif pid is not None: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:++ # Always sweep after the parent-tree kill. A failed bind can leave a+ # second managed process alive even though the recorded parent stopped;+ # returning early here was the orphan leak seen in the live incident.+ swept, survivors = (+ _kill_by_install_root(install_root) if install_root is not None else (0, 0)+ )+ if survivors:+ if owner_stopped:+ clear_pidfile()+ return False, f"could not stop {survivors} managed process(es)"+ if owner_stopped or swept: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}"+ details: list[str] = []+ if owner_stopped and pid is not None:+ details.append(f"pid {pid}")+ if swept:+ details.append(f"{swept} managed process(es)")+ return True, f"stopped {' and '.join(details)}"+ if alive and pid is not None:+ return False, f"could not stop pid {pid}"if not owned_only:log.info("supervisor: no owned server process found to stop")return False, "no owned server process found"+def _cleanup_timed_out_generation(+ *,+ base_url: str,+ install_root: Path,+ expected_generation: tuple[int, float, str],+) -> tuple[str, str]:+ """Conditionally stop only the exact child a readiness waiter observed."""+ with lifecycle_guard() as guarded:+ if not guarded:+ return "deferred", "another lifecycle operation is in progress"+ # Both checks occur while the lifecycle lease is held. No newer spawn+ # can slip between the readiness verdict, generation compare and stop.+ if probe_runtime(base_url, timeout=0.75) is not None:+ return "ready", "model pool became ready at the timeout boundary"+ if _owned_generation() != expected_generation:+ return "skipped", "owned server generation changed"+ changed, message = _stop_owned_unlocked(+ owned_only=True,+ install_root=install_root,+ )+ return ("completed" if changed else "failed"), message++def _kill_pid_tree(pid: int) -> bool:try:if os.name == "nt":from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # lazy- subprocess.run(+ result = subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"],capture_output=True,timeout=30,creationflags=NO_WINDOW_CREATIONFLAGS,)- return True+ if result.returncode == 0:+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline and _pid_exists(pid):+ time.sleep(0.1)+ if not _pid_exists(pid):+ return True+ stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""+ log.warning(+ "supervisor: taskkill did not terminate pid %s (exit %s): %s",+ pid,+ result.returncode,+ stderr.strip()[:300],+ )+ return Falseimport signal# The spawn used start_new_session, so the pid IS the group leader:@@ -422,26 +968,94 @@ def _pid_exists(pid: int) -> bool:return True-def _kill_by_install_root(root: Path) -> int:- """Kill processes running out of the managed tree. Needs psutil; else 0."""+def _path_is_within_root(value: str, root: Path) -> bool:+ text = (value or "").strip().strip("\"'")+ if "=" in text:+ text = text.split("=", 1)[1].strip().strip("\"'")+ if not text or not Path(text).is_absolute():+ return False+ try:+ candidate = Path(text).resolve()+ except OSError:+ return False+ return candidate == root or candidate.is_relative_to(root)+++def _lexical_path_is_within_root(value: str, root: Path) -> bool:+ """Containment without dereferencing a POSIX venv interpreter symlink."""+ text = (value or "").strip().strip("\"'")+ if not text or not Path(text).is_absolute():+ return False+ candidate = os.path.normcase(os.path.abspath(text))+ root_text = os.path.normcase(os.path.abspath(root))+ try:+ return os.path.commonpath((candidate, root_text)) == root_text+ except ValueError:+ return False+++def _process_identity_is_managed(exe: str, cmdline: tuple[str, ...], root: Path) -> bool:+ """Match only executable identity, never arbitrary opened-file arguments."""+ return _lexical_path_is_within_root(exe, root) or bool(+ cmdline and _lexical_path_is_within_root(cmdline[0], root)+ )+++def _kill_by_install_root(root: Path) -> tuple[int, int]:+ """Return ``(stopped, survivors)`` for processes in OUR managed tree."""+ try:+ resolved_root = root.resolve()+ except OSError:+ return 0, 0+ if resolved_root.name.lower() != "local_realtime" or not resolved_root.exists():+ log.warning("supervisor: refused unsafe install-root sweep of %s", resolved_root)+ return 0, 0try:import psutil # type: ignore[import-untyped]except ImportError:log.debug("supervisor: psutil unavailable — skipping needle scan")- return 0- needle = str(root).lower()- killed = 0+ return 0, 0++ protected = {os.getpid()}+ try:+ protected.update(parent.pid for parent in psutil.Process().parents())+ except psutil.Error:+ log.debug("supervisor: process-parent protection lookup failed", exc_info=True)++ matches = []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+ if int(proc.info.get("pid") or 0) in protected:+ continue+ exe = str(proc.info.get("exe") or "")+ cmdline = tuple(str(item) for item in (proc.info.get("cmdline") or ()))+ if _process_identity_is_managed(exe, cmdline, resolved_root):+ matches.append(proc)+ except (psutil.Error, OSError, TypeError, ValueError):+ log.debug("supervisor: managed process inspection failed", exc_info=True)++ signalled = []+ vanished = 0+ failed = 0+ for proc in matches:+ try:+ proc.kill()+ signalled.append(proc)+ except psutil.NoSuchProcess:+ vanished += 1+ except (psutil.Error, OSError):+ failed += 1+ log.warning(+ "supervisor: could not kill managed pid %s",+ getattr(proc, "pid", "?"),+ exc_info=True,+ )+ if not signalled:+ return vanished, failed+ gone, alive = psutil.wait_procs(signalled, timeout=10)+ for proc in alive:+ log.warning("supervisor: managed pid %s survived forced stop", proc.pid)+ return vanished + len(gone), failed + len(alive)# ── Brain warm-up ────────────────────────────────────────────────────────diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.pyindex d432bb5cfb..0a26a5ce35 100644--- a/tests/unit/realtime/local_server/test_supervisor.py+++ b/tests/unit/realtime/local_server/test_supervisor.py@@ -11,7 +11,10 @@ provider registry (AP-21: the artifact's own capability).from __future__ import annotationsimport json+import osimport subprocess+import sys+import timefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any@@ -29,6 +32,8 @@ def _spawn_ready(monkeypatch, tmp_path: Path) -> list[dict[str, Any]]:"""monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.0)spawned: list[dict[str, Any]] = []def fake_popen(command: Any, **kwargs: Any) -> SimpleNamespace:@@ -45,11 +50,138 @@ def _spawn_ready(monkeypatch, tmp_path: Path) -> list[dict[str, Any]]: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("") == ("127.0.0.1", 8765)assert supervisor._host_port("localhost") == ("localhost", 8765)+ assert supervisor._host_port("http://[::1]:9000/v1") == ("::1", 9000)assert supervisor._host_port("http://gpu.lan:8443") == ("gpu.lan", 8443)+def test_pool_url_normalizes_every_supported_input_shape() -> None:+ assert supervisor._pool_url("http://localhost:8765") == ("http://127.0.0.1:8765/v1/pool")+ assert supervisor._pool_url("ws://localhost:8765/v1/realtime") == (+ "http://127.0.0.1:8765/v1/pool"+ )+ assert supervisor._pool_url("http://[::1]:8765/v1") == ("http://[::1]:8765/v1/pool")+++def test_runtime_probe_requires_a_valid_loaded_pool(monkeypatch) -> None:+ import http.client++ class _Response:+ status = 200++ def __init__(self, payload: object) -> None:+ self._payload = json.dumps(payload).encode("utf-8")++ def read(self, limit: int) -> bytes:+ return self._payload[:limit]++ payload = {+ "size": 2,+ "in_use": 1,+ "units": [+ {"index": 0, "state": "active", "session_id": "private"},+ {"index": 1, "state": "idle", "session_id": None},+ ],+ }+ class _Connection:+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ pass++ def request(self, *args: Any, **kwargs: Any) -> None:+ pass++ def getresponse(self) -> _Response:+ return _Response(payload)++ def close(self) -> None:+ pass++ monkeypatch.setattr(http.client, "HTTPConnection", _Connection)+ assert supervisor.probe_runtime("http://localhost:8765") == {+ "size": 2,+ "in_use": 1,+ "available": 1,+ "stuck": 0,+ }++ payload["units"] = []+ assert supervisor.probe_runtime("http://localhost:8765") is None+++def test_wait_until_ready_ignores_tcp_and_waits_for_the_pool(monkeypatch) -> None:+ answers = iter([None, None, {"size": 1, "in_use": 0, "available": 1, "stuck": 0}])+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: next(answers))+ assert supervisor.wait_until_ready("http://127.0.0.1:8765", timeout=1.0, poll_interval=0.001)+++def test_managed_readiness_timeout_cleans_up_the_zombie(monkeypatch, tmp_path) -> None:+ root = tmp_path / "local_realtime"+ entrypoint = root / "venv" / "server.exe"+ command = f'"{entrypoint}" --mode realtime'+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor, "managed_install_root", lambda value: root)+ generation = (4711, 1000.0, "generation-a")+ monkeypatch.setattr(supervisor, "_owned_generation", lambda: generation)+ cleaned: list[tuple[Path, tuple[int, float, str]]] = []+ monkeypatch.setattr(+ supervisor,+ "_cleanup_timed_out_generation",+ lambda **kwargs: cleaned.append(+ (kwargs["install_root"], kwargs["expected_generation"])+ )+ or ("completed", "stopped pid 4711"),+ )++ assert not supervisor.wait_until_ready(+ "http://127.0.0.1:8765",+ timeout=0.0,+ launch_command=command,+ cleanup_on_timeout=True,+ )+ assert cleaned == [(root, generation)]+++def test_timeout_cleanup_skips_a_newer_owned_generation(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ expected = (4711, 1000.0, "generation-a")+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(+ supervisor,+ "_owned_generation",+ lambda: (7331, 2000.0, "generation-b"),+ )++ def forbidden_stop(**kwargs):+ raise AssertionError("a stale waiter must not stop a newer child")++ monkeypatch.setattr(supervisor, "_stop_owned_unlocked", forbidden_stop)+ outcome, message = supervisor._cleanup_timed_out_generation(+ base_url="http://127.0.0.1:8765",+ install_root=tmp_path / "local_realtime",+ expected_generation=expected,+ )+ assert outcome == "skipped"+ assert "generation changed" in message+++def test_timeout_cleanup_reprobes_readiness_under_the_lease(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ pool = {"size": 1, "in_use": 0, "available": 1, "stuck": 0}+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)++ def forbidden_stop(**kwargs):+ raise AssertionError("a ready child must not be stopped")++ monkeypatch.setattr(supervisor, "_stop_owned_unlocked", forbidden_stop)+ outcome, _message = supervisor._cleanup_timed_out_generation(+ base_url="http://127.0.0.1:8765",+ install_root=tmp_path / "local_realtime",+ expected_generation=(4711, 1000.0, "generation-a"),+ )+ assert outcome == "ready"++# ── ensure_running: refusals ─────────────────────────────────────────────def test_no_launch_command_is_refused(tmp_path, monkeypatch) -> None:monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))@@ -69,8 +201,9 @@ def test_remote_targets_are_refused(tmp_path, monkeypatch) -> None:assert outcome == "refused:not-local"-def test_a_served_port_means_already_running(monkeypatch, tmp_path) -> None:+def test_a_byo_listener_without_the_private_pool_is_reused(monkeypatch, tmp_path) -> None:monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)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"@@ -78,11 +211,46 @@ def test_a_served_port_means_already_running(monkeypatch, tmp_path) -> None:assert outcome == "already-running"+def test_an_unowned_managed_nonprotocol_listener_blocks_spawn(monkeypatch, tmp_path) -> None:+ from jarvis.realtime.local_server import install++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ root = install.install_root()+ entrypoint = root / "venv" / "server.exe"+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: True)+ outcome = supervisor.ensure_running(+ launch_command=f'"{entrypoint}" --mode realtime',+ base_url="http://localhost:8765",+ reason="test",+ )+ assert outcome == "refused:port-in-use"+++def test_a_ready_protocol_server_means_already_running(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ monkeypatch.setattr(+ supervisor,+ "probe_runtime",+ lambda *args, **kwargs: {+ "size": 1,+ "in_use": 0,+ "available": 1,+ "stuck": 0,+ },+ )+ 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 secondspawn 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, "probe_runtime", lambda *args, **kwargs: None)monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))outcome = supervisor.ensure_running(launch_command="serve", base_url="http://localhost:8765", reason="test"@@ -90,6 +258,53 @@ def test_an_alive_owned_process_is_not_double_spawned(monkeypatch, tmp_path) ->assert outcome == "already-running"+def test_an_owned_managed_zombie_is_replaced_after_startup_deadline(+ monkeypatch, tmp_path+) -> None:+ from jarvis.realtime.local_server import install++ supervisor._reset_for_tests()+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ entrypoint = install.install_root() / "venv" / "server.exe"+ command = f'"{entrypoint}" --mode realtime'+ (tmp_path / "local_realtime_server.pid.json").write_text(+ json.dumps(+ {+ "pid": 4711,+ "create_time": 1000.0,+ "spawned_at": time.time() - supervisor.OWNED_STARTUP_TIMEOUT_S - 1,+ "port": 8765,+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: False)+ 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+ )+ monkeypatch.setattr(supervisor, "_kill_by_install_root", lambda root: (0, 0))+ spawned: list[str] = []+ monkeypatch.setattr(+ supervisor,+ "_spawn",+ lambda candidate, **kwargs: spawned.append(candidate) or 7331,+ )+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: True)++ outcome = supervisor.ensure_running(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ reason="test",+ )++ assert outcome == "spawned"+ assert killed == [4711]+ assert spawned and "--ws_host 127.0.0.1" in spawned[0]++def test_a_running_install_blocks_the_spawn(monkeypatch, tmp_path) -> None:"""Spawning a half-installed venv proves nothing and locks files theinstaller is about to replace."""@@ -99,8 +314,11 @@ def test_a_running_install_blocks_the_spawn(monkeypatch, tmp_path) -> None:monkeypatch.setattr(install, "snapshot", lambda: {"running": True, "phase": "deps"})+ entrypoint = install.install_root() / "venv" / "server.exe"outcome = supervisor.ensure_running(- launch_command="serve", base_url="http://localhost:8765", reason="test"+ launch_command=f'"{entrypoint}" --mode realtime',+ base_url="http://localhost:8765",+ reason="test",)assert outcome == "refused:install-running"@@ -111,6 +329,10 @@ def test_spawns_are_rate_limited(monkeypatch, tmp_path) -> None:first = supervisor.ensure_running(launch_command="serve", base_url="http://localhost:8765", reason="test")+ # Simulate the just-spawned process crashing. A healthy owner correctly+ # returns already-running; the persisted spawn timestamp is what must+ # still stop a different Jarvis process from immediately replacing it.+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, False))second = supervisor.ensure_running(launch_command="serve", base_url="http://localhost:8765", reason="test")@@ -122,6 +344,7 @@ def test_spawns_are_rate_limited(monkeypatch, tmp_path) -> None: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)+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)def broken_popen(command: Any, **kwargs: Any) -> SimpleNamespace:raise FileNotFoundError(command)@@ -133,6 +356,78 @@ def test_a_failing_spawn_is_reported_not_raised(monkeypatch, tmp_path) -> None:assert outcome == "refused:spawn-failed"+def test_a_failing_spawn_does_not_consume_the_retry_window(monkeypatch, tmp_path) -> None:+ supervisor._reset_for_tests()+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: False)+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ attempts = iter([None, 7331])+ monkeypatch.setattr(supervisor, "_spawn", lambda *args, **kwargs: next(attempts))+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: True)++ 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 == "refused:spawn-failed"+ assert second == "spawned"+++def test_an_abandoned_lock_file_is_not_a_stale_lease(monkeypatch, tmp_path) -> None:+ """Kernel ownership, not file age/content, decides whether the lease is live."""+ spawned = _spawn_ready(monkeypatch, tmp_path)+ lock = tmp_path / "local_realtime_server.spawn.lock"+ lock.write_bytes(b"old-owner-metadata")+ outcome = supervisor.ensure_running(+ launch_command="serve", base_url="http://127.0.0.1:8765", reason="test"+ )+ assert outcome == "spawned"+ assert len(spawned) == 1+ assert lock.is_file()+++def test_the_lifecycle_lease_serializes_real_processes(monkeypatch, tmp_path) -> None:+ """A thread lock cannot protect two Jarvis processes; the OS lease can."""+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ env = dict(os.environ)+ env["JARVIS_DATA_DIR"] = str(tmp_path)+ script = (+ "from jarvis.realtime.local_server import supervisor; "+ "guard=supervisor._exclusive_spawn_guard(); "+ "value=guard.__enter__(); print(value); guard.__exit__(None,None,None)"+ )+ with supervisor._exclusive_spawn_guard() as acquired:+ assert acquired is True+ result = subprocess.run(+ [sys.executable, "-c", script],+ capture_output=True,+ text=True,+ encoding="utf-8",+ env=env,+ timeout=15,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "False"+++def test_a_spawn_without_durable_ownership_is_torn_down(monkeypatch, tmp_path) -> None:+ _spawn_ready(monkeypatch, tmp_path)+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: False)+ killed: list[int] = []+ monkeypatch.setattr(supervisor, "_kill_pid_tree", lambda pid: killed.append(pid) or True)+ outcome = supervisor.ensure_running(+ launch_command="serve", base_url="http://127.0.0.1:8765", reason="test"+ )+ assert outcome == "refused:ownership-failed"+ assert killed == [4711]++# ── 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@@ -150,6 +445,125 @@ def test_spawn_is_windowless_and_records_ownership(monkeypatch, tmp_path) -> Nonassert record["port"] == 8765assert record["command"] == "serve --flag"assert "env" not in {k for k in record} # never environment, never secrets+ assert list(tmp_path.glob("*.tmp")) == []+ assert (tmp_path / "local_realtime_server.spawn.lock").is_file()+++def test_legacy_managed_command_is_bound_to_loopback_at_spawn(monkeypatch, tmp_path) -> None:+ from jarvis.realtime.local_server import install++ supervisor._reset_for_tests()+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ entrypoint = install.install_root() / "venv" / "server.exe"+ command = f'"{entrypoint}" --mode realtime --ws_host 0.0.0.0'+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: False)+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (None, False))+ monkeypatch.setattr(supervisor, "_kill_by_install_root", lambda root: (0, 0))+ spawned: list[str] = []+ monkeypatch.setattr(+ supervisor,+ "_spawn",+ lambda candidate, **kwargs: spawned.append(candidate) or 7331,+ )+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: True)++ assert (+ supervisor.ensure_running(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ reason="test",+ )+ == "spawned"+ )+ assert spawned[0].count("--ws_host") == 1+ assert "--ws_host 127.0.0.1" in spawned[0]+ assert "0.0.0.0" not in spawned[0] # noqa: S104 - legacy input assertion+++def test_a_ready_owned_legacy_bind_is_migrated_to_loopback(monkeypatch, tmp_path) -> None:+ from jarvis.realtime.local_server import install++ supervisor._reset_for_tests()+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ entrypoint = install.install_root() / "venv" / "server.exe"+ legacy = f'"{entrypoint}" --mode realtime --ws_host 0.0.0.0'+ (tmp_path / "local_realtime_server.pid.json").write_text(+ json.dumps(+ {+ "pid": 4711,+ "create_time": 1000.0,+ "spawned_at": 1000.0,+ "port": 8765,+ "command": legacy,+ }+ ),+ encoding="utf-8",+ )+ pool = {"size": 1, "in_use": 0, "available": 1, "stuck": 0}+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.0)+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: False)+ stopped: list[Path] = []+ monkeypatch.setattr(+ supervisor,+ "_stop_owned_unlocked",+ lambda **kwargs: stopped.append(kwargs["install_root"]) or (True, "stopped"),+ )+ monkeypatch.setattr(supervisor, "_kill_by_install_root", lambda root: (0, 0))+ spawned: list[str] = []+ monkeypatch.setattr(+ supervisor,+ "_spawn",+ lambda command, **kwargs: spawned.append(command) or 7331,+ )+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: True)++ outcome = supervisor.ensure_running(+ launch_command=legacy,+ base_url="http://127.0.0.1:8765",+ reason="upgrade",+ )++ assert outcome == "spawned"+ assert stopped == [install.install_root()]+ assert spawned[0].count("--ws_host") == 1+ assert "--ws_host 127.0.0.1" in spawned[0]+++def test_a_ready_owned_loopback_bind_is_not_restarted(monkeypatch, tmp_path) -> None:+ from jarvis.realtime.local_server import install++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ entrypoint = install.install_root() / "venv" / "server.exe"+ command = f'"{entrypoint}" --mode realtime --ws_host 127.0.0.1'+ (tmp_path / "local_realtime_server.pid.json").write_text(+ json.dumps(+ {+ "pid": 4711,+ "create_time": 1000.0,+ "port": 8765,+ "command": command,+ }+ ),+ encoding="utf-8",+ )+ pool = {"size": 1, "in_use": 0, "available": 1, "stuck": 0}+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.0)+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)++ def forbidden_stop(**kwargs):+ raise AssertionError("a loopback-bound server must stay alive")++ monkeypatch.setattr(supervisor, "_stop_owned_unlocked", forbidden_stop)+ assert (+ supervisor.ensure_running(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ reason="upgrade",+ )+ == "already-running"+ )def test_pid_reuse_is_never_trusted(monkeypatch, tmp_path) -> None:@@ -184,23 +598,78 @@ def test_stop_without_ownership_changes_nothing(monkeypatch, tmp_path) -> None:assert "no owned" in message-def test_stop_kills_only_the_verified_pid(monkeypatch, tmp_path) -> None:+def test_stop_kills_the_verified_tree_and_sweeps_managed_orphans(monkeypatch, tmp_path) -> None:monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ install_root = tmp_path / "local_realtime"+ install_root.mkdir()(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)+ swept: list[Path] = []monkeypatch.setattr(- supervisor, "_kill_pid_tree", lambda pid: killed.append(pid) or True+ supervisor,+ "_kill_by_install_root",+ lambda root: swept.append(root) or (2, 0),)- changed, message = supervisor.stop(owned_only=True)+ changed, message = supervisor.stop(owned_only=True, install_root=install_root)assert changed is Trueassert killed == [4711]+ assert swept == [install_root]+ assert "2 managed process(es)" in messageassert not (tmp_path / "local_realtime_server.pid.json").exists()+def test_stop_succeeds_when_tree_kill_fails_but_managed_sweep_recovers(+ monkeypatch, tmp_path+) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ root = tmp_path / "local_realtime"+ root.mkdir()+ (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)+ monkeypatch.setattr(supervisor, "_kill_pid_tree", lambda pid: False)+ monkeypatch.setattr(supervisor, "_kill_by_install_root", lambda value: (1, 0))++ changed, message = supervisor.stop(owned_only=True, install_root=root)++ assert changed is True+ assert "1 managed process(es)" in message+ assert not (tmp_path / "local_realtime_server.pid.json").exists()+++def test_stop_fails_closed_when_a_managed_process_survives(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ root = tmp_path / "local_realtime"+ root.mkdir()+ monkeypatch.setattr(supervisor, "_kill_by_install_root", lambda value: (1, 1))++ changed, message = supervisor.stop(owned_only=True, install_root=root)++ assert changed is False+ assert "could not stop 1 managed process" in message+++def test_windows_taskkill_success_code_is_not_enough_if_pid_survives(monkeypatch) -> None:+ monkeypatch.setattr(supervisor.os, "name", "nt")+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *args, **kwargs: SimpleNamespace(returncode=0, stderr=b""),+ )+ monkeypatch.setattr(supervisor, "_pid_exists", lambda pid: True)+ moments = iter([0.0, 6.0])+ monkeypatch.setattr(supervisor.time, "monotonic", lambda: next(moments))++ assert supervisor._kill_pid_tree(4711) is False++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))@@ -214,14 +683,57 @@ def test_stop_clears_a_stale_pidfile(monkeypatch, tmp_path) -> None:assert not (tmp_path / "local_realtime_server.pid.json").exists()+def test_install_root_matching_has_a_real_path_boundary(tmp_path) -> None:+ root = (tmp_path / "local_realtime").resolve()+ root.mkdir()+ assert supervisor._path_is_within_root(str(root / "venv" / "server.exe"), root)+ assert not supervisor._path_is_within_root(+ str(tmp_path / "local_realtime_backup" / "server.exe"), root+ )+++def test_managed_sweep_ignores_an_editor_opening_a_file_in_the_tree(tmp_path) -> None:+ root = (tmp_path / "local_realtime").resolve()+ root.mkdir()+ editor = str((tmp_path / "editor.exe").resolve())+ log_file = str((root / "smoke_boot.log").resolve())+ assert not supervisor._process_identity_is_managed(+ editor,+ (editor, log_file),+ root,+ )+ managed = str((root / "venv" / "server.exe").resolve())+ assert supervisor._process_identity_is_managed(managed, (managed,), root)+++def test_managed_identity_keeps_a_posix_venv_python_symlink_lexical(tmp_path) -> None:+ if os.name == "nt":+ return+ root = (tmp_path / "local_realtime").resolve()+ interpreter = root / "venv" / "bin" / "python"+ interpreter.parent.mkdir(parents=True)+ interpreter.symlink_to(Path(sys.executable))+ assert not interpreter.resolve().is_relative_to(root)+ assert supervisor._process_identity_is_managed(+ str(interpreter.resolve()),+ (str(interpreter), str(root / "venv" / "bin" / "speech-to-speech")),+ root,+ )++# ── 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)+ pool = {"size": 1, "in_use": 0, "available": 1, "stuck": 0}+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)monkeypatch.setattr(supervisor, "_owned_process", lambda: (None, False))status = supervisor.status("http://localhost:8765")assert status == {"reachable": True,+ "ready": True,+ "available": True,+ "pool": pool,"port": 8765,"pid": None,"owned": False,@@ -229,6 +741,18 @@ def test_status_reports_reachable_and_ownership(monkeypatch, tmp_path) -> None:}+def test_status_never_calls_a_tcp_listener_model_ready(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, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))+ runtime = supervisor.status("http://127.0.0.1:8765")+ assert runtime["reachable"] is True+ assert runtime["ready"] is False+ assert runtime["available"] is False+ assert runtime["pool"] is None++# ── brain warm-up ────────────────────────────────────────────────────────_COMMAND = ('"C:\\tree\\venv\\Scripts\\speech-to-speech.exe" --mode realtime 'diff --git a/tests/unit/realtime/test_local_realtime.py b/tests/unit/realtime/test_local_realtime.pyindex 4be5910d9f..f725a58dc2 100644--- a/tests/unit/realtime/test_local_realtime.py+++ b/tests/unit/realtime/test_local_realtime.py@@ -236,6 +236,21 @@ async def test_a_pinned_model_skips_the_probe(fake_models) -> None:assert fake_models.last_url is None+async def test_the_managed_server_skips_its_unsupported_models_route(+ fake_models, monkeypatch+) -> None:+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setattr(supervisor, "is_managed_launch_command", lambda command: True)+ provider = LocalRealtimeProvider(+ base_url="http://localhost:8080",+ launch_command="managed-server --mode realtime",+ )++ assert await provider._resolve_model()+ assert fake_models.last_url is None++async def test_a_server_without_a_model_list_still_connects(fake_models) -> None:"""The probe is a convenience, not a gate: the connect that follows carriesthe honest failure if there is one."""@@ -391,6 +406,8 @@ def _fresh_launch_state(monkeypatch) -> list[dict[str, Any]]:from jarvis.realtime.local_server import supervisormonkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.0)monkeypatch.setattr(LocalRealtimeProvider, "_last_launch_at", float("-inf"))spawned: list[dict[str, Any]] = []@@ -417,6 +434,27 @@ def test_revive_spawns_windowless_and_rate_limited(monkeypatch, tmp_path) -> Nonassert spawned[0]["creationflags"] == NO_WINDOW_CREATIONFLAGS # AP-1+def test_transient_lifecycle_refusal_is_immediately_retryable(monkeypatch) -> None:+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setattr(LocalRealtimeProvider, "_last_launch_at", float("-inf"))+ outcomes = iter(["refused:spawn-in-progress", "spawned"])+ calls: list[str] = []+ monkeypatch.setattr(+ supervisor,+ "ensure_running",+ lambda **kwargs: calls.append(kwargs["reason"]) or next(outcomes),+ )+ provider = LocalRealtimeProvider(+ base_url="http://127.0.0.1:8765",+ launch_command="serve --mode realtime",+ )++ assert provider._maybe_launch_server() is False+ assert provider._maybe_launch_server() is True+ assert calls == ["connect-revive", "connect-revive"]++def test_revive_refuses_remote_servers(monkeypatch) -> None:"""A LAN endpoint going down must not start a second server HERE."""spawned = _fresh_launch_state(monkeypatch)@@ -611,6 +649,12 @@ async def test_warm_transport_prewarms_via_the_supervisor("ensure_running",lambda **kwargs: calls.append(f"run:{kwargs['reason']}") or "spawned",)+ monkeypatch.setattr(supervisor, "is_managed_launch_command", lambda command: True)+ monkeypatch.setattr(+ supervisor,+ "wait_until_ready",+ lambda *args, **kwargs: calls.append("ready") or True,+ )monkeypatch.setattr(supervisor, "warm_brain", lambda **kwargs: calls.append("warm") or True)@@ -618,7 +662,55 @@ async def test_warm_transport_prewarms_via_the_supervisor(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"]+ assert calls == ["run:prewarm", "ready", "warm"]+++async def test_warm_transport_never_warms_the_brain_before_speech_is_ready(+ monkeypatch, tmp_path+) -> None:+ from jarvis.realtime.local_server import supervisor++ calls: list[str] = []+ monkeypatch.setattr(supervisor, "ensure_running", lambda **kwargs: "spawned")+ monkeypatch.setattr(supervisor, "is_managed_launch_command", lambda command: True)+ monkeypatch.setattr(supervisor, "wait_until_ready", lambda *args, **kwargs: False)+ monkeypatch.setattr(+ supervisor, "warm_brain", lambda **kwargs: calls.append("warm") or True+ )+ exe = tmp_path / "server"+ exe.write_bytes(b"")+ cfg = _warm_cfg("http://127.0.0.1:8765", f'"{exe}" --model_name m')+ assert await LocalRealtimeProvider.warm_transport(cfg) is False+ assert calls == []+++async def test_byo_warm_transport_does_not_require_the_private_pool(+ monkeypatch, tmp_path+) -> None:+ from jarvis.realtime.local_server import supervisor++ calls: list[str] = []+ monkeypatch.setattr(supervisor, "ensure_running", lambda **kwargs: "already-running")+ monkeypatch.setattr(supervisor, "is_managed_launch_command", lambda command: False)++ def forbidden_wait(*args: Any, **kwargs: Any) -> bool:+ raise AssertionError("BYO servers do not promise /v1/pool")++ monkeypatch.setattr(supervisor, "wait_until_ready", forbidden_wait)+ monkeypatch.setattr(+ supervisor, "warm_brain", lambda **kwargs: calls.append("warm") or False+ )++ async def resolved_model(_provider: LocalRealtimeProvider) -> str:+ return "m"++ monkeypatch.setattr(LocalRealtimeProvider, "_resolve_model", resolved_model)+ exe = tmp_path / "server"+ exe.write_bytes(b"")+ cfg = _warm_cfg("http://127.0.0.1:8765", f'"{exe}" --model_name m')++ assert await LocalRealtimeProvider.warm_transport(cfg) is True+ assert calls == ["warm"]async def test_warm_transport_skips_a_deleted_install(monkeypatch, tmp_path) -> None:diff --git a/tests/unit/ui/web/test_managed_local_realtime_routes.py b/tests/unit/ui/web/test_managed_local_realtime_routes.pyindex 52355a2fad..c72d5ba994 100644--- a/tests/unit/ui/web/test_managed_local_realtime_routes.py+++ b/tests/unit/ui/web/test_managed_local_realtime_routes.py@@ -9,12 +9,15 @@ cards carry None.from __future__ import annotations+import threading+import pytestfrom fastapi.testclient import TestClientfrom jarvis.core.bus import EventBusfrom jarvis.core.config import JarvisConfigfrom jarvis.realtime.local_server import brain_link, install, preflight+from jarvis.ui.web import provider_routesfrom jarvis.ui.web.server import WebServer@@ -115,6 +118,9 @@ def test_status_pairs_progress_with_failclosed_probe(# The live half says what the disk cannot: nothing serves, nothing owned.assert body["runtime"] == {"reachable": False,+ "ready": False,+ "available": False,+ "pool": None,"port": 8765,"pid": None,"owned": False,@@ -147,7 +153,7 @@ def test_start_forwards_the_supervisor_refusal(assert resp.json()["detail"] == "refused:rate-limited"-def test_start_spawns_and_warms_the_brain(+def test_start_spawns_and_schedules_the_brain_warm(server: WebServer, monkeypatch: pytest.MonkeyPatch) -> None:from jarvis.core.config import BrainProviderConfig@@ -163,17 +169,86 @@ def test_start_spawns_and_warms_the_brain(lambda **kwargs: calls.append("start") or "spawned",)monkeypatch.setattr(- supervisor, "warm_brain", lambda **kwargs: calls.append("warm") or True+ provider_routes,+ "_schedule_managed_server_warm",+ lambda *args: calls.append("schedule"),)monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: True)+ monkeypatch.setattr(+ supervisor,+ "probe_runtime",+ lambda *args, **kwargs: {+ "size": 1,+ "in_use": 0,+ "available": 1,+ "stuck": 0,+ },+ )with TestClient(server.app) as client:resp = client.post("/api/providers/local-realtime/managed-server/start")assert resp.status_code == 200body = resp.json()assert body["ok"] is Trueassert body["outcome"] == "spawned"- assert calls == ["start", "warm"]+ assert calls == ["start", "schedule"]assert body["runtime"]["reachable"] is True+ assert body["runtime"]["ready"] is True+++def test_start_does_not_compete_for_gpu_while_speech_is_still_loading(+ 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: "spawned")+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: False)+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ scheduled: list[str] = []+ monkeypatch.setattr(+ provider_routes,+ "_schedule_managed_server_warm",+ lambda *args: scheduled.append("warm-worker"),+ )+ with TestClient(server.app) as client:+ resp = client.post("/api/providers/local-realtime/managed-server/start")+ assert resp.status_code == 200+ assert resp.json()["runtime"]["ready"] is False+ assert scheduled == ["warm-worker"]+++async def test_background_warm_waits_for_managed_pool_before_brain(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis.realtime.local_server import supervisor++ calls: list[tuple[str, object]] = []+ monkeypatch.setattr(supervisor, "is_managed_launch_command", lambda command: True)++ def ready(*args, **kwargs) -> bool:+ calls.append(("ready", kwargs))+ return True++ monkeypatch.setattr(supervisor, "wait_until_ready", ready)+ monkeypatch.setattr(+ supervisor,+ "warm_brain",+ lambda **kwargs: calls.append(("brain", kwargs)) or True,+ )++ await provider_routes._finish_managed_server_warm(+ "http://127.0.0.1:8765",+ "managed-server --mode realtime",+ threading.Event(),+ )++ assert [name for name, _payload in calls] == ["ready", "brain"]+ ready_kwargs = calls[0][1]+ assert isinstance(ready_kwargs, dict)+ assert ready_kwargs["cleanup_on_timeout"] is Truedef test_brain_route_rewrites_the_model_without_reinstall(@@ -245,12 +320,23 @@ def test_stop_reports_success() -> None:from jarvis.realtime.local_server import supervisor- monkeypatch.setattr(supervisor, "stop", lambda **kwargs: (True, "stopped pid 4711"))+ calls: list[str] = []++ async def cancel_warm(_request) -> None:+ calls.append("cancel")++ monkeypatch.setattr(provider_routes, "_cancel_managed_server_warm", cancel_warm)+ monkeypatch.setattr(+ supervisor,+ "stop",+ lambda **kwargs: calls.append("stop") or (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 == 200assert resp.json()["ok"] is True+ assert calls == ["cancel", "stop"]def test_uninstall_refuses_while_running(