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
feat(local-realtime): honest boot progress, crash forensics and crash-loop verdicts
rubenluetke10-beepc77aa55032b4
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex 1091d56e07..51affe297d 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1430,6 +1430,11 @@ _LOCAL_POOL_PROBE_TIMEOUT_S = 0.35#: reported unavailable" told nobody what to do (live 2026-08-09 11:50:47).#: English on purpose: these are backend strings, and the spoken failure#: sentence is localized separately by the session's language resolver.+#: The starting sentence is only the fallback: when the supervisor can see+#: the boot stage and a measured ETA, ``_local_starting_reason`` upgrades it+#: to "loading the speaking voice, about 40 seconds left" (the static+#: "about a minute" undersold a 65-second model switch, live 2026-08-10+#: 20:16:49)._LOCAL_REASON_STARTING = ("The local voice server is not answering yet — it is starting in the ""background. Try the call again in about a minute."@@ -1702,6 +1707,43 @@ class LocalRealtimeProvider:"""return self._duplex_unavailable_reason+ @staticmethod+ def _local_starting_reason(supervisor: Any) -> str:+ """The boot refusal, upgraded with the live stage and honest ETA.++ Falls back to the static sentence whenever the supervisor cannot+ prove a stage or a measured remaining time — a progress hint must+ never invent one.+ """+ try:+ boot = supervisor.boot_snapshot()+ if not isinstance(boot, dict) or not boot.get("starting"):+ return _LOCAL_REASON_STARTING+ label = boot.get("stage_label")+ remaining = boot.get("remaining_s")+ if isinstance(label, str) and label:+ if (+ isinstance(remaining, (int, float))+ and not isinstance(remaining, bool)+ and remaining > 0+ ):+ # Tens of seconds is the honest resolution of a model+ # load; a to-the-second countdown would imply precision+ # the median of five boots does not have.+ rounded = max(10, round(float(remaining) / 10.0) * 10)+ return (+ "The local voice server is starting — currently "+ f"{label}, about {rounded} seconds left. Try the "+ "call again shortly."+ )+ return (+ "The local voice server is starting — currently "+ f"{label}. Try the call again in about a minute."+ )+ except Exception: # noqa: BLE001 - a progress hint never breaks the verdict+ log.debug("local-realtime: boot progress hint failed", exc_info=True)+ return _LOCAL_REASON_STARTING+async def can_open_duplex_session(self) -> bool:self._duplex_unavailable_reason = ""if not self._base_url:@@ -1740,10 +1782,10 @@ class LocalRealtimeProvider:"local-realtime: pool capacity probe failed",exc_info=True,)- self._duplex_unavailable_reason = _LOCAL_REASON_STARTING+ self._duplex_unavailable_reason = self._local_starting_reason(supervisor)return Falseif pool is None:- self._duplex_unavailable_reason = _LOCAL_REASON_STARTING+ self._duplex_unavailable_reason = self._local_starting_reason(supervisor)return Falseif int(pool.get("available", 0)) > 0:self._duplex_unavailable_reason = ""@@ -1819,7 +1861,7 @@ class LocalRealtimeProvider:"local-realtime: managed server is still starting in the ""background; refusing to hold this call on Connecting")- self._duplex_unavailable_reason = _LOCAL_REASON_STARTING+ self._duplex_unavailable_reason = self._local_starting_reason(supervisor)return Falseasync def _resolve_model(self) -> str:diff --git a/jarvis/realtime/local_server/boot_progress.py b/jarvis/realtime/local_server/boot_progress.pynew file mode 100644index 0000000000..bd91859089--- /dev/null+++ b/jarvis/realtime/local_server/boot_progress.py@@ -0,0 +1,287 @@+"""Boot progress, boot statistics and crash forensics for the managed server.++Why this exists (live 2026-08-10 20:16): a deliberate model switch replaced a+healthy idle server, the new generation needed ~65 seconds to load its speech+models, and every call attempt inside that window failed with the static+sentence "try again in about a minute". The card showed the equally static+"Server starting — loading voice models…". Nothing told the user WHICH model+was loading or HOW LONG was actually left, and a silent native crash of the+previous generation (live 2026-08-10 18:41) left zero forensic trace because+the log tail was pure ``/v1/pool`` polling noise.++Three read-only-safe capabilities, all pure functions over explicit inputs so+they are unit-testable without a live server:++- **Stage parsing**: the pinned server logs a stable module prefix per boot+ phase (``speech_to_speech.STT.* Loading``, ``speech_to_speech.TTS.*+ Loading``, …). Matching on the MODULE rather than the model name keeps the+ parse honest across engines and tiers (Parakeet vs Whisper, Qwen3-TTS vs+ others). Lines from earlier generations in the shared append-only log are+ excluded by their timestamps.+- **Boot statistics**: recent completed boot durations (median → honest ETA)+ plus a consecutive readiness-timeout streak, persisted as one small JSON.+ Concurrent writers can race read-modify-write; the cost is one lost sample,+ never corruption (atomic replace).+- **Crash tail**: the last substantive server-log lines with the readiness+ polling noise removed, bounded, for the desktop log when the monitor sees+ the owned process exit.++This module must not import the supervisor (the supervisor imports it); every+path arrives as a parameter.+"""++from __future__ import annotations++import json+import logging+import os+import re+import time+import uuid+from pathlib import Path+from typing import TypedDict++log = logging.getLogger(__name__)+++class BootStats(TypedDict):+ """Validated shape of the persisted boot-statistics file."""++ durations_s: list[float]+ failed_streak: int+ ready_token: str+ timeout_token: str++#: How much of the shared append-only log one parse reads. Big enough to span+#: a whole boot transcript (~30 KB observed) plus call noise, small enough to+#: stay cheap on every status poll.+TAIL_READ_BYTES = 128 * 1024++#: Bounds for the crash tail that lands in the desktop log.+CRASH_TAIL_MAX_LINES = 25+CRASH_TAIL_MAX_LINE_CHARS = 300++#: How many completed boot durations feed the median ETA.+MAX_RECORDED_BOOTS = 5++#: The readiness poll requests that make a raw tail useless as forensics.+_POOL_POLL_NOISE = re.compile(r'"GET /v1/pool HTTP/1\.1" 200')++_LINE_TIMESTAMP = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")++#: Ordered boot phases. Module-prefixed patterns, never model names: the same+#: stage line must match whichever STT/TTS engine the user's tier selected.+#: ``label`` is a backend English sentence fragment (rendered verbatim by the+#: UI per the managed-card doctrine: substance from the server, chrome+#: localized).+_STAGE_MARKERS: tuple[tuple[re.Pattern[str], str, str], ...] = (+ (+ re.compile(r"speech_to_speech\.VAD\.\S+ - INFO - Load"),+ "speech-detection",+ "preparing speech detection",+ ),+ (+ re.compile(r"speech_to_speech\.STT\.\S+ - INFO - Loading"),+ "listening-model",+ "loading the listening model",+ ),+ (+ re.compile(r"speech_to_speech\.STT\.\S+ - INFO - Warming up"),+ "listening-model",+ "warming up the listening model",+ ),+ (+ re.compile(r"speech_to_speech\.LLM\.\S+ - INFO - Warming up"),+ "brain",+ "warming up the language model",+ ),+ (+ re.compile(r"speech_to_speech\.TTS\.\S+ - INFO - Loading"),+ "voice-model",+ "loading the speaking voice",+ ),+ (+ re.compile(r"speech_to_speech\.TTS\.\S+ - INFO - Warming up"),+ "voice-warmup",+ "warming up the speaking voice",+ ),+ (+ re.compile(r"speech_to_speech\.api\.\S+ - INFO - OpenAI Realtime API starting"),+ "opening",+ "opening the call endpoint",+ ),+)+++def read_log_tail(path: Path, *, max_bytes: int = TAIL_READ_BYTES) -> list[str]:+ """The last ``max_bytes`` of one log file as text lines, never raising.++ The child writes UTF-8 (``PYTHONIOENCODING`` is set at spawn); a seek into+ the middle of a multibyte character is healed by ``errors="replace"``.+ """+ try:+ with path.open("rb") as handle:+ handle.seek(0, os.SEEK_END)+ size = handle.tell()+ handle.seek(max(0, size - max(0, max_bytes)))+ raw = handle.read(max(0, max_bytes))+ except OSError:+ return []+ return raw.decode("utf-8", errors="replace").splitlines()+++def _line_epoch(line: str) -> float | None:+ """Local-time epoch of a timestamped server-log line, else ``None``."""+ match = _LINE_TIMESTAMP.match(line)+ if match is None:+ return None+ try:+ return time.mktime(time.strptime(match.group(1), "%Y-%m-%d %H:%M:%S"))+ except (OverflowError, ValueError):+ return None+++def parse_boot_stage(lines: list[str], *, spawned_at: float) -> tuple[str, str] | None:+ """``(stage_key, stage_label)`` of the newest boot marker after the spawn.++ The server log is append-only across generations, so every marker is+ gated on its line timestamp: only lines stamped at or after ``spawned_at``+ (with a small clock-skew allowance) belong to the current boot.+ Untimestamped lines (uvicorn, bare prints) inherit the verdict of the last+ timestamped line above them.+ """+ threshold = spawned_at - 5.0+ in_current_boot = False+ best: tuple[int, str, str] | None = None+ for line in lines:+ stamp = _line_epoch(line)+ if stamp is not None:+ in_current_boot = stamp >= threshold+ if not in_current_boot:+ continue+ for ordinal, (pattern, key, label) in enumerate(_STAGE_MARKERS):+ if pattern.search(line) and (best is None or ordinal >= best[0]):+ best = (ordinal, key, label)+ if best is None:+ return None+ return best[1], best[2]+++def crash_tail(lines: list[str]) -> list[str]:+ """The substantive end of the server log, bounded for the desktop log.++ Readiness polling produces hundreds of identical ``GET /v1/pool`` lines+ that would drown the one traceback worth keeping (a real crashed+ generation's tail was 100% polling noise, live 2026-08-10 18:41).+ """+ kept = [+ line[:CRASH_TAIL_MAX_LINE_CHARS]+ for line in lines+ if line.strip() and _POOL_POLL_NOISE.search(line) is None+ ]+ return kept[-CRASH_TAIL_MAX_LINES:]+++# ── Boot statistics ──────────────────────────────────────────────────────+++def _atomic_write_json(path: Path, payload: dict[str, object]) -> bool:+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8")+ os.replace(temporary, path)+ return True+ except OSError:+ log.debug("boot stats: atomic write failed", exc_info=True)+ return False+ finally:+ try:+ temporary.unlink(missing_ok=True)+ except OSError:+ log.debug("boot stats: temporary cleanup failed", exc_info=True)+++def load_stats(path: Path) -> BootStats:+ """The persisted boot statistics, empty-but-valid when absent/corrupt."""+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ data = None+ if not isinstance(data, dict):+ data = {}+ durations = data.get("durations_s")+ cleaned: list[float] = []+ if isinstance(durations, list):+ for value in durations:+ if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:+ cleaned.append(float(value))+ streak = data.get("failed_streak")+ if isinstance(streak, bool) or not isinstance(streak, int) or streak < 0:+ streak = 0+ ready_token = data.get("ready_token")+ timeout_token = data.get("timeout_token")+ return {+ "durations_s": cleaned[-MAX_RECORDED_BOOTS:],+ "failed_streak": streak,+ "ready_token": ready_token if isinstance(ready_token, str) else "",+ "timeout_token": timeout_token if isinstance(timeout_token, str) else "",+ }+++def expected_boot_s(stats: BootStats) -> float | None:+ """Median of the recorded boot durations; ``None`` without history."""+ durations = stats["durations_s"]+ if not durations:+ return None+ ordered = sorted(durations)+ middle = len(ordered) // 2+ if len(ordered) % 2:+ return ordered[middle]+ return (ordered[middle - 1] + ordered[middle]) / 2.0+++def record_ready(path: Path, *, token: str, duration_s: float) -> bool:+ """Record one completed boot exactly once per spawn generation.++ Also clears the consecutive-failure streak: a server that just proved it+ can boot is not crash-looping. Returns ``False`` when this generation was+ already recorded (idempotent — status polls, the monitor and the warm+ task all race to be the first observer).+ """+ if not token or duration_s <= 0:+ return False+ stats = load_stats(path)+ if stats["ready_token"] == token:+ return False+ durations = list(stats["durations_s"])+ durations.append(round(float(duration_s), 1))+ return _atomic_write_json(+ path,+ {+ "durations_s": durations[-MAX_RECORDED_BOOTS:],+ "failed_streak": 0,+ "ready_token": token,+ "timeout_token": stats["timeout_token"],+ "updated_at": time.time(),+ },+ )+++def record_timeout(path: Path, *, token: str) -> bool:+ """Count one readiness timeout, once per spawn generation."""+ if not token:+ return False+ stats = load_stats(path)+ if stats["timeout_token"] == token:+ return False+ return _atomic_write_json(+ path,+ {+ "durations_s": stats["durations_s"],+ "failed_streak": stats["failed_streak"] + 1,+ "ready_token": stats["ready_token"],+ "timeout_token": token,+ "updated_at": time.time(),+ },+ )diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.pyindex a5b1493ae8..ebc6d5b809 100644--- a/jarvis/realtime/local_server/supervisor.py+++ b/jarvis/realtime/local_server/supervisor.py@@ -92,9 +92,7 @@ _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-)+_WINDOWS_BREAKAWAY_FROM_JOB = getattr(subprocess, "CREATE_BREAKAWAY_FROM_JOB", 0x01000000)_LOCK = threading.Lock()_last_spawn_at: float = float("-inf")@@ -128,6 +126,10 @@ def _spawn_lock() -> Path:return _data_dir() / "local_realtime_server.spawn.lock"+def _boot_stats() -> Path:+ return _data_dir() / "local_realtime_server.boot.json"++# ── Address handling ─────────────────────────────────────────────────────@@ -205,9 +207,7 @@ def probe_runtime(base_url: str, timeout: float = 0.75) -> dict[str, int] | Noneif target_host is None:return Noneconnection_type = (- http.client.HTTPSConnection- if target.scheme == "https"- else http.client.HTTPConnection+ http.client.HTTPSConnection if target.scheme == "https" else http.client.HTTPConnection)connection = connection_type(target_host,@@ -301,6 +301,7 @@ def wait_until_ready(if cancel_event is not None and cancel_event.is_set():return Falseif probe_runtime(base_url, timeout=min(0.75, max(0.05, timeout))) is not None:+ _record_boot_ready_once()return Trueremaining = deadline - time.monotonic()if remaining <= 0:@@ -595,6 +596,122 @@ def hardened_child_env(*, inject_openai_key: bool) -> dict[str, str]:return env+# ── Boot progress ────────────────────────────────────────────────────────+++def _record_boot_ready_once() -> None:+ """Persist the just-observed boot completion, once per spawn generation.++ Callers race to be the first observer (status polls, the readiness+ waiter, the monitor revive); the per-token guard in the stats file makes+ every observation after the first a no-op. The duration sanity bound+ keeps a long-running server's status polls from recording hours as a+ "boot".+ """+ try:+ record = _read_pidfile() or {}+ token = record.get("spawn_token")+ spawned_at = _json_float(record.get("spawned_at"))+ if not isinstance(token, str) or not token or spawned_at is None:+ return+ duration = time.time() - spawned_at+ if not 0 < duration <= RUNTIME_READY_TIMEOUT_S + 60.0:+ return+ from jarvis.realtime.local_server import boot_progress # lazy (AP-26)++ boot_progress.record_ready(_boot_stats(), token=token, duration_s=duration)+ except Exception: # noqa: BLE001 - statistics must never break readiness+ log.debug("supervisor: boot-duration record failed", exc_info=True)+++def _record_boot_timeout(token: str) -> None:+ """Count one readiness timeout toward the consecutive-failure streak."""+ try:+ from jarvis.realtime.local_server import boot_progress # lazy (AP-26)++ boot_progress.record_timeout(_boot_stats(), token=token)+ except Exception: # noqa: BLE001 - statistics must never break cleanup+ log.debug("supervisor: boot-timeout record failed", exc_info=True)+++def _boot_status(*, booting: bool) -> dict[str, object]:+ """The boot sub-verdict of :func:`status`, safe on every failure path."""+ from jarvis.realtime.local_server import boot_progress # lazy (AP-26)++ stats = boot_progress.load_stats(_boot_stats())+ payload: dict[str, object] = {+ "failed_streak": stats["failed_streak"],+ "starting": False,+ }+ if not booting:+ return payload+ record = _read_pidfile() or {}+ spawned_at = _json_float(record.get("spawned_at"))+ if spawned_at is None:+ return payload+ elapsed = max(0.0, time.time() - spawned_at)+ stage = boot_progress.parse_boot_stage(+ boot_progress.read_log_tail(_server_log()), spawned_at=spawned_at+ )+ expected = boot_progress.expected_boot_s(stats)+ remaining: float | None = None+ # Past twice the historical boot time the countdown would be a lie;+ # showing only the stage is the honest degradation.+ if expected is not None and elapsed <= 2.0 * expected:+ remaining = max(5.0, expected - elapsed)+ payload.update(+ {+ "starting": True,+ "stage": stage[0] if stage else None,+ "stage_label": stage[1] if stage else None,+ "elapsed_s": round(elapsed, 1),+ "expected_total_s": expected,+ "remaining_s": round(remaining) if remaining is not None else None,+ }+ )+ return payload+++def boot_snapshot() -> dict[str, object]:+ """Live boot progress of the owned child, for user-facing refusals.++ Lighter than :func:`status`: no port or pool probe — the caller already+ holds a "not ready" verdict and only needs the stage and the honest ETA.+ """+ try:+ _pid, alive = _owned_process()+ return _boot_status(booting=alive)+ except Exception: # noqa: BLE001 - a progress hint never breaks a verdict+ log.debug("supervisor: boot snapshot failed", exc_info=True)+ return {"failed_streak": 0, "starting": False}+++def _log_crash_tail() -> None:+ """One bounded forensic tail when the owned server exits unexpectedly.++ A silently dying native child (live 2026-08-10 18:41) previously left+ nothing but readiness-poll noise; whatever the server managed to say+ last belongs in the desktop log next to the recovery decision.+ """+ try:+ from jarvis.realtime.local_server import boot_progress # lazy (AP-26)++ tail = boot_progress.crash_tail(boot_progress.read_log_tail(_server_log()))+ if tail:+ log.warning(+ "local-realtime monitor: owned server process exited "+ "unexpectedly; last server-log lines:\n%s",+ "\n".join(tail),+ )+ else:+ log.warning(+ "local-realtime monitor: owned server process exited "+ "unexpectedly and left no substantive log tail"+ )+ except Exception: # noqa: BLE001 - forensics must never break recovery+ log.debug("supervisor: crash-tail capture failed", exc_info=True)++# ── Status ───────────────────────────────────────────────────────────────@@ -604,6 +721,10 @@ def status(base_url: str = "") -> dict[str, object]: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 None+ if pool is not None and alive:+ # The UI polls this while the card is open, which makes it the most+ # reliable first observer of a completed boot (token-guarded).+ _record_boot_ready_once()return {"reachable": reachable,"ready": pool is not None,@@ -613,6 +734,7 @@ def status(base_url: str = "") -> dict[str, object]:"pid": pid,"owned": alive,"stale": pid is not None and not alive,+ "boot": _boot_status(booting=alive and pool is None),}@@ -881,36 +1003,26 @@ def ensure_running(_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- )+ owned_root = managed_install_root(owned_command) if owned_command is not None else Noneunsafe_bind = bool(owned_command and not _uses_loopback_bind(owned_command))slow_ollama_backend = bool(owned_command and _needs_ollama_backend_migration(owned_command))unstable_turn_detection = bool(- owned_command- and _needs_stable_turn_detection_migration(owned_command)+ owned_command and _needs_stable_turn_detection_migration(owned_command))latency_migration = slow_ollama_backend or unstable_turn_detectionif (latency_migrationand not unsafe_bind- and (- pool is None- or pool.get("active", pool["in_use"]) > 0- )+ and (pool is None or pool.get("active", pool["in_use"]) > 0)):# Latency migration is never a reason to terminate somebody's# live call or a generation whose state cannot be proven. The# next verified-idle connect can replace this generation.return "already-running"if owned_root is not None and (- unsafe_bind- or (- latency_migration- and replace_unavailable_generation is None- )+ unsafe_bind or (latency_migration and replace_unavailable_generation is None)):# Managed servers survive app exits, so an upgrade can inherit# a healthy legacy generation. Only a verified owned process@@ -1130,11 +1242,7 @@ def _server_creationflags(*, platform_name: str | None = None) -> int:platform = os.name if platform_name is None else platform_nameif platform != "nt":return NO_WINDOW_CREATIONFLAGS- return (- _WINDOWS_NO_WINDOW- | _WINDOWS_DETACHED_PROCESS- | _WINDOWS_BREAKAWAY_FROM_JOB- )+ return _WINDOWS_NO_WINDOW | _WINDOWS_DETACHED_PROCESS | _WINDOWS_BREAKAWAY_FROM_JOBdef _spawn(command: str, *, reason: str) -> int | None:@@ -1238,11 +1346,7 @@ def start_runtime_monitor(*, launch_command: str, base_url: str) -> bool:global _monitor_thread, _monitor_stop, _monitor_keywith _MONITOR_LOCK:- if (- _monitor_thread is not None- and _monitor_thread.is_alive()- and _monitor_key == key- ):+ if _monitor_thread is not None and _monitor_thread.is_alive() and _monitor_key == key:return Falseif _monitor_stop is not None:_monitor_stop.set()@@ -1314,12 +1418,20 @@ def _runtime_monitor(unready_since: float | None = Noneunhealthy_kind = ""last_outcome = ""+ # The monitor only arms on a verified ready server, so the first+ # alive→gone transition it sees is a genuine unexpected exit.+ was_alive = Truetry:while not stop_event.wait(RUNTIME_MONITOR_POLL_S):try:if managed_install_root(launch_command) is None:return_pid, alive = _owned_process()+ if alive:+ was_alive = True+ elif was_alive:+ was_alive = False+ _log_crash_tail()if not alive:# A healthy listener without our ownership is foreign. Do# not fight it or keep trying to adopt it.@@ -1339,9 +1451,7 @@ def _runtime_monitor(log.info("local-realtime monitor: crashed runtime recovered")unready_since = Noneunhealthy_kind = ""- next_pool_probe = (- time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S- )+ next_pool_probe = time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_Selif outcome != last_outcome:log.warning("local-realtime monitor: crash recovery deferred (%s)",@@ -1390,8 +1500,7 @@ def _runtime_monitor(outcome = "refused:unverified-generation"if outcome != last_outcome:log.warning(- "local-realtime monitor: unavailable recovery "- "deferred (%s)",+ "local-realtime monitor: unavailable recovery deferred (%s)",outcome,)last_outcome = outcome@@ -1407,9 +1516,7 @@ def _runtime_monitor(log.info("local-realtime monitor: wedged runtime recovered")unready_since = Noneunhealthy_kind = ""- next_pool_probe = (- time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S- )+ next_pool_probe = time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_Selif outcome != last_outcome:log.warning("local-realtime monitor: unready recovery deferred (%s)",@@ -1470,9 +1577,7 @@ def _stop_owned_unlocked(# 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)- )+ swept, survivors = _kill_by_install_root(install_root) if install_root is not None else (0, 0)if survivors:if owner_stopped:clear_pidfile()@@ -1512,6 +1617,10 @@ def _cleanup_timed_out_generation(owned_only=True,install_root=install_root,)+ # Whatever the stop outcome, this generation provably never became+ # ready inside its whole budget — that is the crash-loop signal the+ # provider card surfaces after repeated failures.+ _record_boot_timeout(expected_generation[2])return ("completed" if changed else "failed"), message@@ -1819,9 +1928,7 @@ def warm_brain(*, launch_command: str, timeout: float = 5.0) -> bool:return True-def prepare_voice_brain_command(- launch_command: str, *, timeout: float = 30.0-) -> str:+def prepare_voice_brain_command(launch_command: str, *, timeout: float = 30.0) -> str:"""Return a managed-server command using a bounded Ollama context profile.Ollama documents that its OpenAI-compatible API has no context-size field;@@ -1865,8 +1972,7 @@ def prepare_voice_brain_command() from exc_prepared_voice_models.add(cache_key)log.info(- "local-realtime supervisor: prepared bounded Ollama model %s "- "from %s (num_ctx=%s)",+ "local-realtime supervisor: prepared bounded Ollama model %s from %s (num_ctx=%s)",voice_model,source_model,VOICE_BRAIN_CONTEXT_TOKENS,@@ -1911,10 +2017,7 @@ def _effective_owned_launch_command(configured_command: str) -> str:if configured_root is None:return configured_commandactive_command = _verified_owned_command()- if (- active_command is not None- and managed_install_root(active_command) == configured_root- ):+ if active_command is not None and managed_install_root(active_command) == configured_root:return active_commandreturn configured_commanddiff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsxindex f087fab7fb..dddc5ca1de 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx@@ -1197,4 +1197,26 @@ describe("managed server badge", () => {managedRuntimeBadge(runtime({ reachable: false, owned: false }), false)?.key,).toBe("apikeys_view.managed_server_stopped");});++ it("names a crash loop instead of hiding it behind 'stopped'", () => {+ // Live 2026-08-09: four consecutive readiness timeouts read as a quiet+ // muted badge; two burned five-minute boot budgets deserve a warning.+ const looping = runtime({+ reachable: false,+ owned: false,+ boot: { failed_streak: 2, starting: false },+ });+ const badge = managedRuntimeBadge(looping, true);+ expect(badge?.key).toBe("apikeys_view.managed_server_crash_loop");+ expect(badge?.tone).toBe("warn");+ // One failure is still normal churn, not a loop.+ const single = runtime({+ reachable: false,+ owned: false,+ boot: { failed_streak: 1, starting: false },+ });+ expect(managedRuntimeBadge(single, true)?.key).toBe(+ "apikeys_view.managed_server_stopped",+ );+ });});diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex 3cbad789c5..ab0a680301 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -1945,9 +1945,17 @@ export function managedRuntimeBadge(if (runtime.reachable) {return { key: "apikeys_view.managed_server_port_conflict", tone: "warn" };}- return runtime.owned- ? { key: "apikeys_view.managed_server_starting", tone: "warn" }- : { key: "apikeys_view.managed_server_stopped", tone: "muted" };+ if (runtime.owned) {+ return { key: "apikeys_view.managed_server_starting", tone: "warn" };+ }+ // Two consecutive readiness timeouts mean whole five-minute boot budgets+ // burned with nothing to show — "Server stopped" would hide a crash loop+ // behind the same muted badge as a deliberate stop (live 2026-08-09, four+ // reaped generations in forty minutes read as an endless quiet "starting").+ if ((runtime.boot?.failed_streak ?? 0) >= 2) {+ return { key: "apikeys_view.managed_server_crash_loop", tone: "warn" };+ }+ return { key: "apikeys_view.managed_server_stopped", tone: "muted" };}/**@@ -2302,6 +2310,26 @@ function ManagedServerPanel({>{t(runtimeBadge.key)}</span>+ {runtimeBadge.key === "apikeys_view.managed_server_starting" &&+ runtime?.boot?.starting &&+ runtime.boot.stage_label && (+ <span className="text-muted-foreground">+ {typeof runtime.boot.remaining_s === "number" &&+ runtime.boot.remaining_s > 0+ ? `${runtime.boot.stage_label} · ${t(+ "apikeys_view.managed_server_starting_eta",+ ).replace(+ "{0}",+ String(+ Math.max(+ 10,+ Math.round(runtime.boot.remaining_s / 10) * 10,+ ),+ ),+ )}`+ : runtime.boot.stage_label}+ </span>+ )}{runtime && !runtime.reachable && !runtime.owned && (<Buttonsize="sm"diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 500c6ebc07..ec4cc810b1 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -857,6 +857,21 @@ export interface ManagedServerRuntime {owned: boolean;/** A pidfile exists but its process is gone. */stale: boolean;+ /**+ * Live boot verdict while an owned child loads its models, plus the+ * consecutive readiness-timeout streak that survives a reaped child.+ * `stage_label` is a backend English sentence fragment rendered verbatim+ * (managed-card doctrine: substance from the server, chrome localized).+ */+ boot?: {+ failed_streak?: number;+ starting?: boolean;+ stage?: string | null;+ stage_label?: string | null;+ elapsed_s?: number;+ expected_total_s?: number | null;+ remaining_s?: number | null;+ } | null;}/** Honest go/no-go report for the one-click managed install. */diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex aa95f0b610..cb0b3fab9b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1181,6 +1181,8 @@"managed_server_running": "Server läuft","managed_server_stopped": "Server gestoppt","managed_server_starting": "Server startet — Sprachmodelle werden geladen…",+ "managed_server_starting_eta": "noch etwa {0} s",+ "managed_server_crash_loop": "Server startet wiederholt nicht — bitte das Server-Log prüfen","managed_server_port_conflict": "Ein anderer Prozess belegt diesen Port","managed_server_no_capacity": "Server antwortet, hat aber keine freie Sprach-Pipeline","managed_start_cta": "Server starten",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 04fdbd0176..d59b6d73b3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1181,6 +1181,8 @@"managed_server_running": "Server running","managed_server_stopped": "Server stopped","managed_server_starting": "Server starting — loading voice models…",+ "managed_server_starting_eta": "about {0} s left",+ "managed_server_crash_loop": "Server keeps failing to start — check the server log","managed_server_port_conflict": "Another process is serving this port","managed_server_no_capacity": "Server answers but has no free voice pipeline","managed_start_cta": "Start server",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 4e3f69abc4..70ad0b9b97 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1181,6 +1181,8 @@"managed_server_running": "Servidor en marcha","managed_server_stopped": "Servidor detenido","managed_server_starting": "Servidor iniciándose — cargando los modelos de voz…",+ "managed_server_starting_eta": "quedan unos {0} s",+ "managed_server_crash_loop": "El servidor no consigue arrancar — revisa el registro del servidor","managed_server_port_conflict": "Otro proceso está sirviendo en este puerto","managed_server_no_capacity": "El servidor responde pero no tiene ninguna canalización de voz libre","managed_start_cta": "Iniciar servidor",diff --git a/tests/unit/realtime/local_server/test_boot_progress.py b/tests/unit/realtime/local_server/test_boot_progress.pynew file mode 100644index 0000000000..15b9e2a10a--- /dev/null+++ b/tests/unit/realtime/local_server/test_boot_progress.py@@ -0,0 +1,179 @@+"""Boot-stage parsing, boot statistics and crash-tail forensics.++The log fixtures are verbatim lines from a real managed-server boot+(2026-08-10 20:16 — the model switch whose 65-second window produced the+static "about a minute" toast this module exists to replace).+"""++from __future__ import annotations++import time+from pathlib import Path++from jarvis.realtime.local_server import boot_progress+++def _epoch(stamp: str) -> float:+ return time.mktime(time.strptime(stamp, "%Y-%m-%d %H:%M:%S"))+++_BOOT_LINES = [+ "DeepFilterNet not available for audio enhancement: No module named 'df'",+ "2026-08-10 20:17:07,702 - speech_to_speech.VAD.smart_turn - INFO - Loaded Smart Turn v3.2",+ (+ "2026-08-10 20:17:08,010 - speech_to_speech.STT.parakeet_tdt_handler - INFO - "+ "Loading Parakeet TDT model: nvidia/parakeet-tdt-0.6b-v3 on cpu"+ ),+ (+ "2026-08-10 20:17:22,921 - speech_to_speech.STT.parakeet_tdt_handler - INFO - "+ "Warming up ParakeetTDTSTTHandler"+ ),+ (+ "2026-08-10 20:17:23,568 - speech_to_speech.LLM.chat_completions_language_model - "+ "INFO - Warming up ChatCompletionsApiModelHandler"+ ),+ (+ "2026-08-10 20:17:25,797 - speech_to_speech.TTS.qwen3_tts_handler - INFO - "+ "Loading Qwen3-TTS model: Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice"+ ),+ # Verbatim localized OS noise from a real boot on a German Windows host —+ # the parser must ignore it, so the fixture keeps it. (i18n-allow)+ 'Der Befehl "sox" ist entweder falsch geschrieben oder', # i18n-allow+ (+ "2026-08-10 20:17:36,489 - speech_to_speech.TTS.qwen3_tts_handler - INFO - "+ "Warming up Qwen3TTSHandler"+ ),+ (+ "2026-08-10 20:17:47,589 - speech_to_speech.api.openai_realtime.server - INFO - "+ "OpenAI Realtime API starting on ws://127.0.0.1:8765/v1/realtime (pool size 1)"+ ),+]+++class TestParseBootStage:+ def test_reports_the_newest_marker_of_the_current_boot(self) -> None:+ spawned_at = _epoch("2026-08-10 20:16:42")+ for upto, expected in [+ (3, ("listening-model", "loading the listening model")),+ (4, ("listening-model", "warming up the listening model")),+ (5, ("brain", "warming up the language model")),+ (6, ("voice-model", "loading the speaking voice")),+ (8, ("voice-warmup", "warming up the speaking voice")),+ (9, ("opening", "opening the call endpoint")),+ ]:+ assert (+ boot_progress.parse_boot_stage(_BOOT_LINES[:upto], spawned_at=spawned_at)+ == expected+ )++ def test_earlier_generations_in_the_shared_log_are_invisible(self) -> None:+ # The append-only log still carries yesterday's full boot; a parse for+ # a child spawned AFTER those lines must not claim their progress.+ spawned_at = _epoch("2026-08-11 09:00:00")+ assert boot_progress.parse_boot_stage(_BOOT_LINES, spawned_at=spawned_at) is None++ def test_model_names_never_matter_only_the_module_prefix(self) -> None:+ # A different tier ships Whisper + another TTS; the module prefixes+ # are the stable contract.+ lines = [+ (+ "2026-08-10 20:17:08,010 - speech_to_speech.STT.whisper_handler - INFO - "+ "Loading Whisper large-v3 on cuda"+ )+ ]+ spawned_at = _epoch("2026-08-10 20:16:42")+ assert boot_progress.parse_boot_stage(lines, spawned_at=spawned_at) == (+ "listening-model",+ "loading the listening model",+ )++ def test_call_traffic_lines_are_not_boot_markers(self) -> None:+ lines = [+ (+ "2026-08-10 20:18:24,558 - [pipeline 0] speech_to_speech.STT."+ "parakeet_tdt_handler - INFO - Parakeet final STT start turn=turn_1"+ ),+ 'INFO: 127.0.0.1:50085 - "GET /v1/pool HTTP/1.1" 200 OK',+ ]+ spawned_at = _epoch("2026-08-10 20:16:42")+ assert boot_progress.parse_boot_stage(lines, spawned_at=spawned_at) is None+++class TestReadLogTail:+ def test_reads_only_the_requested_tail(self, tmp_path: Path) -> None:+ log_file = tmp_path / "server.log"+ log_file.write_text("first\n" + "x" * 100 + "\nlast line\n", encoding="utf-8")+ lines = boot_progress.read_log_tail(log_file, max_bytes=12)+ assert lines[-1] == "last line"+ assert "first" not in lines++ def test_missing_file_is_an_empty_tail_not_an_error(self, tmp_path: Path) -> None:+ assert boot_progress.read_log_tail(tmp_path / "absent.log") == []+++class TestCrashTail:+ def test_polling_noise_and_blank_lines_are_dropped(self) -> None:+ lines = [+ "2026-08-10 18:37:25,279 - ... - INFO - Pipeline 0 released",+ 'INFO: 127.0.0.1:57496 - "GET /v1/pool HTTP/1.1" 200 OK',+ "",+ 'INFO: 127.0.0.1:57504 - "GET /v1/pool HTTP/1.1" 200 OK',+ "Windows fatal exception: access violation",+ ]+ tail = boot_progress.crash_tail(lines)+ assert tail == [+ "2026-08-10 18:37:25,279 - ... - INFO - Pipeline 0 released",+ "Windows fatal exception: access violation",+ ]++ def test_output_is_bounded_in_lines_and_line_length(self) -> None:+ lines = [f"line {index} " + "y" * 1000 for index in range(200)]+ tail = boot_progress.crash_tail(lines)+ assert len(tail) == boot_progress.CRASH_TAIL_MAX_LINES+ assert all(len(line) <= boot_progress.CRASH_TAIL_MAX_LINE_CHARS for line in tail)+++class TestBootStats:+ def test_ready_is_recorded_once_per_generation_and_resets_the_streak(+ self, tmp_path: Path+ ) -> None:+ stats_file = tmp_path / "boot.json"+ generation_a, generation_b = "gen-a", "gen-b"+ assert boot_progress.record_timeout(stats_file, token=generation_a)+ assert boot_progress.load_stats(stats_file)["failed_streak"] == 1++ assert boot_progress.record_ready(stats_file, token=generation_b, duration_s=65.2)+ # The same generation observed again (status poll race) is a no-op.+ assert not boot_progress.record_ready(stats_file, token=generation_b, duration_s=120.0)+ stats = boot_progress.load_stats(stats_file)+ assert stats["durations_s"] == [65.2]+ assert stats["failed_streak"] == 0++ def test_timeout_streak_counts_distinct_generations_only(self, tmp_path: Path) -> None:+ stats_file = tmp_path / "boot.json"+ generation_a, generation_b = "gen-a", "gen-b"+ assert boot_progress.record_timeout(stats_file, token=generation_a)+ assert not boot_progress.record_timeout(stats_file, token=generation_a)+ assert boot_progress.record_timeout(stats_file, token=generation_b)+ assert boot_progress.load_stats(stats_file)["failed_streak"] == 2++ def test_expected_boot_is_the_median_of_recent_boots(self, tmp_path: Path) -> None:+ stats_file = tmp_path / "boot.json"+ assert boot_progress.expected_boot_s(boot_progress.load_stats(stats_file)) is None+ for index, duration in enumerate([60.0, 90.0, 70.0]):+ boot_progress.record_ready(stats_file, token=f"gen-{index}", duration_s=duration)+ assert boot_progress.expected_boot_s(boot_progress.load_stats(stats_file)) == 70.0++ def test_history_is_bounded_to_the_recent_boots(self, tmp_path: Path) -> None:+ stats_file = tmp_path / "boot.json"+ for index in range(boot_progress.MAX_RECORDED_BOOTS + 3):+ boot_progress.record_ready(stats_file, token=f"gen-{index}", duration_s=60.0 + index)+ stats = boot_progress.load_stats(stats_file)+ assert len(stats["durations_s"]) == boot_progress.MAX_RECORDED_BOOTS # type: ignore[arg-type]++ def test_corrupt_stats_degrade_to_empty_defaults(self, tmp_path: Path) -> None:+ stats_file = tmp_path / "boot.json"+ stats_file.write_text('{"durations_s": ["nan", -3, true], "failed_streak": -1}')+ stats = boot_progress.load_stats(stats_file)+ assert stats["durations_s"] == []+ assert stats["failed_streak"] == 0diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.pyindex f10eebd232..3ccc82d8c0 100644--- a/tests/unit/realtime/local_server/test_supervisor.py+++ b/tests/unit/realtime/local_server/test_supervisor.py@@ -50,9 +50,7 @@ def _spawn_ready(monkeypatch, tmp_path: Path) -> list[dict[str, Any]]:return spawned-def test_model_switch_never_interrupts_an_active_voice_call(- monkeypatch, tmp_path-) -> None:+def test_model_switch_never_interrupts_an_active_voice_call(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import installmonkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))@@ -73,12 +71,15 @@ def test_model_switch_never_interrupts_an_active_voice_call(lambda **kwargs: pytest.fail("an active call must not be stopped"),)- assert supervisor.replace_idle_managed_runtime(- current_command=command,- launch_command=f"{command} --model_name qwen3.5:4b",- base_url="http://127.0.0.1:8765",- reason="test-switch",- ) == "refused:call-active"+ assert (+ supervisor.replace_idle_managed_runtime(+ current_command=command,+ launch_command=f"{command} --model_name qwen3.5:4b",+ base_url="http://127.0.0.1:8765",+ reason="test-switch",+ )+ == "refused:call-active"+ )# ── Address parsing ──────────────────────────────────────────────────────@@ -121,6 +122,7 @@ def test_runtime_probe_requires_a_valid_loaded_pool(monkeypatch) -> None:{"index": 3, "state": "stuck", "session_id": "private"},],}+class _Connection:def __init__(self, *args: Any, **kwargs: Any) -> None:pass@@ -202,10 +204,10 @@ def test_managed_readiness_timeout_cleans_up_the_zombie(monkeypatch, tmp_path) -monkeypatch.setattr(supervisor,"_cleanup_timed_out_generation",- lambda **kwargs: cleaned.append(- (kwargs["install_root"], kwargs["expected_generation"])- )- or ("completed", "stopped pid 4711"),+ lambda **kwargs: (+ cleaned.append((kwargs["install_root"], kwargs["expected_generation"]))+ or ("completed", "stopped pid 4711")+ ),)assert not supervisor.wait_until_ready(@@ -333,9 +335,7 @@ def test_an_alive_owned_process_is_not_double_spawned(monkeypatch, tmp_path) ->assert outcome == "already-running"-def test_slow_managed_cold_start_survives_beyond_interactive_budget(- monkeypatch, tmp_path-) -> None:+def test_slow_managed_cold_start_survives_beyond_interactive_budget(monkeypatch, tmp_path) -> None:"""A healthy cold boot observed at 122 s must not be mistaken for a zombie."""from jarvis.realtime.local_server import install@@ -379,9 +379,7 @@ def test_slow_managed_cold_start_survives_beyond_interactive_budget(assert outcome == "already-running"-def test_an_owned_managed_zombie_is_replaced_after_startup_deadline(- monkeypatch, tmp_path-) -> None:+def test_an_owned_managed_zombie_is_replaced_after_startup_deadline(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import installsupervisor._reset_for_tests()@@ -403,9 +401,7 @@ def test_an_owned_managed_zombie_is_replaced_after_startup_deadline(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_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(@@ -426,9 +422,7 @@ def test_an_owned_managed_zombie_is_replaced_after_startup_deadline(assert spawned and "--ws_host 127.0.0.1" in spawned[0]-def test_managed_spawn_uses_the_bounded_voice_brain_command(- monkeypatch, tmp_path-) -> None:+def test_managed_spawn_uses_the_bounded_voice_brain_command(monkeypatch, tmp_path) -> None:"""The resource-safe profile must reach Popen, not just a helper test."""from jarvis.realtime.local_server import install@@ -469,9 +463,7 @@ def test_a_running_install_blocks_the_spawn(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import install_spawn_ready(monkeypatch, tmp_path)- monkeypatch.setattr(- install, "snapshot", lambda: {"running": True, "phase": "deps"}- )+ monkeypatch.setattr(install, "snapshot", lambda: {"running": True, "phase": "deps"})entrypoint = install.install_root() / "venv" / "server.exe"outcome = supervisor.ensure_running(launch_command=f'"{entrypoint}" --mode realtime',@@ -601,9 +593,7 @@ def test_spawn_is_windowless_and_records_ownership(monkeypatch, tmp_path) -> Nonassert creationflags & supervisor._WINDOWS_BREAKAWAY_FROM_JOBelse:assert creationflags == 0- record = json.loads(- (tmp_path / "local_realtime_server.pid.json").read_text(encoding="utf-8")- )+ record = json.loads((tmp_path / "local_realtime_server.pid.json").read_text(encoding="utf-8"))assert record["pid"] == 4711assert record["port"] == 8765assert record["command"] == "serve --flag"@@ -840,9 +830,7 @@ def test_a_ready_owned_legacy_ollama_backend_is_migrated(monkeypatch, tmp_path)assert "--responses_api_reasoning_effort none" in spawned[0]-def test_ollama_backend_migration_never_interrupts_an_active_call(- monkeypatch, tmp_path-) -> None:+def test_ollama_backend_migration_never_interrupts_an_active_call(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import installmonkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))@@ -889,9 +877,7 @@ def test_ollama_backend_migration_never_interrupts_an_active_call()-def test_ollama_backend_migration_defers_when_pool_state_is_unknown(- monkeypatch, tmp_path-) -> None:+def test_ollama_backend_migration_defers_when_pool_state_is_unknown(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import installmonkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))@@ -977,9 +963,7 @@ def test_a_ready_owned_loopback_bind_is_not_restarted(monkeypatch, tmp_path) ->)-def test_an_abandoned_owned_pool_is_replaced_generation_safely(- monkeypatch, tmp_path-) -> None:+def test_an_abandoned_owned_pool_is_replaced_generation_safely(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import installsupervisor._reset_for_tests()@@ -1029,9 +1013,7 @@ def test_an_abandoned_owned_pool_is_replaced_generation_safely(assert spawned == [supervisor._force_stable_turn_detection(command)]-def test_unavailable_pool_replacement_skips_a_newer_generation(- monkeypatch, tmp_path-) -> None:+def test_unavailable_pool_replacement_skips_a_newer_generation(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import installroot = tmp_path / "local_realtime"@@ -1293,9 +1275,7 @@ def test_spawn_retries_without_breakaway_when_the_host_job_forbids_it(assert attempts == [flags, flags & ~supervisor._WINDOWS_BREAKAWAY_FROM_JOB]-def test_runtime_monitor_restarts_and_rewarms_a_dead_owned_server(- monkeypatch, tmp_path-) -> None:+def test_runtime_monitor_restarts_and_rewarms_a_dead_owned_server(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import installmonkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))@@ -1333,9 +1313,7 @@ def test_runtime_monitor_restarts_and_rewarms_a_dead_owned_server(assert calls == ["ensure:watchdog-exit", "ready", "marker", "brain"]-def test_runtime_monitor_replaces_an_abandoned_pool_after_the_grace(- monkeypatch, tmp_path-) -> None:+def test_runtime_monitor_replaces_an_abandoned_pool_after_the_grace(monkeypatch, tmp_path) -> None:root = tmp_path / "local_realtime"command = f'"{root / "server.exe"}" --mode realtime'generation = (4711, 1000.0, "generation-a")@@ -1376,9 +1354,7 @@ def test_runtime_monitor_replaces_an_abandoned_pool_after_the_grace(assert revives[0]["unavailable_generation"] == generation-def test_runtime_monitor_does_not_replace_a_connected_full_pool(- monkeypatch, tmp_path-) -> None:+def test_runtime_monitor_does_not_replace_a_connected_full_pool(monkeypatch, tmp_path) -> None:root = tmp_path / "local_realtime"command = f'"{root / "server.exe"}" --mode realtime'pool = {@@ -1418,9 +1394,7 @@ def test_runtime_monitor_does_not_replace_a_connected_full_pool()-def test_runtime_monitor_is_singleton_for_one_managed_generation(- monkeypatch, tmp_path-) -> None:+def test_runtime_monitor_is_singleton_for_one_managed_generation(monkeypatch, tmp_path) -> None:from jarvis.realtime.local_server import installmonkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))@@ -1551,9 +1525,7 @@ def test_managed_identity_follows_a_uv_python_console_script(tmp_path) -> None:@pytest.mark.skipif(os.name != "nt", reason="uv Windows console-script handoff")-def test_ready_listener_replaces_a_dead_launcher_as_owner(- monkeypatch, tmp_path-) -> None:+def test_ready_listener_replaces_a_dead_launcher_as_owner(monkeypatch, tmp_path) -> None:import psutilmonkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))@@ -1627,6 +1599,7 @@ def test_status_reports_reachable_and_ownership(monkeypatch, tmp_path) -> None:"pid": None,"owned": False,"stale": False,+ "boot": {"failed_streak": 0, "starting": False},}@@ -1780,3 +1753,108 @@ def test_hf_symlink_workaround_is_windows_only(monkeypatch) -> None:assert "HF_HUB_DISABLE_SYMLINKS" not in envassert env.get("PYTHONFAULTHANDLER") == "1"assert env.get("PYTHONUNBUFFERED") == "1"+++# ── Boot progress in status ──────────────────────────────────────────────+def _write_booting_pidfile(tmp_path: Path, *, spawned_ago_s: float) -> None:+ (tmp_path / "local_realtime_server.pid.json").write_text(+ json.dumps(+ {+ "pid": 4711,+ "create_time": 1000.0,+ "port": 8765,+ "command": "serve",+ "spawned_at": time.time() - spawned_ago_s,+ "spawn_token": "boot-test-token",+ }+ ),+ encoding="utf-8",+ )+++def test_status_reports_stage_and_eta_while_an_owned_child_boots(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)+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.0)+ _write_booting_pidfile(tmp_path, spawned_ago_s=20.0)+ stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+ (tmp_path / "local_realtime_server.log").write_text(+ f"{stamp},100 - speech_to_speech.TTS.qwen3_tts_handler - INFO - "+ "Loading Qwen3-TTS model: Qwen/Qwen3-TTS\n",+ encoding="utf-8",+ )+ from jarvis.realtime.local_server import boot_progress++ earlier_generation = "an-earlier-generation"+ boot_progress.record_ready(+ tmp_path / "local_realtime_server.boot.json",+ token=earlier_generation,+ duration_s=80.0,+ )++ boot = supervisor.status("http://127.0.0.1:8765")["boot"]++ assert boot["starting"] is True+ assert boot["stage"] == "voice-model"+ assert boot["stage_label"] == "loading the speaking voice"+ assert boot["expected_total_s"] == 80.0+ assert 50.0 <= boot["remaining_s"] <= 65.0+ assert boot["failed_streak"] == 0+++def test_status_records_the_boot_duration_once_when_the_pool_turns_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: {+ "size": 1,+ "in_use": 0,+ "available": 1,+ "active": 0,+ "draining": 0,+ "stuck": 0,+ },+ )+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.0)+ _write_booting_pidfile(tmp_path, spawned_ago_s=64.0)+ from jarvis.realtime.local_server import boot_progress++ first = supervisor.status("http://127.0.0.1:8765")+ second = supervisor.status("http://127.0.0.1:8765")++ assert first["boot"]["starting"] is False+ assert second["boot"]["starting"] is False+ stats = boot_progress.load_stats(tmp_path / "local_realtime_server.boot.json")+ assert len(stats["durations_s"]) == 1+ assert 63.0 <= stats["durations_s"][0] <= 70.0+++def test_readiness_timeout_cleanup_counts_toward_the_crash_loop_streak(+ monkeypatch, tmp_path+) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1000.0)+ monkeypatch.setattr(+ supervisor, "_stop_owned_unlocked", lambda **kwargs: (True, "stopped pid 4711")+ )+ _write_booting_pidfile(tmp_path, spawned_ago_s=400.0)+ generation = supervisor._owned_generation()+ assert generation is not None++ outcome, _message = supervisor._cleanup_timed_out_generation(+ base_url="http://127.0.0.1:8765",+ install_root=tmp_path / "local_realtime",+ expected_generation=generation,+ )++ from jarvis.realtime.local_server import boot_progress++ assert outcome == "completed"+ stats = boot_progress.load_stats(tmp_path / "local_realtime_server.boot.json")+ assert stats["failed_streak"] == 1