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(stt): honor the user-selected provider
Ruben Lütkecc811d40890d
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 1b733dd6b4..6bdb4a6106 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -428,6 +428,12 @@ class TriggerConfig(BaseModel):class STTConfig(BaseModel):provider: str = "groq-api"+ # Set by every user-facing provider switch. Once present, the persisted+ # provider is authoritative over a stale JARVIS__STT__PROVIDER inherited+ # from an older desktop process or User-scope environment entry. Fresh+ # headless installs keep the normal ENV-over-TOML contract until a user+ # explicitly chooses a provider through Jarvis.+ provider_user_selected: bool = False# Where transcription goes when ``provider`` keeps failing at RUNTIME — a# depleted or revoked key (401/402), or a rate limit that survives the# retry ladder. ``auto`` (the default) asks the key-aware resolver for a@@ -3689,10 +3695,21 @@ def _apply_env_overrides(data: dict[str, Any], prefix: str = "JARVIS__") -> dictExample: JARVIS__BRAIN__PRIMARY=openrouter → config["brain"]["primary"]"""+ stt_section = data.get("stt")+ stt_provider_user_selected = bool(+ isinstance(stt_section, dict)+ and stt_section.get("provider_user_selected") is True+ )for env_key, env_val in tuple(os.environ.items()):if not env_key.startswith(prefix):continuepath = env_key[len(prefix):].lower().split("__")+ if path == ["stt", "provider"] and stt_provider_user_selected:+ logging.getLogger(__name__).debug(+ "Ignoring %s because the persisted STT provider was user-selected",+ env_key,+ )+ continuecursor = datablocked = Falsefor segment in path[:-1]:diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 7cd80d3a47..2295665189 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -413,8 +413,16 @@ def set_stt_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:drift-guard reverts it within 5 minutes. Layers 2 + 3 are best-effort(cloud-first) and never break the TOML write."""- # Layer 1 — universal, runs on every platform. May raise FileNotFoundError.- _patch_table(path, "stt", "provider", name)+ # Layer 1 — universal, runs on every platform. The marker lands in the+ # same atomic write and makes this explicit user choice authoritative over+ # a stale provider override inherited by a later desktop process.+ _patch_table(+ path,+ "stt",+ "provider",+ name,+ extra={"provider_user_selected": True},+ )# Layers 2 + 3 — best-effort, never raise._sync_stt_provider_drift_soll(name) # i18n-allowdiff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex e5358257d2..e82cc35e98 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -657,13 +657,9 @@ def _stt_crossover_would_leave_the_machine() -> bool:def _resolve_stt_fallback_chain(stt_cfg: Any, configured: str) -> tuple[str, ...]:"""Provider ids to cross to when ``configured`` fails at CALL time.- The ONE place ``[stt].fallback`` is interpreted, and the reason it exists is- that the key was shipped in configs for a long time while nothing read it —- a switch whose value is ignored is a lie the user cannot detect (AP-31), and- it was documented in ``STTConfig`` as honoured. Both consumers — the- dictation lane's session chain and the voice lane's last-resort crossover —- resolve through here, because two readings of one switch are two readings- that will drift.+ Both consumers use ``configured_fallback_names`` for the setting semantics,+ so the utterance wrapper and this last-resort resolver cannot disagree about+ whether fallback is automatic, pinned, or disabled (AP-31).Three settings, all of them the user's call:@@ -694,19 +690,11 @@ def _resolve_stt_fallback_chain(stt_cfg: Any, configured: str) -> tuple[str, ...unimportable plugin package or an unreadable keyring costs the crossover,never the transcription. Names only, nothing built (AP-26)."""+ from jarvis.speech.stt_fallback import configured_fallback_names+setting = str(getattr(stt_cfg, "fallback", "auto") or "").strip()- if not setting:- log.debug("STT crossover disabled by [stt].fallback = '' (empty).")- return ()if setting.lower() != "auto":- if setting == configured:- log.debug(- "STT crossover pinned to the configured provider %r — the same "- "failure twice is not a fallback; ignoring the pin.",- setting,- )- return ()- return (setting,)+ return configured_fallback_names(stt_cfg, configured, ())if _stt_crossover_would_leave_the_machine():log.info("STT crossover declined: [stt].provider = %s transcribes on this "@@ -721,7 +709,11 @@ def _resolve_stt_fallback_chain(stt_cfg: Any, configured: str) -> tuple[str, ...try:from jarvis.plugins.stt import resolve_keyed_stt_fallback- return tuple(resolve_keyed_stt_fallback(configured))+ return configured_fallback_names(+ stt_cfg,+ configured,+ resolve_keyed_stt_fallback(configured),+ )except Exception as exc: # noqa: BLE001 — no chain is worse than no transcriptlog.warning("STT crossover chain could not be resolved (%s); this transcription "diff --git a/jarvis/speech/stt_fallback.py b/jarvis/speech/stt_fallback.pyindex 0ba2173d4f..ebb95ea4c3 100644--- a/jarvis/speech/stt_fallback.py+++ b/jarvis/speech/stt_fallback.py@@ -267,6 +267,25 @@ def alternate_provider_names(configured: str, available: Sequence[str]) -> list[return ordered+def configured_fallback_names(+ stt_cfg: Any,+ configured: str,+ automatic: Sequence[str],+) -> tuple[str, ...]:+ """Apply the user's ``[stt].fallback`` setting to an automatic chain.++ An empty setting disables crossover, a concrete provider pins exactly that+ provider, and ``auto`` keeps the key-aware chain supplied by the caller.+ The selected provider is never repeated as its own fallback.+ """+ setting = str(getattr(stt_cfg, "fallback", "auto") or "").strip()+ if not setting:+ return ()+ if setting.lower() != "auto":+ return () if setting == configured else (setting,)+ return tuple(name for name in automatic if name != configured)++def wrap_stt_with_fallback(provider: Any, stt_cfg: Any) -> Any:"""Wrap ``provider`` in a :class:`FallbackSTT` over the user's other keys.@@ -283,8 +302,10 @@ def wrap_stt_with_fallback(provider: Any, stt_cfg: Any) -> Any:)configured = (getattr(stt_cfg, "provider", "") or "").strip()- alternates = alternate_provider_names(- configured, available_stt_provider_names()+ alternates = configured_fallback_names(+ stt_cfg,+ configured,+ alternate_provider_names(configured, available_stt_provider_names()),)if not alternates:return provider@@ -310,5 +331,6 @@ __all__ = ["RATE_LIMIT_COOLDOWN_S","TRANSIENT_COOLDOWN_S","alternate_provider_names",+ "configured_fallback_names","wrap_stt_with_fallback",]diff --git a/scripts/jarvis-config-drift-guard.ps1 b/scripts/jarvis-config-drift-guard.ps1index bda1416cda..9dade0f41f 100644--- a/scripts/jarvis-config-drift-guard.ps1+++ b/scripts/jarvis-config-drift-guard.ps1@@ -95,6 +95,34 @@ try {exit 4}+# A provider chosen through Jarvis is the authoritative STT selection. Older+# desktop processes may have left a different User-scope environment value or+# desired-state entry behind; repairing TOML from either would silently undo+# the user's explicit choice. Use the marked TOML provider as the in-memory+# desired value for both comparisons. The writer normally keeps all layers in+# sync, while this protects the partial-write and stale-process edge cases.+$tomlSnapshot = Get-Content -Path $tomlFile -Raw -Encoding utf8+$sttSectionMatch = [regex]::Match($tomlSnapshot, '(?ms)^\[stt\][^\[]*')+if ($sttSectionMatch.Success) {+ $sttSectionBody = $sttSectionMatch.Value+ $selectionMarker = [regex]::Match(+ $sttSectionBody,+ '(?im)^\s*provider_user_selected\s*=\s*true\b'+ )+ $selectedProvider = [regex]::Match(+ $sttSectionBody,+ '(?m)^\s*provider\s*=\s*"([^"]+)"'+ )+ if (+ $selectionMarker.Success -and+ $selectedProvider.Success -and+ $null -ne $desired.stt -and+ $null -ne $desired.stt.PSObject.Properties['provider']+ ) {+ $desired.stt.provider = $selectedProvider.Groups[1].Value+ }+}+# A JARVIS__SECTION__KEY override can represent one scalar only. PowerShell# stringifies nested JSON objects as "@{key=value}"; Python then receives a# string where the config schema expects a mapping and the desktop app cannotdiff --git a/tests/unit/core/test_stt_provider_precedence.py b/tests/unit/core/test_stt_provider_precedence.pynew file mode 100644index 0000000000..cc0224426b--- /dev/null+++ b/tests/unit/core/test_stt_provider_precedence.py@@ -0,0 +1,42 @@+"""The user's explicit STT provider choice is authoritative at boot."""++from __future__ import annotations++import pytest++from jarvis.core import config as config_module+from jarvis.core.config import STTConfig+from jarvis.ui.web.provider_spec import PROVIDERS++STT_PROVIDER_IDS = tuple(spec.id for spec in PROVIDERS if spec.tier == "stt")++[email protected]("selected", STT_PROVIDER_IDS)+def test_user_selected_provider_ignores_a_stale_environment_override(+ selected: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ stale = next(provider for provider in STT_PROVIDER_IDS if provider != selected)+ monkeypatch.setenv("JARVIS__STT__PROVIDER", stale)+ data = {+ "stt": {+ "provider": selected,+ "provider_user_selected": True,+ }+ }++ result = config_module._apply_env_overrides(data)++ assert result["stt"]["provider"] == selected+++def test_headless_environment_override_still_works_without_a_user_selection(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("JARVIS__STT__PROVIDER", "openai-api")+ data = {"stt": {"provider": "faster-whisper"}}++ result = config_module._apply_env_overrides(data)++ assert result["stt"]["provider"] == "openai-api"+ assert STTConfig().provider_user_selected is Falsediff --git a/tests/unit/scripts/test_drift_guard_brain_primary_contract.py b/tests/unit/scripts/test_drift_guard_brain_primary_contract.pyindex fcafd325b9..4587f07818 100644--- a/tests/unit/scripts/test_drift_guard_brain_primary_contract.py+++ b/tests/unit/scripts/test_drift_guard_brain_primary_contract.py@@ -193,3 +193,66 @@ def test_structured_stt_models_never_becomes_one_env_override(assert toml_file.read_text(encoding="utf-8") == ('[stt.models]\nopenrouter-stt = "openai/gpt-4o-transcribe"\n')+++def test_user_selected_stt_provider_survives_stale_desired_state(+ tmp_path: Path,+) -> None:+ """The guard heals stale ENV toward the user's selection, never away."""+ powershell = shutil.which("powershell") or shutil.which("pwsh")+ if powershell is None:+ pytest.skip("PowerShell is unavailable")++ guard = (+ Path(__file__).resolve().parents[3]+ / "scripts"+ / "jarvis-config-drift-guard.ps1"+ )+ sandbox = tmp_path / "repo"+ sandbox.mkdir()+ desired_file = sandbox / "desired.json"+ desired_file.write_text(+ json.dumps({"stt": {"provider": "groq-api"}}),+ encoding="utf-8",+ )+ toml_file = sandbox / "jarvis.toml"+ expected = (+ '[stt]\nprovider = "openrouter-stt"\nprovider_user_selected = true\n'+ )+ toml_file.write_text(expected, encoding="utf-8")+ env = os.environ.copy()+ env["JARVIS__STT__PROVIDER"] = "groq-api"++ result = subprocess.run(+ [+ powershell,+ "-NoProfile",+ "-ExecutionPolicy",+ "Bypass",+ "-File",+ str(guard),+ "-RepoRoot",+ str(sandbox),+ "-DesiredFile",+ str(desired_file),+ "-EnvironmentTarget",+ "Process",+ ],+ cwd=sandbox,+ env=env,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=30,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )++ assert result.returncode == 0, result.stdout + result.stderr+ log = (sandbox / "logs" / "config-drift-guard.log").read_text(+ encoding="utf-8-sig"+ )+ assert "JARVIS__STT__PROVIDER := 'openrouter-stt'" in log+ assert "[stt] provider: actual='openrouter-stt' desired='groq-api'" not in log+ assert toml_file.read_text(encoding="utf-8") == expecteddiff --git a/tests/unit/speech/test_stt_fallback.py b/tests/unit/speech/test_stt_fallback.pyindex b866f6f910..88651fc366 100644--- a/tests/unit/speech/test_stt_fallback.py+++ b/tests/unit/speech/test_stt_fallback.py@@ -13,8 +13,10 @@ import pytestfrom jarvis.core.protocols import Transcriptfrom jarvis.plugins.stt import _STT_CROSS_FAMILY_ORDERfrom jarvis.speech.stt_fallback import (+ RATE_LIMIT_COOLDOWN_S,FallbackSTT,alternate_provider_names,+ configured_fallback_names,wrap_stt_with_fallback,)@@ -60,6 +62,35 @@ async def test_rate_limit_crosses_to_the_next_provider():assert backup.calls == 1+ "selected",+ (+ "openrouter-stt",+ "openai-api",+ "gemini-api",+ "groq-api",+ "faster-whisper",+ "nemotron-local",+ ),+)+async def test_every_healthy_user_selected_provider_stays_primary(selected: str):+ primary = FakeSTT(text="selected")+ backup = FakeSTT(text="fallback")+ chain = FallbackSTT(+ primary,+ ["emergency-stt"],+ lambda _name: backup,+ primary_name=selected,+ )++ result = await chain.transcribe_pcm(b"x")++ assert result.text == "selected"+ assert chain.last_used_provider == selected+ assert primary.calls == 1+ assert backup.calls == 0++async def test_fallback_exposes_the_model_that_actually_answered():primary = FakeSTT(error=RuntimeError("429 Too Many Requests"))primary._model = "whisper-large-v3-turbo"@@ -137,6 +168,25 @@ async def test_a_rate_limited_provider_is_skipped_on_the_next_call():assert backup.calls == 2+async def test_selected_provider_returns_after_its_emergency_cooldown(monkeypatch):+ import jarvis.speech.stt_fallback as fallback_mod++ now = 0.0+ monkeypatch.setattr(fallback_mod.time, "monotonic", lambda: now)+ primary = FakeSTT(error=RuntimeError("429 Too Many Requests"))+ backup = FakeSTT(text="temporary fallback")+ chain = _chain(primary, **{"openai-api": backup})++ assert (await chain.transcribe_pcm(b"x")).text == "temporary fallback"+ primary.error = None+ primary.text = "selected provider restored"+ now = RATE_LIMIT_COOLDOWN_S + 1.0++ assert (await chain.transcribe_pcm(b"x")).text == "selected provider restored"+ assert primary.calls == 2+ assert backup.calls == 1++async def test_a_cooling_provider_is_still_the_last_resort():"""Skipped is not dropped: with every alternate dead it gets the last word."""primary = FakeSTT(text="from the configured provider")@@ -215,6 +265,26 @@ def test_a_single_key_install_is_not_wrapped():stt_mod.available_stt_provider_names = original+def test_empty_fallback_setting_disables_the_runtime_wrapper():+ class Cfg:+ provider = "openrouter-stt"+ fallback = ""++ provider = FakeSTT(text="x")+ assert wrap_stt_with_fallback(provider, Cfg()) is provider+++def test_concrete_fallback_setting_pins_exactly_one_provider():+ class Cfg:+ fallback = "gemini-api"++ assert configured_fallback_names(+ Cfg(),+ "openrouter-stt",+ ("openai-api", "groq-api"),+ ) == ("gemini-api",)++def test_attributes_delegate_to_the_provider_in_front():"""Duck-typed callers (recover(), is_warm, model fields) keep working."""primary = FakeSTT(text="x")diff --git a/tests/unit/test_config_writer_stt_sync.py b/tests/unit/test_config_writer_stt_sync.pyindex ce63fdbf1b..11738b9911 100644--- a/tests/unit/test_config_writer_stt_sync.py+++ b/tests/unit/test_config_writer_stt_sync.py@@ -74,7 +74,9 @@ def test_set_stt_provider_writes_all_three_layers(config_writer.set_stt_provider("faster-whisper", path=sample_toml)# Layer 1: TOML.- assert 'provider = "faster-whisper"' in sample_toml.read_text(encoding="utf-8")+ toml_text = sample_toml.read_text(encoding="utf-8")+ assert 'provider = "faster-whisper"' in toml_text+ assert "provider_user_selected = true" in toml_text# Layer 2: config-soll.json stt.provider. # i18n-allowsoll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow