Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix: switch STT providers without restart

Ruben Lütke9c0319cbfdaa
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 19173c7e1f..605e762fa4 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -3281,11 +3281,12 @@ async def tts_preview(body: TtsPreviewBody) -> Response:
@router.post("/stt/switch")
async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
- """Persist the active STT provider in ``jarvis.toml``.
+ """Switch the active STT provider without restarting the app.
- The SpeechPipeline constructs STT once because loading a Whisper model is
- expensive. The selection therefore applies after the next voice or app
- restart and the response reports ``restart_required: true``.
+ A running SpeechPipeline constructs the replacement first, then swaps the
+ voice recognizer and invalidates the prompt-free dictation cache as one
+ cut-over. An in-flight transcription keeps its old provider reference and
+ finishes normally; the next transcription uses the new provider.
"""
spec = get_spec(body.provider)
if spec is None:
@@ -3316,52 +3317,96 @@ async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
if not_installed:
raise HTTPException(status_code=409, detail=not_installed)
+ cfg = _resolve_cfg(request)
+ stt_cfg = getattr(cfg, "stt", None) if cfg is not None else None
+ if stt_cfg is None:
+ raise HTTPException(status_code=503, detail="STT configuration is unavailable.")
+
+ # Pin the checkpoint the local card promised and downloaded. Cloud
+ # providers keep their model in [stt.models] and leave this value alone.
+ from jarvis.speech.local_models import get_local_provider
+
+ local_entry = get_local_provider(body.provider)
+ local_model = (
+ local_entry.model_id
+ if local_entry is not None and local_entry.runtime == "faster-whisper"
+ else None
+ )
+ old_provider = str(getattr(stt_cfg, "provider", "") or "")
+ old_model = str(getattr(stt_cfg, "model", "") or "")
+
+ pipeline = getattr(request.app.state, "speech_pipeline", None)
+ setter = getattr(pipeline, "set_stt_provider", None)
+ live_switched = False
+ if pipeline is not None:
+ if not callable(setter):
+ raise HTTPException(
+ status_code=503,
+ detail="The active speech pipeline cannot switch STT providers live.",
+ )
+ try:
+ live_switched = bool(setter(body.provider, model=local_model))
+ except Exception as exc: # noqa: BLE001 — keep the old provider alive
+ log.error("STT live switch raised unexpectedly: %s", exc, exc_info=True)
+ live_switched = False
+ if not live_switched:
+ raise HTTPException(
+ status_code=502,
+ detail=(
+ f"Provider '{body.provider}' could not be activated live. "
+ "The previous STT provider is still active."
+ ),
+ )
+ else:
+ # Voice is not running (headless / disabled), so there is no stale live
+ # object to replace. The next pipeline construction reads this value;
+ # an application restart is neither needed nor useful.
+ try:
+ stt_cfg.provider = body.provider
+ if local_model is not None:
+ stt_cfg.model = local_model
+ except Exception as exc: # noqa: BLE001 — a frozen model is not an error
+ log.debug("In-memory STT provider update skipped: %s", exc)
+
+ persisted = False
if body.persist:
try:
from jarvis.core.config_writer import set_stt_provider
set_stt_provider(body.provider)
- # Pin the checkpoint the card promised and the download fetched.
- # Without this, activating the local card would inherit whatever
- # [stt].model happened to hold (its default is a DIFFERENT Whisper
- # size), so the user would run a model they never chose — and one
- # that may not be downloaded at all.
- from jarvis.speech.local_models import get_local_provider
-
- local_entry = get_local_provider(body.provider)
- if local_entry is not None and local_entry.runtime == "faster-whisper":
+ if local_model is not None:
from jarvis.core.config_writer import set_stt_model
- set_stt_model(local_entry.model_id)
- except FileNotFoundError as exc:
- raise HTTPException(status_code=500, detail=str(exc)) from exc
- except Exception as exc: # noqa: BLE001
+ set_stt_model(local_model)
+ persisted = True
+ except Exception as exc: # noqa: BLE001 — roll live state back below
+ # Do not leave the card, live recognizer, and durable config naming
+ # three different providers when the atomic writer rejects a save.
+ try:
+ if live_switched and callable(setter):
+ setter(old_provider, model=old_model)
+ else:
+ stt_cfg.provider = old_provider
+ stt_cfg.model = old_model
+ except Exception as rollback_exc: # noqa: BLE001
+ log.error(
+ "STT live-switch rollback failed after persistence error: %s",
+ rollback_exc,
+ exc_info=True,
+ )
raise HTTPException(
- status_code=500, detail=f"TOML write failed: {exc}"
+ status_code=500, detail=f"STT provider save failed: {exc}"
) from exc
- cfg = _resolve_cfg(request)
- if cfg is not None and getattr(cfg, "stt", None) is not None:
- try:
- cfg.stt.provider = body.provider # type: ignore[attr-defined]
- # Same pin in memory, so a live restart of the speech pipeline picks
- # up the checkpoint without waiting for a config re-read.
- from jarvis.speech.local_models import get_local_provider
-
- entry = get_local_provider(body.provider)
- if entry is not None and entry.runtime == "faster-whisper":
- cfg.stt.model = entry.model_id # type: ignore[attr-defined]
- except Exception as exc: # noqa: BLE001 — a frozen model is not an error
- log.debug("In-memory STT provider update skipped: %s", exc)
-
await _emit(request, SecretConfigured(key="stt.provider", action="set"))
_invalidate_section_health_state(request)
return {
"ok": True,
"active": body.provider,
- "persisted": body.persist,
- "restart_required": True,
+ "persisted": persisted,
+ "live_switched": live_switched,
+ "restart_required": False,
}
diff --git a/tests/unit/speech/test_stt_provider_live_switch.py b/tests/unit/speech/test_stt_provider_live_switch.py
new file mode 100644
index 0000000000..3fb4f03389
--- /dev/null
+++ b/tests/unit/speech/test_stt_provider_live_switch.py
@@ -0,0 +1,156 @@
+"""Regression guards for restart-free STT provider switching."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig, STTConfig
+from jarvis.speech.pipeline import SpeechPipeline
+from jarvis.ui.web import provider_routes
+from jarvis.ui.web.server import WebServer
+
+
+class _Provider:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+
+def _bare_pipeline() -> tuple[SpeechPipeline, Any, Any]:
+ pipeline = SpeechPipeline.__new__(SpeechPipeline)
+ old_provider = _Provider("groq-api")
+ old_dictation = _Provider("faster-whisper")
+ pipeline._config = SimpleNamespace(stt=STTConfig(provider="groq-api", fallback=""))
+ pipeline._dictation_cfg = SimpleNamespace(bias_prompt="")
+ pipeline._stt = None
+ pipeline._utterance_stt = old_provider
+ pipeline._probe_stt = old_provider
+ pipeline._dictation_stt_instance = old_dictation
+ pipeline._voice_stt_fallback_chain = ("openai-api",)
+ pipeline._voice_stt_fallback_instances = {"openai-api": object()}
+ return pipeline, old_provider, old_dictation
+
+
+def test_pipeline_switch_replaces_voice_and_next_dictation_provider(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pipeline, old_provider, _old_dictation = _bare_pipeline()
+ built: list[str] = []
+
+ def _build(cfg: Any) -> _Provider:
+ built.append(str(cfg.provider))
+ return _Provider(str(cfg.provider))
+
+ monkeypatch.setattr("jarvis.plugins.stt.build_stt_from_config", _build)
+ monkeypatch.setattr("jarvis.plugins.stt.provider_runs_on_device", lambda _provider: False)
+ monkeypatch.setattr(
+ "jarvis.speech.stt_fallback.wrap_stt_with_fallback",
+ lambda provider, _cfg: provider,
+ )
+ monkeypatch.setattr(
+ "jarvis.speech.stt_dictionary.wrap_stt_with_dictionary",
+ lambda provider: provider,
+ )
+
+ assert pipeline.set_stt_provider("openrouter-stt") is True
+
+ assert pipeline._utterance_stt.name == "openrouter-stt"
+ assert pipeline._utterance_stt is not old_provider
+ assert pipeline._probe_stt is pipeline._utterance_stt
+ assert pipeline._config.stt.provider == "openrouter-stt"
+ assert pipeline._dictation_stt_instance is None
+ assert pipeline._voice_stt_fallback_chain is None
+ assert pipeline._voice_stt_fallback_instances == {}
+
+ # The dictation lane builds its own prompt-free instance lazily. Its first
+ # use after the cut-over must read the new provider, not the stale cache.
+ assert pipeline._dictation_stt().name == "openrouter-stt"
+ assert built == ["openrouter-stt", "openrouter-stt"]
+
+
+def test_pipeline_switch_failure_preserves_every_live_reference(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pipeline, old_provider, old_dictation = _bare_pipeline()
+
+ def _fail(_cfg: Any) -> Any:
+ raise RuntimeError("constructor failed")
+
+ monkeypatch.setattr("jarvis.plugins.stt.build_stt_from_config", _fail)
+
+ assert pipeline.set_stt_provider("openrouter-stt") is False
+ assert pipeline._utterance_stt is old_provider
+ assert pipeline._probe_stt is old_provider
+ assert pipeline._dictation_stt_instance is old_dictation
+ assert pipeline._config.stt.provider == "groq-api"
+
+
+def web_server() -> Iterator[WebServer]:
+ cfg = JarvisConfig()
+ cfg.stt.provider = "groq-api"
+ server = WebServer(cfg, bus=EventBus())
+ yield server
+
+
+class _LivePipeline:
+ def __init__(self, cfg: JarvisConfig) -> None:
+ self.cfg = cfg
+ self.calls: list[tuple[str, str | None]] = []
+
+ def set_stt_provider(self, provider: str, *, model: str | None = None) -> bool:
+ self.calls.append((provider, model))
+ self.cfg.stt.provider = provider
+ return True
+
+
+def test_switch_route_applies_to_running_pipeline_without_restart(
+ web_server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pipeline = _LivePipeline(web_server.cfg)
+ web_server.app.state.speech_pipeline = pipeline
+ writes: list[str] = []
+ monkeypatch.setattr(provider_routes, "_is_credential_present", lambda _spec: True)
+ monkeypatch.setattr("jarvis.brain.app_control.local_readiness_error", lambda _spec: None)
+ monkeypatch.setattr("jarvis.core.config_writer.set_stt_provider", writes.append)
+
+ with TestClient(web_server.app) as client:
+ response = client.post(
+ "/api/stt/switch",
+ json={"provider": "openrouter-stt", "persist": True},
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "ok": True,
+ "active": "openrouter-stt",
+ "persisted": True,
+ "live_switched": True,
+ "restart_required": False,
+ }
+ assert pipeline.calls == [("openrouter-stt", None)]
+ assert web_server.cfg.stt.provider == "openrouter-stt"
+ assert writes == ["openrouter-stt"]
+
+
+def test_switch_route_never_requests_restart_when_voice_is_not_running(
+ web_server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(provider_routes, "_is_credential_present", lambda _spec: True)
+ monkeypatch.setattr("jarvis.brain.app_control.local_readiness_error", lambda _spec: None)
+
+ with TestClient(web_server.app) as client:
+ response = client.post(
+ "/api/stt/switch",
+ json={"provider": "openrouter-stt", "persist": False},
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["live_switched"] is False
+ assert response.json()["restart_required"] is False
+ assert web_server.cfg.stt.provider == "openrouter-stt"