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): make local model switches transactional
rubenluetke10-beep4455bd1b34c4
diff --git a/docs/commands-reference.md b/docs/commands-reference.mdindex 847f26de0f..a8464e7905 100644--- a/docs/commands-reference.md+++ b/docs/commands-reference.md@@ -51,6 +51,16 @@ Switch which realtime voice engine (speech-to-speech) is active, including subsc- **Desktop UI section:** `apikeys`- **Voice example (EN):** "switch the realtime model to gemini"+## `local-realtime-models-set` — Configure local realtime models++Select the Ollama brain and speech model for the managed local realtime server, then activate them only after a voice test.++- **Endpoint:** `POST /api/providers/local-realtime/managed-server/setup`+- **Arguments:** `brain_model` (string; required); `voice_model` (one of: qwen3-tts-1.7b, qwen3-tts-0.6b; required)+- **Requires confirmation:** yes+- **Desktop UI section:** `apikeys`+- **Voice example (EN):** "change the local realtime models"+## `computer-use-switch` — Switch Computer-Use providerSwitch the dedicated Computer-Use planner provider (screen control), decoupled from the main brain.diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.pyindex dcd6692594..3d52d79af7 100644--- a/jarvis/commands/registry.py+++ b/jarvis/commands/registry.py@@ -233,6 +233,36 @@ def _build_registry() -> tuple[AppCommand, ...]:"es": ("cambia el modelo en tiempo real a gemini",), # i18n-allow: input vocab},),+ AppCommand(+ id="local-realtime-models-set",+ title="Configure local realtime models",+ description=(+ "Select the Ollama brain and speech model for the managed local "+ "realtime server, then activate them only after a voice test."+ ),+ method="POST",+ path="/api/providers/local-realtime/managed-server/setup",+ params={+ "type": "object",+ "properties": {+ "brain_model": _str_param(+ "Exact Ollama model tag.", min_length=1, max_length=201+ ),+ "voice_model": _str_param(+ "Managed speech-model profile id.",+ enum=["qwen3-tts-1.7b", "qwen3-tts-0.6b"],+ ),+ },+ "required": ["brain_model", "voice_model"],+ },+ dangerous=True,+ ui_section="apikeys",+ voice_aliases={+ "de": ("stelle die lokalen sprachmodelle um",), # i18n-allow: input vocab+ "en": ("change the local realtime models",),+ "es": ("cambia los modelos de voz locales",), # i18n-allow: input vocab+ },+ ),AppCommand(id="computer-use-switch",title="Switch Computer-Use provider",diff --git a/jarvis/realtime/local_server/brain_link.py b/jarvis/realtime/local_server/brain_link.pyindex c14ed381e1..202e43e6a9 100644--- a/jarvis/realtime/local_server/brain_link.py+++ b/jarvis/realtime/local_server/brain_link.py@@ -60,6 +60,7 @@ _UNUSABLE_MARKERS: tuple[str, ...] = ()_OLLAMA_DEFAULT = "http://127.0.0.1:11434"+_MANAGED_VOICE_SUFFIX = "-voice-8k"@dataclass(frozen=True, slots=True)@@ -196,12 +197,17 @@ def list_brain_choices(resolver applies, so the picker and the resolver can never disagree."""base = _ollama_base()+ if current_model.endswith(_MANAGED_VOICE_SUFFIX):+ current_model = current_model[: -len(_MANAGED_VOICE_SUFFIX)]served = _ollama_models(base, timeout)reachable = served is not Nonechoices: list[dict[str, object]] = []seen: set[str] = set()for name, size in served or []:- if not _usable_tag(name):+ # The managed 8k alias is an implementation detail derived from its+ # base tag. Listing both made one selection look like two models and+ # encouraged users to select an alias that is recreated automatically.+ if name.endswith(_MANAGED_VOICE_SUFFIX) or not _usable_tag(name):continueseen.add(name)fits = _fits(size, usable_gb)diff --git a/jarvis/realtime/local_server/configure.py b/jarvis/realtime/local_server/configure.pynew file mode 100644index 0000000000..2c3d7a1bf4--- /dev/null+++ b/jarvis/realtime/local_server/configure.py@@ -0,0 +1,178 @@+"""Transactional model changes for the managed local realtime server."""++from __future__ import annotations++import asyncio+import logging+import re++log = logging.getLogger(__name__)++_OLLAMA_TAG = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,200}")+++class ManagedSetupError(RuntimeError):+ """A setup failed after preserving or restoring the previous stack."""+++def build_launch_command(+ current_command: str,+ *,+ brain_model: str,+ voice_model: str,+) -> str:+ """Apply validated model identifiers to a managed launch command."""+ selected_brain = (brain_model or "").strip()+ if not _OLLAMA_TAG.fullmatch(selected_brain):+ raise ValueError("the selected Ollama model name is not valid")+ from jarvis.realtime.local_server import supervisor+ from jarvis.realtime.local_server.model_catalog import apply_voice_profile++ if not supervisor.is_managed_launch_command(current_command):+ raise ValueError("only the Jarvis-managed server can be configured here")+ rewritten = supervisor._replace_brain_model(current_command, selected_brain)+ return apply_voice_profile(rewritten, voice_model)+++async def apply_and_test_stack(+ *,+ base_url: str,+ current_command: str,+ brain_model: str,+ voice_model: str,+ language: str,+) -> dict[str, object]:+ """Replace, voice-test, persist, or roll back one complete local stack."""+ from jarvis.realtime.local_server import install, supervisor+ from jarvis.realtime.local_server.smoke import probe_voice_roundtrip++ new_command = build_launch_command(+ current_command,+ brain_model=brain_model,+ voice_model=voice_model,+ )+ outcome = await asyncio.to_thread(+ lambda: supervisor.replace_idle_managed_runtime(+ current_command=current_command,+ launch_command=new_command,+ base_url=base_url,+ reason="model-switch",+ )+ )+ if outcome.startswith("refused:"):+ reason = outcome.partition(":")[2]+ if reason == "call-active":+ raise ManagedSetupError(+ "a voice call is active; finish it before changing local models"+ )+ if reason == "runtime-state-unknown":+ raise ManagedSetupError(+ "the local server is still starting; wait until it is ready and retry"+ )+ raise ManagedSetupError(f"the local server could not switch models ({reason})")++ try:+ ready = await asyncio.to_thread(+ lambda: supervisor.wait_until_ready(+ base_url,+ timeout=supervisor.RUNTIME_READY_TIMEOUT_S,+ launch_command=new_command,+ cleanup_on_timeout=True,+ )+ )+ if not ready:+ raise RuntimeError("the selected models did not become ready in time")+ await asyncio.to_thread(lambda: supervisor.warm_brain(launch_command=new_command))+ smoke = await probe_voice_roundtrip(+ base_url,+ language=language,+ timeout_s=90.0,+ )++ await asyncio.to_thread(lambda: install.repair_smoke_marker_from_live_runtime(base_url))+ await asyncio.to_thread(+ lambda: supervisor.start_runtime_monitor(+ launch_command=new_command,+ base_url=base_url,+ )+ )+ runtime = await asyncio.to_thread(supervisor.status, base_url)++ # Persist last: a model is not the active selection until it has+ # produced both a safe transcript and real PCM through the shipped+ # adapter, and its runtime supervision is armed. The config writer+ # supplies lock + atomic replace + BOM handling (AP-7).+ from jarvis.core.config_writer import set_local_realtime_launch_command++ await asyncio.to_thread(set_local_realtime_launch_command, new_command)+ return {+ "ok": True,+ "changed": new_command != current_command,+ "brain_model": brain_model,+ "voice_model": voice_model,+ "smoke": smoke,+ "runtime": runtime,+ "launch_command": new_command,+ }+ except BaseException as exc:+ rollback = await _rollback_stack(+ base_url=base_url,+ failed_command=new_command,+ previous_command=current_command,+ )+ if isinstance(exc, asyncio.CancelledError):+ raise+ message = str(exc) or type(exc).__name__+ if rollback:+ raise ManagedSetupError(+ f"the selected models failed the voice test ({message}); "+ "the previous setup was restored"+ ) from exc+ raise ManagedSetupError(+ f"the selected models failed the voice test ({message}); automatic rollback also failed"+ ) from exc+++async def _rollback_stack(+ *,+ base_url: str,+ failed_command: str,+ previous_command: str,+) -> bool:+ """Best-effort rollback that is still fully readiness-verified."""+ from jarvis.realtime.local_server import supervisor++ try:+ outcome = await asyncio.to_thread(+ lambda: supervisor.replace_idle_managed_runtime(+ current_command=failed_command,+ launch_command=previous_command,+ base_url=base_url,+ reason="model-switch-rollback",+ )+ )+ if outcome.startswith("refused:"):+ log.error("local-realtime model rollback was refused: %s", outcome)+ return False+ ready = await asyncio.to_thread(+ lambda: supervisor.wait_until_ready(+ base_url,+ timeout=supervisor.RUNTIME_READY_TIMEOUT_S,+ launch_command=previous_command,+ cleanup_on_timeout=True,+ )+ )+ if not ready:+ log.error("local-realtime model rollback did not become ready")+ return False+ await asyncio.to_thread(lambda: supervisor.warm_brain(launch_command=previous_command))+ await asyncio.to_thread(+ lambda: supervisor.start_runtime_monitor(+ launch_command=previous_command,+ base_url=base_url,+ )+ )+ return True+ except Exception: # noqa: BLE001 - the caller surfaces rollback failure+ log.exception("local-realtime model rollback failed")+ return Falsediff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.pyindex e466e55afd..3c985fd683 100644--- a/jarvis/realtime/local_server/install.py+++ b/jarvis/realtime/local_server/install.py@@ -565,6 +565,14 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:f"server exited right after binding (code {proc.returncode}); "f"see {smoke_log}")+ _set("smoke", 94, "testing a complete text-to-speech response")+ from jarvis.realtime.local_server.smoke import (+ probe_voice_roundtrip_sync,+ )++ probe_voice_roundtrip_sync(+ f"http://127.0.0.1:{_SMOKE_PORT}", timeout_s=90.0+ )returnelapsed = int(time.monotonic() - (deadline - _SMOKE_TIMEOUT_S))_set("smoke", 70 + min(25, elapsed // 30), "waiting for first boot (downloads models)")@@ -579,7 +587,12 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:)-def start_install(*, confirmed_brain: str = "") -> tuple[bool, str]:+def start_install(+ *,+ confirmed_brain: str = "",+ brain_model: str = "",+ voice_model: str = "",+) -> tuple[bool, str]:"""Kick off (or resume) the managed install. Returns immediately.``confirmed_brain`` is the brain kind the user saw in the preflight@@ -600,7 +613,11 @@ def start_install(*, confirmed_brain: str = "") -> tuple[bool, str]:thread = threading.Thread(target=_run_install,name="local-realtime-install",- args=(confirmed_brain.strip(),),+ args=(+ confirmed_brain.strip(),+ brain_model.strip(),+ voice_model.strip(),+ ),daemon=True,)_STATE.thread = thread@@ -608,7 +625,11 @@ def start_install(*, confirmed_brain: str = "") -> tuple[bool, str]:return True, "install started"-def _run_install(confirmed_brain: str = "") -> None:+def _run_install(+ confirmed_brain: str = "",+ brain_model: str = "",+ voice_model: str = "",+) -> None:"""Hold the cross-process server lifecycle lease for the whole install."""from jarvis.realtime.local_server import supervisor@@ -616,7 +637,12 @@ def _run_install(confirmed_brain: str = "") -> None:if not guarded:_fail("another local-realtime lifecycle operation is already running")return- _run_install_guarded(confirmed_brain)+ if brain_model or voice_model:+ _run_install_guarded(confirmed_brain, brain_model, voice_model)+ else:+ # Keep the long-standing one-argument seam used by embedders and+ # tests while extending new installs with explicit model choices.+ _run_install_guarded(confirmed_brain)def _pull_brain_model(model: str) -> None:@@ -661,7 +687,7 @@ def _pull_brain_model(model: str) -> None:asyncio.run(_pull_and_wait())-def resolve_brain_for_install() -> BrainResolution:+def resolve_brain_for_install(preferred_model: str = "") -> BrainResolution:"""The brain resolution the install engine trusts (own seam for tests)."""from jarvis.realtime.local_server.brain_link import resolve_brainfrom jarvis.realtime.local_server.preflight import (@@ -671,11 +697,12 @@ def resolve_brain_for_install() -> BrainResolution:usable_gb, _source = _usable_accelerator_gb()return resolve_brain(- preferred_model=_preferred_brain_model(), usable_gb=usable_gb+ preferred_model=preferred_model or _preferred_brain_model(),+ usable_gb=usable_gb,)-def _setup_local_brain() -> None:+def _setup_local_brain(preferred_model: str = "") -> None:"""Make the Ollama brain real: runtime installed + running + model present.The single-click promise (maintainer directive 2026-08-08): selecting@@ -690,19 +717,41 @@ def _setup_local_brain() -> None:ok, detail = ollama_runtime.ensure_runtime_blocking()if not ok:raise RuntimeError(detail)- if resolve_brain_for_install().ok:+ resolved = (+ resolve_brain_for_install(preferred_model)+ if preferred_model+ else resolve_brain_for_install()+ )+ if resolved.ok and (not preferred_model or resolved.model == preferred_model):return_set("brain-setup", 5, "no usable brain model yet — downloading one")- _pull_brain_model(_PREFERRED_MODELS[0])+ _pull_brain_model(preferred_model or _PREFERRED_MODELS[0])++ if not preferred_model:+ return+ verified = resolve_brain_for_install(preferred_model)+ if not verified.ok or verified.model != preferred_model:+ raise RuntimeError(+ f"the selected brain model is not usable after download: {preferred_model}"+ )-def _run_install_guarded(confirmed_brain: str = "") -> None:+def _run_install_guarded(+ confirmed_brain: str = "",+ brain_model: str = "",+ voice_model: str = "",+) -> None:try:# Marker-schema upgrades are metadata debt, not grounds to tear down a# healthy multi-gigabyte runtime. Only this exact patched install's# owned, fully-ready pool may take the non-destructive repair path.- if not _smoke_marker_valid() and _repair_smoke_marker_from_live_runtime_unlocked(- f"http://127.0.0.1:{SERVE_PORT}"+ if (+ not brain_model+ and not voice_model+ and not _smoke_marker_valid()+ and _repair_smoke_marker_from_live_runtime_unlocked(+ f"http://127.0.0.1:{SERVE_PORT}"+ )):marker = _read_smoke_marker_payload() or {}repaired_brain = str(marker.get("brain") or "")@@ -716,24 +765,42 @@ def _run_install_guarded(confirmed_brain: str = "") -> None:log.info("local-realtime: install proof repaired without server teardown")return_set("preflight", 2, "checking hardware, disk, and brain")- report: PreflightReport = run_preflight(install_root())+ report: PreflightReport = (+ run_preflight(install_root(), preferred_model=brain_model)+ if brain_model+ else run_preflight(install_root())+ )if (- not report.ok- and confirmed_brain == "ollama"+ confirmed_brain == "ollama"and report.tier is not Noneand report.brain is not None- and report.brain.kind == "blocked"+ and (+ report.brain.kind == "blocked"+ or (brain_model and report.brain.model != brain_model)+ )):# Hardware and disk are fine; only the BRAIN is missing — and# the user just confirmed a fully-local install. Set it up# (install/start Ollama, pull the model) and check again.- _setup_local_brain()+ if brain_model:+ _setup_local_brain(brain_model)+ else:+ _setup_local_brain()_set("preflight", 7, "re-checking after the brain setup")- report = run_preflight(install_root())+ report = (+ run_preflight(install_root(), preferred_model=brain_model)+ if brain_model+ else run_preflight(install_root())+ )if not report.ok:_fail(report.blocker)returnassert report.brain is not None and report.tier is not None+ if brain_model and report.brain.model != brain_model:+ _fail(+ f"the selected brain model is not available or does not fit: {brain_model}"+ )+ returnif confirmed_brain and report.brain.kind != confirmed_brain:_fail("the reasoning setup changed since your confirmation (was "@@ -792,6 +859,10 @@ def _run_install_guarded(confirmed_brain: str = "") -> None:_set("smoke", 70, "first boot (downloads voice/hearing models once)")launch_command = derive_launch_command(report.brain, memory_source=report.memory_source)+ if voice_model:+ from jarvis.realtime.local_server.model_catalog import apply_voice_profile++ launch_command = apply_voice_profile(launch_command, voice_model)if report.brain.kind == "ollama":# The OpenAI-compatible Ollama API cannot carry num_ctx per request.# Create/use the managed 8k profile before the first smoke boot so@@ -812,6 +883,8 @@ def _run_install_guarded(confirmed_brain: str = "") -> None:"at": time.time(),"tier": report.tier.key,"brain": report.brain.kind,+ "brain_model": report.brain.model,+ "voice_model": voice_model or "qwen3-tts-1.7b","preflight": report_payload(report),})diff --git a/jarvis/realtime/local_server/model_catalog.py b/jarvis/realtime/local_server/model_catalog.pynew file mode 100644index 0000000000..e02781f11a--- /dev/null+++ b/jarvis/realtime/local_server/model_catalog.py@@ -0,0 +1,202 @@+"""User-selectable model profiles for the managed local realtime stack.++Ollama owns the language-model catalog. This module owns the smaller speech+catalog because TTS checkpoints are not Ollama models and pretending otherwise+would make the picker lie. Only profiles exercised by the pinned managed+runtime are selectable; upstream backends remain visible with an honest reason+until their dependency set and end-to-end audio path pass the same smoke gate.+"""++from __future__ import annotations++import os+import re+from dataclasses import asdict, dataclass+++@dataclass(frozen=True, slots=True)+class VoiceProfile:+ id: str+ label: str+ backend: str+ model: str+ languages: tuple[str, ...]+ selectable: bool+ recommended: bool = False+ note: str = ""+ speaker: str = ""+++_QWEN_LANGUAGES = ("de", "en", "es", "fr", "it", "pt", "zh", "ja", "ko", "ru")++# The two CustomVoice checkpoints use the same pinned qwen-tts runtime and+# speaker contract. The remaining entries are capabilities of the pinned+# speech-to-speech server, but their optional dependency/profile bake-off has+# not passed Jarvis's managed audio gate yet.+VOICE_PROFILES: tuple[VoiceProfile, ...] = (+ VoiceProfile(+ id="qwen3-tts-1.7b",+ label="Qwen3-TTS 1.7B",+ backend="qwen3",+ model="Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",+ languages=_QWEN_LANGUAGES,+ selectable=True,+ recommended=True,+ note="Best multilingual quality in the tested managed profile.",+ speaker="Aiden",+ ),+ VoiceProfile(+ id="qwen3-tts-0.6b",+ label="Qwen3-TTS 0.6B",+ backend="qwen3",+ model="Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice",+ languages=_QWEN_LANGUAGES,+ selectable=True,+ note="Smaller multilingual voice model; first use downloads its weights.",+ speaker="Aiden",+ ),+ VoiceProfile(+ id="kokoro-82m",+ label="Kokoro-82M",+ backend="kokoro",+ model="hexgrad/Kokoro-82M",+ languages=("en", "ja", "zh", "fr", "it", "pt"),+ selectable=False,+ note="Visible upstream option; its optional package has not passed the managed voice test.",+ ),+ VoiceProfile(+ id="pocket-tts",+ label="Pocket TTS",+ backend="pocket",+ model="kyutai/pocket-tts",+ languages=("en", "fr"),+ selectable=False,+ note=(+ "Visible upstream option; its optional package conflicts with the "+ "current audio-enhancement stack."+ ),+ ),+ VoiceProfile(+ id="chattts",+ label="ChatTTS",+ backend="chatTTS",+ model="2Noise/ChatTTS",+ languages=("en", "zh"),+ selectable=False,+ note="Visible upstream option; it is not yet validated by the managed realtime smoke test.",+ ),+ VoiceProfile(+ id="mms-tts",+ label="MMS TTS",+ backend="facebookMMS",+ model="facebook/mms-tts-*",+ languages=("single-language",),+ selectable=False,+ note=(+ "Visible upstream option; each language needs a separate model, so "+ "it cannot follow automatic language switching yet."+ ),+ ),+)++_PROFILE_BY_ID = {profile.id: profile for profile in VOICE_PROFILES}+_TTS_FLAG = re.compile(r"(?<!\S)--tts(?:\s+|=)(?:\"[^\"]*\"|'[^']*'|\S+)", re.IGNORECASE)+_QWEN_MODEL_FLAG = re.compile(+ r"(?<!\S)--qwen3_tts_model_name(?:\s+|=)(?:\"[^\"]*\"|'[^']*'|\S+)",+ re.IGNORECASE,+)+_QWEN_SPEAKER_FLAG = re.compile(+ r"(?<!\S)--qwen3_tts_speaker(?:\s+|=)(?:\"[^\"]*\"|'[^']*'|\S+)",+ re.IGNORECASE,+)+++def get_voice_profile(profile_id: str) -> VoiceProfile | None:+ """Return a known profile without accepting arbitrary command fragments."""+ return _PROFILE_BY_ID.get((profile_id or "").strip())+++def current_voice_profile(command: str) -> str:+ """Resolve the effective managed TTS profile from a launch command."""+ backend = _flag_value(command, "--tts") or "qwen3"+ model = _flag_value(command, "--qwen3_tts_model_name")+ if backend.lower() == "qwen3" and not model:+ return "qwen3-tts-1.7b"+ for profile in VOICE_PROFILES:+ if profile.backend.lower() != backend.lower():+ continue+ if not profile.model or profile.model == model:+ return profile.id+ return ""+++def voice_catalog(command: str) -> dict[str, object]:+ """JSON-shaped speech model catalog with the persisted selection."""+ current = current_voice_profile(command)+ models: list[dict[str, object]] = []+ for profile in VOICE_PROFILES:+ item = asdict(profile)+ item["languages"] = list(profile.languages)+ item["current"] = profile.id == current+ # Kokoro's built-in status differs by platform, but it stays+ # unselectable until its Jarvis smoke profile passes on every OS.+ item["platform"] = (+ "macOS / Linux / Windows"+ if profile.id != "kokoro-82m"+ else ("built in on macOS; optional package elsewhere")+ )+ models.append(item)+ return {+ "current": current,+ "models": models,+ "hearing": {+ "id": "parakeet-tdt",+ "label": "Parakeet TDT",+ "note": "Speech-to-text for the call. The wake-word model is configured separately.",+ },+ }+++def apply_voice_profile(command: str, profile_id: str) -> str:+ """Return ``command`` with one validated, selectable TTS profile applied."""+ profile = get_voice_profile(profile_id)+ if profile is None:+ raise ValueError(f"unknown voice model: {profile_id}")+ if not profile.selectable:+ raise ValueError(profile.note or f"voice model {profile_id} is not selectable")+ rewritten = _replace_flag(command, _TTS_FLAG, f"--tts {profile.backend}")+ rewritten = _replace_flag(+ rewritten,+ _QWEN_MODEL_FLAG,+ f"--qwen3_tts_model_name {profile.model}",+ )+ if profile.speaker:+ rewritten = _replace_flag(+ rewritten,+ _QWEN_SPEAKER_FLAG,+ f"--qwen3_tts_speaker {profile.speaker}",+ )+ return rewritten+++def _replace_flag(command: str, pattern: re.Pattern[str], rendered: str) -> str:+ without_old = pattern.sub("", command or "").strip()+ return f"{without_old} {rendered}".strip()+++def _flag_value(command: str, flag: str) -> str:+ try:+ import shlex++ tokens = shlex.split(command or "", posix=os.name != "nt")+ except ValueError:+ return ""+ value = ""+ lowered_flag = flag.lower()+ for index, token in enumerate(tokens):+ lowered = token.lower()+ if lowered == lowered_flag and index + 1 < len(tokens):+ value = tokens[index + 1].strip("\"'")+ elif lowered.startswith(f"{lowered_flag}="):+ value = token.split("=", 1)[1].strip("\"'")+ return valuediff --git a/jarvis/realtime/local_server/preflight.py b/jarvis/realtime/local_server/preflight.pyindex 2870ce442e..cabe8da479 100644--- a/jarvis/realtime/local_server/preflight.py+++ b/jarvis/realtime/local_server/preflight.py@@ -98,7 +98,9 @@ def _preferred_brain_model() -> str:return ""-def run_preflight(install_root: Path) -> PreflightReport:+def run_preflight(+ install_root: Path, *, preferred_model: str = ""+) -> PreflightReport:"""The full go/no-go report for a managed install under ``install_root``."""usable_gb, source = _usable_accelerator_gb()disk_free = _disk_free_gb(install_root)@@ -148,7 +150,8 @@ def run_preflight(install_root: Path) -> PreflightReport:tier=tier,)brain = resolve_brain(- preferred_model=_preferred_brain_model(), usable_gb=usable_gb+ preferred_model=preferred_model or _preferred_brain_model(),+ usable_gb=usable_gb,)if not brain.ok:return PreflightReport(diff --git a/jarvis/realtime/local_server/smoke.py b/jarvis/realtime/local_server/smoke.pynew file mode 100644index 0000000000..84e1a68f47--- /dev/null+++ b/jarvis/realtime/local_server/smoke.py@@ -0,0 +1,119 @@+"""End-to-end audio proof for the managed local realtime server."""++from __future__ import annotations++import asyncio+import time+from typing import Any++from jarvis.core.turn_language import validate_output_language++_MIN_AUDIO_BYTES = 2_400 # 50 ms of 24 kHz mono PCM16; rejects empty headers.++_PROBE_INPUTS = {+ "en": "Please answer with one short sentence confirming that the voice test works.",+ "de": ( # i18n-allow: runtime voice probe+ "Bitte antworte mit einem kurzen Satz, der " # i18n-allow+ "bestätigt, dass der Sprachtest funktioniert." # i18n-allow+ ),+ "es": "Responde con una frase corta que confirme que la prueba de voz funciona.",+}++_PROBE_INSTRUCTIONS = {+ "en": "Answer briefly in English. Do not call tools and do not use code or lists.",+ "de": ( # i18n-allow: runtime voice probe+ "Antworte kurz auf Deutsch. Verwende keine Tools, " # i18n-allow+ "keinen Code und keine Listen." # i18n-allow+ ),+ "es": "Responde brevemente en español. No uses herramientas, código ni listas.",+}+++async def probe_voice_roundtrip(+ base_url: str,+ *,+ language: str = "en",+ timeout_s: float = 60.0,+) -> dict[str, object]:+ """Prove handshake -> LLM -> transcript -> TTS audio -> clean boundary.++ A ready ``/v1/pool`` proves model loading only. This probe deliberately+ traverses the same OpenAI Realtime adapter the desktop call uses, so a+ protocol/model switch that yields text but no audible response cannot be+ persisted as successful.+ """+ expected = language if language in _PROBE_INPUTS else "en"++ # Import through the plugin loader boundary rather than creating another+ # websocket implementation whose event semantics could drift.+ from jarvis.plugins.realtime.openai_realtime import LocalRealtimeProvider+ from jarvis.realtime.protocol import RealtimeSessionConfig++ provider = LocalRealtimeProvider(base_url=base_url)+ started_at = time.monotonic()+ session: Any | None = None+ transcript_parts: list[str] = []+ audio_bytes = 0+ first_audio_ms: int | None = None+ completed = False+ try:+ async with asyncio.timeout(max(1.0, timeout_s)):+ session = await provider.open_session(+ RealtimeSessionConfig(+ instructions=_PROBE_INSTRUCTIONS[expected],+ language=expected,+ input_language=expected,+ language_is_pinned=True,+ tools=(),+ )+ )+ await session.send_text(_PROBE_INPUTS[expected])+ async for event in session.receive():+ if event.type == "audio_delta" and event.audio is not None:+ chunk = bytes(getattr(event.audio, "pcm", b"") or b"")+ if chunk and first_audio_ms is None:+ first_audio_ms = int((time.monotonic() - started_at) * 1000)+ audio_bytes += len(chunk)+ elif event.type == "output_transcript_delta" and event.text:+ transcript_parts.append(str(event.text))+ elif event.type == "error":+ raise RuntimeError(event.error or "the realtime server reported an error")+ elif event.type == "turn_complete":+ completed = True+ break+ except TimeoutError as exc:+ raise TimeoutError(f"voice test did not complete within {timeout_s:.0f} seconds") from exc+ finally:+ if session is not None:+ await session.close()++ transcript = "".join(transcript_parts).strip()+ if not completed:+ raise RuntimeError("voice test ended without a response boundary")+ if not transcript:+ raise RuntimeError("voice test produced audio without a safety transcript")+ if audio_bytes < _MIN_AUDIO_BYTES:+ raise RuntimeError("voice test produced no usable speech audio")+ verdict = validate_output_language(transcript, resolved_language=expected)+ if verdict.should_block:+ raise RuntimeError(+ "voice test answered in the wrong language "+ f"(expected {expected}, detected {verdict.detected_language})"+ )+ return {+ "ok": True,+ "language": expected,+ "audio_bytes": audio_bytes,+ "first_audio_ms": first_audio_ms,+ "transcript_chars": len(transcript),+ }+++def probe_voice_roundtrip_sync(+ base_url: str,+ *,+ language: str = "en",+ timeout_s: float = 60.0,+) -> dict[str, object]:+ """Synchronous installer entry point for :func:`probe_voice_roundtrip`."""+ return asyncio.run(probe_voice_roundtrip(base_url, language=language, timeout_s=timeout_s))diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.pyindex c9ce5bd449..a5b1493ae8 100644--- a/jarvis/realtime/local_server/supervisor.py+++ b/jarvis/realtime/local_server/supervisor.py@@ -1029,6 +1029,100 @@ def ensure_running(return "spawned"+def replace_idle_managed_runtime(+ *,+ current_command: str,+ launch_command: str,+ base_url: str,+ reason: str,+) -> str:+ """Replace one managed generation without ever interrupting a live call.++ This is the transactional model-switch primitive. It intentionally+ bypasses the crash-loop rate limit because the caller made one explicit+ replacement decision, but it keeps every ownership, loopback, process-tree+ and pid-reuse guard used by :func:`ensure_running`.+ """+ current = (current_command or "").strip()+ command = (launch_command or "").strip()+ current_root = managed_install_root(current)+ managed_root = managed_install_root(command)+ host, port = _host_port(base_url)+ if not command:+ return "refused:no-launch-command"+ if managed_root is None or (current and current_root != managed_root):+ return "refused:not-managed"+ if not _is_loopback(host):+ return "refused:not-local"++ with lifecycle_guard() as guarded:+ if not guarded:+ return "refused:lifecycle-busy"+ try:+ from jarvis.realtime.local_server import install++ if bool(install.snapshot().get("running")):+ return "refused:install-running"+ except Exception: # noqa: BLE001 - install state is advisory here+ log.debug("supervisor: install snapshot unavailable during switch", exc_info=True)++ pool = probe_runtime(base_url, timeout=0.75)+ if pool is not None and pool.get("in_use", 0) > 0:+ return "refused:call-active"+ _pid, alive = _owned_process()+ if pool is None and alive:+ # No model-pool verdict means the process may be loading or may+ # still own a client. Never turn uncertainty into a destructive+ # model switch.+ return "refused:runtime-state-unknown"+ if pool is None and _port_open(port, timeout=0.25):+ return "refused:port-in-use"++ _request_runtime_monitor_stop()+ changed, stop_message = _stop_owned_unlocked(+ owned_only=True,+ install_root=managed_root,+ )+ if not changed and pool is not None:+ log.warning(+ "local-realtime supervisor: idle replacement could not stop "+ "the serving generation (%s)",+ stop_message,+ )+ return "refused:stuck-process"+ if _port_open(port, timeout=0.25):+ return "refused:port-still-in-use"++ command = _force_loopback_bind(command)+ command = _force_low_latency_ollama_backend(command)+ command = _force_stable_turn_detection(command)+ try:+ command = prepare_voice_brain_command(command)+ except RuntimeError as exc:+ log.warning(+ "local-realtime supervisor: switch brain profile failed: %s",+ exc,+ )+ return "refused:brain-context-profile"++ clear_pidfile()+ spawned_pid = _spawn(command, reason=reason)+ if spawned_pid is None:+ return "refused:spawn-failed"+ if not _write_pidfile(spawned_pid, port, command):+ _kill_pid_tree(spawned_pid)+ _kill_by_install_root(managed_root)+ return "refused:ownership-failed"+ global _last_spawn_at+ _last_spawn_at = time.monotonic()+ log.info(+ "local-realtime supervisor: replaced idle server with pid=%s (%s)",+ spawned_pid,+ reason,+ )+ return "spawned"++def _server_creationflags(*, platform_name: str | None = None) -> int:"""Windowless flags that let the managed server survive an app restart."""from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # lazy@@ -1135,7 +1229,10 @@ def start_runtime_monitor(*, launch_command: str, base_url: str) -> bool:log.warning("supervisor: runtime monitor could not verify the install", exc_info=True)return False_pid, alive = _owned_process()- if not alive:+ if not alive and not reconcile_ready_ownership(+ launch_command=command,+ base_url=base_url,+ ):return Falsekey = (command, _pool_url(base_url))@@ -1547,11 +1644,79 @@ def _lexical_path_is_within_root(value: str, root: Path) -> bool: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(+ if _lexical_path_is_within_root(exe, root) or bool(cmdline and _lexical_path_is_within_root(cmdline[0], root)+ ):+ return True+ # uv-managed Windows environments can hand execution from the venv+ # launcher to uv's base Python. The first program argument is then the+ # managed console-script executable; it is executable identity, not an+ # arbitrary opened data file. Without this case the listener survived+ # while its short-lived launcher PID made ownership disappear.+ interpreter = Path(exe or (cmdline[0] if cmdline else "")).name.lower()+ return bool(+ os.name == "nt"+ and interpreter in {"python", "python.exe", "pythonw", "pythonw.exe"}+ and len(cmdline) > 1+ and Path(cmdline[1].strip("\"'")).name.lower() == "speech-to-speech.exe"+ and _lexical_path_is_within_root(cmdline[1], root))+def reconcile_ready_ownership(*, launch_command: str, base_url: str) -> bool:+ """Adopt the unique managed process that actually owns the ready port.++ Windows console-script launchers may exit after delegating to a Python+ child. Recording only the initial ``Popen.pid`` therefore loses+ ownership even though the server keeps listening. This bounded adoption+ requires all three proofs: a ready pool, executable identity under the+ managed install, and the exact loopback listening port.+ """+ root = managed_install_root(launch_command)+ host, port = _host_port(base_url)+ if root is None or not _is_loopback(host):+ return False+ with lifecycle_guard() as guarded:+ if not guarded or probe_runtime(base_url, timeout=0.75) is None:+ return False+ try:+ import psutil # type: ignore[import-untyped]+ except ImportError:+ return False++ candidates: list[Any] = []+ for proc in psutil.process_iter(["pid", "exe", "cmdline"]):+ try:+ exe = str(proc.info.get("exe") or "")+ cmdline = tuple(str(item) for item in (proc.info.get("cmdline") or ()))+ if not _process_identity_is_managed(exe, cmdline, root):+ continue+ if any(+ connection.status == psutil.CONN_LISTEN+ and connection.laddr+ and int(connection.laddr.port) == port+ for connection in proc.net_connections(kind="inet")+ ):+ candidates.append(proc)+ except (psutil.Error, OSError, TypeError, ValueError):+ log.debug("supervisor: ready-owner inspection failed", exc_info=True)+ if len(candidates) != 1:+ log.warning(+ "local-realtime supervisor: expected one managed listener on %s, found %s",+ port,+ len(candidates),+ )+ return False+ proc = candidates[0]+ pid = int(proc.pid)+ record = _read_pidfile() or {}+ command = str(record.get("command") or launch_command)+ if not _write_pidfile(pid, port, command):+ return False+ log.info("local-realtime supervisor: adopted ready listener pid=%s", pid)+ return True++def _kill_by_install_root(root: Path) -> tuple[int, int]:"""Return ``(stopped, survivors)`` for processes in OUR managed tree."""try:diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex a8608d490f..d866ec9e36 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -2698,13 +2698,35 @@ async def managed_server_install(request: Request) -> dict[str, Any]:from jarvis.realtime.local_server.install import snapshot, start_installconfirmed_brain = ""+ brain_model = ""+ voice_model = ""try:body = await request.json()confirmed_brain = str((body or {}).get("confirmed_brain", "") or "")+ brain_model = str((body or {}).get("brain_model", "") or "").strip()+ voice_model = str((body or {}).get("voice_model", "") or "").strip()except Exception: # noqa: BLE001 — an empty/absent body is the normal caseconfirmed_brain = ""+ if voice_model:+ from jarvis.realtime.local_server.model_catalog import get_voice_profile++ profile = get_voice_profile(voice_model)+ if profile is None or not profile.selectable:+ raise HTTPException(+ status_code=409,+ detail=(+ profile.note+ if profile is not None+ else f"unknown voice model: {voice_model}"+ ),+ )+ install_options = {"confirmed_brain": confirmed_brain}+ if brain_model:+ install_options["brain_model"] = brain_model+ if voice_model:+ install_options["voice_model"] = voice_modelstarted, message = await asyncio.to_thread(- lambda: start_install(confirmed_brain=confirmed_brain)+ lambda: start_install(**install_options))payload = snapshot()payload["started"] = started@@ -2909,70 +2931,189 @@ async def managed_server_brain_models(request: Request) -> dict[str, Any]:return await asyncio.to_thread(_collect)[email protected]("/providers/local-realtime/managed-server/brain")-async def managed_server_brain(request: Request) -> dict[str, Any]:- """Re-resolve the brain model and rewrite the launch command in place.-- The model choice is baked into the persisted command; before this route- changing it meant a full multi-gigabyte reinstall. Optional body- ``{"model": "..."}`` names an explicit Ollama tag (else the configured- ollama-card model, else the curated preference order). Only the managed- command is ever rewritten (`only_if_under` autonomy guard); the running- server keeps its old brain until the next start.[email protected]("/providers/local-realtime/managed-server/model-catalog")+async def managed_server_model_catalog(request: Request) -> dict[str, Any]:+ """The local voice stack as three honest, separate model roles.++ Ollama supplies the reasoning catalog. Hearing and speaking are not+ Ollama models, so this endpoint exposes the managed server's own speech+ catalog instead of mixing incompatible model types into one list."""- from jarvis.core.config_writer import update_local_realtime_launch_model+ from jarvis.realtime.local_server.model_catalog import voice_catalog++ _base_url, command = _local_realtime_card(request)+ return {+ "brain": await managed_server_brain_models(request),+ **voice_catalog(command),+ }+++def _managed_probe_language(request: Request) -> str:+ """Resolve the setup probe language through the one language resolver."""+ from jarvis.core.turn_language import DEFAULT_LOCALE, resolve_output_language++ cfg = getattr(request.app.state, "config", None) or getattr(+ request.app.state, "cfg", None+ )+ reply_language = getattr(getattr(cfg, "brain", None), "reply_language", "auto")+ ui_language = getattr(getattr(cfg, "ui", None), "language", DEFAULT_LOCALE)+ return resolve_output_language(+ reply_language,+ ui_language,+ "",+ default=DEFAULT_LOCALE,+ )+++def _adopt_managed_command(request: Request, command: str) -> None:+ """Keep the live config object aligned with the atomically written file."""+ cfg = getattr(request.app.state, "config", None) or getattr(+ request.app.state, "cfg", None+ )+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}+ getter = getattr(providers, "get", None)+ card = getter("local-realtime") if callable(getter) else None+ if card is None:+ return+ card.launch_command = command+ if not str(getattr(card, "base_url", "") or "").strip():+ card.base_url = "http://127.0.0.1:8765"+++async def _apply_managed_stack(+ request: Request,+ *,+ requested_brain: str,+ requested_voice: str,+) -> dict[str, Any]:from jarvis.realtime.local_server.brain_link import resolve_brain- from jarvis.realtime.local_server.install import install_root+ from jarvis.realtime.local_server.configure import (+ ManagedSetupError,+ apply_and_test_stack,+ )+ from jarvis.realtime.local_server.model_catalog import get_voice_profilefrom jarvis.realtime.local_server.preflight import (_preferred_brain_model,_usable_accelerator_gb,)+ from jarvis.realtime.local_server.supervisor import is_managed_launch_command- requested = ""- try:- body = await request.json()- requested = str((body or {}).get("model", "") or "").strip()- except Exception: # noqa: BLE001 — an empty/absent body is the normal case- requested = ""+ base_url, command = _local_realtime_card(request)+ if not command or not is_managed_launch_command(command):+ raise HTTPException(+ status_code=409,+ detail="install the managed local server before changing its models",+ )+ profile = get_voice_profile(requested_voice)+ if profile is None or not profile.selectable:+ raise HTTPException(+ status_code=409,+ detail=(+ profile.note+ if profile is not None+ else f"unknown voice model: {requested_voice}"+ ),+ )- def _resolve() -> Any:- usable_gb, _source = _usable_accelerator_gb()- return resolve_brain(- preferred_model=requested or _preferred_brain_model(),+ usable_gb, _source = await asyncio.to_thread(_usable_accelerator_gb)+ preferred = requested_brain or _preferred_brain_model()+ brain = await asyncio.to_thread(+ lambda: resolve_brain(+ preferred_model=preferred,usable_gb=usable_gb,)-- brain = await asyncio.to_thread(_resolve)+ )if not brain.ok or brain.kind != "ollama":raise HTTPException(status_code=409,detail=(brain.note- or "no usable local brain was found — install one via Ollama first"+ or "no usable local brain was found; install one through Ollama first"),)- if requested and brain.model != requested:- # An EXPLICIT choice is never silently swapped (user autonomy): the- # resolver's fallback pick is fine for automatic re-resolution, but a- # user who named a model gets the honest refusal with the reason.+ if requested_brain and brain.model != requested_brain:raise HTTPException(status_code=409,detail=(brain.note- or f"'{requested}' is not served by Ollama or does not fit "- "this machine."+ or f"'{requested_brain}' is not served by Ollama or does not fit this machine"),)- changed = await asyncio.to_thread(- lambda: update_local_realtime_launch_model(- brain.model, only_if_under=str(install_root())++ await _cancel_managed_server_warm(request)+ try:+ result = await apply_and_test_stack(+ base_url=base_url or "http://127.0.0.1:8765",+ current_command=command,+ brain_model=brain.model,+ voice_model=profile.id,+ language=_managed_probe_language(request),)- )- return {- "ok": True,- "changed": changed,- "brain": {"kind": brain.kind, "model": brain.model, "note": brain.note},+ except ManagedSetupError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ launch_command = str(result.pop("launch_command", "") or "")+ if launch_command:+ _adopt_managed_command(request, launch_command)+ result["brain"] = {+ "kind": brain.kind,+ "model": brain.model,+ "note": brain.note,}+ result["voice"] = {+ "id": profile.id,+ "label": profile.label,+ }+ return result+++ "/providers/local-realtime/managed-server/setup",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def managed_server_setup(request: Request) -> dict[str, Any]:+ """Apply a brain + voice choice only after a real audio test succeeds."""+ try:+ body = await request.json()+ except Exception as exc: # noqa: BLE001 - malformed JSON is a client error+ raise HTTPException(status_code=400, detail="a JSON request body is required") from exc+ brain_model = str((body or {}).get("brain_model", "") or "").strip()+ voice_model = str((body or {}).get("voice_model", "") or "").strip()+ if not brain_model or not voice_model:+ raise HTTPException(+ status_code=400,+ detail="brain_model and voice_model are required",+ )+ return await _apply_managed_stack(+ request,+ requested_brain=brain_model,+ requested_voice=voice_model,+ )++[email protected]("/providers/local-realtime/managed-server/brain")+async def managed_server_brain(request: Request) -> dict[str, Any]:+ """Compatibility action: switch the brain through the full voice gate.++ Older clients call this brain-only route. It preserves the current voice+ model but now uses the same restart, audio test and rollback contract as+ the combined setup action, so no user-facing model switch can bypass it.+ """+ from jarvis.realtime.local_server.model_catalog import voice_catalog++ requested = ""+ try:+ body = await request.json()+ requested = str((body or {}).get("model", "") or "").strip()+ except Exception: # noqa: BLE001 — an empty/absent body is the normal case+ requested = ""++ _base_url, command = _local_realtime_card(request)+ current_voice = str(voice_catalog(command).get("current") or "qwen3-tts-1.7b")+ return await _apply_managed_stack(+ request,+ requested_brain=requested,+ requested_voice=current_voice,+ )@router.delete(diff --git a/tests/unit/realtime/local_server/test_configure.py b/tests/unit/realtime/local_server/test_configure.pynew file mode 100644index 0000000000..866f5a47d7--- /dev/null+++ b/tests/unit/realtime/local_server/test_configure.py@@ -0,0 +1,94 @@+from __future__ import annotations++import pytest++from jarvis.realtime.local_server import configure+++async def test_setup_persists_only_after_the_voice_smoke_passes(monkeypatch) -> None:+ from jarvis.core import config_writer+ from jarvis.realtime.local_server import install, smoke, supervisor++ calls: list[str] = []+ monkeypatch.setattr(configure, "build_launch_command", lambda *args, **kwargs: "new")+ monkeypatch.setattr(+ supervisor,+ "replace_idle_managed_runtime",+ lambda **kwargs: calls.append("replace") or "spawned",+ )+ 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)++ async def voice_test(*args, **kwargs):+ calls.append("voice-test")+ return {"ok": True, "audio_bytes": 4_800}++ monkeypatch.setattr(smoke, "probe_voice_roundtrip", voice_test)+ monkeypatch.setattr(+ config_writer,+ "set_local_realtime_launch_command",+ lambda command: calls.append(f"persist:{command}"),+ )+ monkeypatch.setattr(+ install,+ "repair_smoke_marker_from_live_runtime",+ lambda base_url: calls.append("marker") or True,+ )+ monkeypatch.setattr(+ supervisor,+ "start_runtime_monitor",+ lambda **kwargs: calls.append("monitor") or True,+ )+ monkeypatch.setattr(supervisor, "status", lambda base_url: {"ready": True})++ result = await configure.apply_and_test_stack(+ base_url="http://127.0.0.1:8765",+ current_command="old",+ brain_model="qwen3.5:4b",+ voice_model="qwen3-tts-1.7b",+ language="en",+ )++ assert result["ok"] is True+ assert calls.index("voice-test") < calls.index("persist:new")+++async def test_failed_voice_smoke_restores_previous_runtime(monkeypatch) -> None:+ from jarvis.core import config_writer+ from jarvis.realtime.local_server import smoke, supervisor++ replacements: list[str] = []+ monkeypatch.setattr(configure, "build_launch_command", lambda *args, **kwargs: "new")+ monkeypatch.setattr(+ supervisor,+ "replace_idle_managed_runtime",+ lambda **kwargs: replacements.append(kwargs["launch_command"]) or "spawned",+ )+ monkeypatch.setattr(supervisor, "wait_until_ready", lambda *args, **kwargs: True)+ monkeypatch.setattr(supervisor, "warm_brain", lambda **kwargs: True)+ monkeypatch.setattr(supervisor, "start_runtime_monitor", lambda **kwargs: True)++ async def failed_voice_test(*args, **kwargs):+ raise RuntimeError("no usable speech audio")++ monkeypatch.setattr(smoke, "probe_voice_roundtrip", failed_voice_test)+ monkeypatch.setattr(+ config_writer,+ "set_local_realtime_launch_command",+ lambda command: pytest.fail("a failed model must never be persisted"),+ )++ with pytest.raises(configure.ManagedSetupError, match="previous setup was restored"):+ await configure.apply_and_test_stack(+ base_url="http://127.0.0.1:8765",+ current_command="old",+ brain_model="qwen3.5:4b",+ voice_model="qwen3-tts-1.7b",+ language="en",+ )++ assert replacements == ["new", "old"]diff --git a/tests/unit/realtime/local_server/test_engine.py b/tests/unit/realtime/local_server/test_engine.pyindex 607290c48b..5e7d68d5c5 100644--- a/tests/unit/realtime/local_server/test_engine.py+++ b/tests/unit/realtime/local_server/test_engine.py@@ -584,6 +584,10 @@ class TestReviewFixes:monkeypatch.setattr(install, "_kill_tree", lambda proc: killed.append(proc) or True)+ monkeypatch.setattr(+ "jarvis.realtime.local_server.smoke.probe_voice_roundtrip_sync",+ lambda *args, **kwargs: {"ok": True},+ )install._smoke_boot("serve --mode realtime",@@ -620,6 +624,10 @@ class TestReviewFixes:},)monkeypatch.setattr(install, "_kill_tree", lambda proc: False)+ monkeypatch.setattr(+ "jarvis.realtime.local_server.smoke.probe_voice_roundtrip_sync",+ lambda *args, **kwargs: {"ok": True},+ )with pytest.raises(RuntimeError, match="survived teardown"):install._smoke_boot(@@ -812,6 +820,29 @@ class TestBrainSetupChain:assert calls == []assert "minimum" in str(install.snapshot()["error"])+ def test_disk_blocker_never_downloads_a_brain_model(+ self, monkeypatch, tmp_path+ ) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ disk_blocked = preflight.PreflightReport(+ ok=False,+ blocker="not enough free disk",+ usable_gb=16.0,+ memory_source="nvidia-smi",+ disk_free_gb=1.0,+ tier=tiers.TIERS[0],+ )+ monkeypatch.setattr(install, "run_preflight", lambda root: disk_blocked)+ calls: list[str] = []+ monkeypatch.setattr(+ install, "_setup_local_brain", lambda: calls.append("setup")+ )++ install._run_install("ollama")++ assert calls == []+ assert "disk" in str(install.snapshot()["error"])+def test_setup_pulls_the_preferred_model_when_missing(self, monkeypatch) -> None:from jarvis.brain import ollama_runtimediff --git a/tests/unit/realtime/local_server/test_model_catalog.py b/tests/unit/realtime/local_server/test_model_catalog.pynew file mode 100644index 0000000000..6beb042c55--- /dev/null+++ b/tests/unit/realtime/local_server/test_model_catalog.py@@ -0,0 +1,32 @@+from __future__ import annotations++import pytest++from jarvis.realtime.local_server import model_catalog+++def test_catalog_separates_hearing_from_wake_word_and_speaking() -> None:+ catalog = model_catalog.voice_catalog("")++ assert catalog["hearing"]["id"] == "parakeet-tdt"+ assert "wake-word" in str(catalog["hearing"]["note"])+ assert catalog["current"] == "qwen3-tts-1.7b"+ assert len(catalog["models"]) == 6+ selectable = [item["id"] for item in catalog["models"] if item["selectable"]]+ assert selectable == ["qwen3-tts-1.7b", "qwen3-tts-0.6b"]+++def test_voice_profile_replaces_all_qwen_flags_without_duplicates() -> None:+ command = "serve --tts qwen3 --qwen3_tts_model_name old/model --qwen3_tts_speaker Old"++ rewritten = model_catalog.apply_voice_profile(command, "qwen3-tts-0.6b")++ assert rewritten.count("--tts") == 1+ assert rewritten.count("--qwen3_tts_model_name") == 1+ assert "Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice" in rewritten+ assert "--qwen3_tts_speaker Aiden" in rewritten+++def test_unvalidated_upstream_voice_cannot_be_selected() -> None:+ with pytest.raises(ValueError, match="not yet validated"):+ model_catalog.apply_voice_profile("serve", "chattts")diff --git a/tests/unit/realtime/local_server/test_smoke.py b/tests/unit/realtime/local_server/test_smoke.pynew file mode 100644index 0000000000..ab57606229--- /dev/null+++ b/tests/unit/realtime/local_server/test_smoke.py@@ -0,0 +1,88 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.realtime.local_server import smoke+++class _Session:+ def __init__(self, events: list[object]) -> None:+ self._events = events+ self.closed = False++ async def send_text(self, text: str) -> None:+ assert text++ async def receive(self):+ for event in self._events:+ yield event++ async def close(self) -> None:+ self.closed = True+++def _event(kind: str, *, text: str = "", pcm: bytes = b"", error: str = ""):+ return SimpleNamespace(+ type=kind,+ text=text,+ audio=SimpleNamespace(pcm=pcm) if pcm else None,+ error=error,+ )+++async def test_roundtrip_requires_audio_transcript_and_turn_boundary(monkeypatch) -> None:+ session = _Session(+ [+ _event("output_transcript_delta", text="The voice test works."),+ _event("audio_delta", pcm=b"\0" * 4_800),+ _event("turn_complete"),+ ]+ )++ class _Provider:+ def __init__(self, **kwargs) -> None:+ assert kwargs["base_url"] == "http://127.0.0.1:8765"++ async def open_session(self, config):+ assert config.language == "en"+ return session++ monkeypatch.setattr(+ "jarvis.plugins.realtime.openai_realtime.LocalRealtimeProvider",+ _Provider,+ )++ result = await smoke.probe_voice_roundtrip("http://127.0.0.1:8765")++ assert result["audio_bytes"] == 4_800+ assert result["first_audio_ms"] is not None+ assert session.closed is True+++async def test_roundtrip_rejects_the_text_only_failure_mode(monkeypatch) -> None:+ session = _Session(+ [+ _event("output_transcript_delta", text="The voice test works."),+ _event("turn_complete"),+ ]+ )++ class _Provider:+ def __init__(self, **kwargs) -> None:+ pass++ async def open_session(self, config):+ return session++ monkeypatch.setattr(+ "jarvis.plugins.realtime.openai_realtime.LocalRealtimeProvider",+ _Provider,+ )++ with pytest.raises(RuntimeError, match="no usable speech audio"):+ await smoke.probe_voice_roundtrip("http://127.0.0.1:8765")+ assert session.closed is Truediff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.pyindex 2ca22e627b..f10eebd232 100644--- a/tests/unit/realtime/local_server/test_supervisor.py+++ b/tests/unit/realtime/local_server/test_supervisor.py@@ -50,6 +50,37 @@ 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:+ from jarvis.realtime.local_server import install++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ root = tmp_path / "local_realtime"+ executable = root / "venv" / "Scripts" / "speech-to-speech.exe"+ executable.parent.mkdir(parents=True)+ executable.write_bytes(b"")+ command = f'"{executable}" --mode realtime'+ monkeypatch.setattr(install, "snapshot", lambda: {"running": False})+ monkeypatch.setattr(+ supervisor,+ "probe_runtime",+ lambda *args, **kwargs: {"size": 1, "in_use": 1, "available": 0},+ )+ monkeypatch.setattr(+ supervisor,+ "_stop_owned_unlocked",+ 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"++# ── Address parsing ──────────────────────────────────────────────────────def test_host_port_parses_the_configured_address() -> None:assert supervisor._host_port("http://localhost:8765") == ("localhost", 8765)@@ -952,6 +983,7 @@ def test_an_abandoned_owned_pool_is_replaced_generation_safely(from jarvis.realtime.local_server import installsupervisor._reset_for_tests()+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))root = tmp_path / "local_realtime"command = f'"{root / "venv" / "server.exe"}" --mode realtime --ws_host 127.0.0.1'generation = (4711, 1000.0, "generation-a")@@ -1500,6 +1532,69 @@ def test_managed_sweep_ignores_an_editor_opening_a_file_in_the_tree(tmp_path) ->assert supervisor._process_identity_is_managed(managed, (managed,), root)[email protected](os.name != "nt", reason="uv Windows console-script handoff")+def test_managed_identity_follows_a_uv_python_console_script(tmp_path) -> None:+ root = (tmp_path / "local_realtime").resolve()+ script = str((root / "venv" / "Scripts" / "speech-to-speech.exe").resolve())+ uv_python = str((tmp_path / "uv" / "python.exe").resolve())++ assert supervisor._process_identity_is_managed(+ uv_python,+ (uv_python, script, "--mode", "realtime"),+ root,+ )+ assert not supervisor._process_identity_is_managed(+ uv_python,+ (uv_python, str(root / "smoke_boot.log")),+ root,+ )++[email protected](os.name != "nt", reason="uv Windows console-script handoff")+def test_ready_listener_replaces_a_dead_launcher_as_owner(+ monkeypatch, tmp_path+) -> None:+ import psutil++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ root = tmp_path / "local_realtime"+ script = root / "venv" / "Scripts" / "speech-to-speech.exe"+ script.parent.mkdir(parents=True)+ script.write_bytes(b"")+ uv_python = str((tmp_path / "uv" / "python.exe").resolve())+ command = f'"{script}" --mode realtime'++ class _Process:+ pid = 8123+ info = {+ "pid": pid,+ "exe": uv_python,+ "cmdline": [uv_python, str(script), "--mode", "realtime"],+ }++ @staticmethod+ def net_connections(*, kind):+ assert kind == "inet"+ return [+ SimpleNamespace(+ status=psutil.CONN_LISTEN,+ laddr=SimpleNamespace(port=8765),+ )+ ]++ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: {"size": 1})+ monkeypatch.setattr(psutil, "process_iter", lambda attrs: [_Process()])+ monkeypatch.setattr(supervisor, "_process_create_time", lambda pid: 1234.5)++ assert supervisor.reconcile_ready_ownership(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ )+ record = supervisor._read_pidfile()+ assert record is not None+ assert record["pid"] == 8123++def test_managed_identity_keeps_a_posix_venv_python_symlink_lexical(tmp_path) -> None:if os.name == "nt":returndiff --git a/tests/unit/ui/web/test_managed_local_realtime_routes.py b/tests/unit/ui/web/test_managed_local_realtime_routes.pyindex 4b5592aedc..d6315bc51a 100644--- a/tests/unit/ui/web/test_managed_local_realtime_routes.py+++ b/tests/unit/ui/web/test_managed_local_realtime_routes.py@@ -266,33 +266,35 @@ async def test_background_warm_waits_for_managed_pool_before_brain(assert ready_kwargs["cleanup_on_timeout"] is True-def test_brain_route_rewrites_the_model_without_reinstall(- server: WebServer, monkeypatch: pytest.MonkeyPatch, tmp_path+def test_brain_route_voice_tests_before_adopting_the_model(+ server: WebServer, monkeypatch: pytest.MonkeyPatch) -> None:- from jarvis.core.config_writer import set_local_realtime_launch_command+ from jarvis.core.config import BrainProviderConfig+ from jarvis.realtime.local_server import configure- cfg_file = tmp_path / "jarvis.toml"- cfg_file.write_text("", encoding="utf-8")entrypoint = (install.install_root() / "venv" / "s.exe").as_posix()- set_local_realtime_launch_command(- f"'{entrypoint}' --mode realtime --model_name qwen2.5:7b", path=cfg_file+ old_command = f"'{entrypoint}' --mode realtime --model_name qwen2.5:7b"+ new_command = f"'{entrypoint}' --mode realtime --model_name llama3.1:8b"+ server.app.state.config.brain.providers["local-realtime"] = BrainProviderConfig(+ base_url="http://127.0.0.1:8765",+ launch_command=old_command,)monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (16.0, "nvidia-smi"))monkeypatch.setattr(brain_link, "_ollama_models", lambda base, timeout: [("llama3.1:8b", 4.9)])- # Route writes through config_writer against the real DEFAULT_CONFIG_FILE;- # redirect it at the writer level for the test.- import jarvis.core.config_writer as config_writer-- original = config_writer.update_local_realtime_launch_model+ seen: dict[str, str] = {}- def redirected(model: str, *, only_if_under: str = "", path=None) -> bool:- return original(model, only_if_under=only_if_under, path=cfg_file)+ async def tested(**kwargs):+ seen.update({key: str(value) for key, value in kwargs.items()})+ return {+ "ok": True,+ "changed": True,+ "smoke": {"audio_bytes": 4800},+ "launch_command": new_command,+ }- monkeypatch.setattr(- config_writer, "update_local_realtime_launch_model", redirected- )+ monkeypatch.setattr(configure, "apply_and_test_stack", tested)with TestClient(server.app) as client:resp = client.post("/api/providers/local-realtime/managed-server/brain",@@ -303,7 +305,12 @@ def test_brain_route_rewrites_the_model_without_reinstall(assert body["ok"] is Trueassert body["changed"] is Trueassert body["brain"]["model"] == "llama3.1:8b"- assert "--model_name llama3.1:8b" in cfg_file.read_text(encoding="utf-8")+ assert seen["brain_model"] == "llama3.1:8b"+ assert seen["voice_model"] == "qwen3-tts-1.7b"+ assert (+ server.app.state.config.brain.providers["local-realtime"].launch_command+ == new_command+ )def test_brain_models_route_lists_annotated_choices(@@ -335,6 +342,12 @@ def test_brain_route_refuses_to_swap_an_explicit_choice() -> None:"""A named model that does not fit gets an honest 409 — never a silentsubstitution (user autonomy)."""+ from jarvis.core.config import BrainProviderConfig++ entrypoint = (install.install_root() / "venv" / "s.exe").as_posix()+ server.app.state.config.brain.providers["local-realtime"] = BrainProviderConfig(+ launch_command=f"'{entrypoint}' --mode realtime --model_name qwen2.5:7b"+ )monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (16.0, "nvidia-smi"))monkeypatch.setattr(brain_link,