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): give every provider a classifiable error and a real timeout
Ruben Lütkeab60cfd0ea93
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.pyindex 7772757a9c..0a41ca3ed0 100644--- a/jarvis/plugins/stt/__init__.py+++ b/jarvis/plugins/stt/__init__.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport jsonimport osimport time+from collections.abc import Iterablefrom functools import lru_cachefrom importlib import metadata as importlib_metadatafrom pathlib import Path@@ -58,6 +59,13 @@ _STT_CROSS_FAMILY_ORDER: tuple[str, ...] = ("groq-api", "openrouter-stt", "openai-api", "gemini-api",)+# Constructor kwargs the factory offers but no provider is required to accept.+# A plugin that predates one of them raises TypeError, and the build retries+# with every one of them dropped rather than falling all the way through to the+# local engine a base install does not ship. Anything NOT listed here (the+# language, the team-proxy endpoint/key) is load-bearing and never dropped.+_OPTIONAL_PROVIDER_KWARGS: tuple[str, ...] = ("prompt", "timeout_s")+def _stt_has_credential(provider_name: str, kwargs: dict[str, Any]) -> bool:"""Whether the configured cloud STT has a usable key (else: fall to local).@@ -129,6 +137,102 @@ def _resolve_keyed_stt_provider(primary_name: str) -> str:return primary_name+def stt_family_id(provider_name: str) -> str:+ """The CREDENTIAL family a provider id belongs to.++ "Family" is defined by the credential slot, never by the provider NAME+ (AP-21). What makes a fallback worthless is landing on a provider that draws+ on the SAME key as the one that just answered 429 / 402 / 401: a depleted or+ rejected credential is not rescued by a sibling id that reads the same+ keyring entry. Two ids that resolve the same primary secret are therefore+ ONE family, however differently they are spelled — which is exactly the+ trap ``openrouter`` (brain) vs ``openrouter-stt`` (STT) would set for a+ naive name comparison.++ Unknown / third-party ids (absent from ``_STT_SECRET_CANDIDATES``) are each+ their own family: we cannot prove they share a credential with anything, and+ excluding them would silently drop a provider that works. The key-free local+ engine is the ``local`` family — it has no credential to exhaust.+ """+ name = (provider_name or "").strip()+ if not name:+ return ""+ if name == "faster-whisper":+ return "local"+ candidates = _STT_SECRET_CANDIDATES.get(name)+ if not candidates:+ return name+ return candidates[0][0]+++def resolve_keyed_stt_fallback(+ current_id: str,+ *,+ exclude_family: str | Iterable[str] = (),+) -> tuple[str, ...]:+ """Cloud STT providers to cross to when ``current_id`` fails at CALL time.++ The runtime half of AP-22. ``_resolve_keyed_stt_provider`` above decides at+ BUILD time and only when a key is entirely MISSING; a provider that has a+ key and then returns 429 / 402 / 401 mid-session was, until this existed,+ the end of the transcription — even with three other keyed families sitting+ unused. Mirrors the TTS tier's ``resolve_keyed_fallback``+ (``jarvis/plugins/tts/__init__.py``), which the TTS plugins have called from+ their real error handlers for months.++ Returns provider ids, in the shipped cross-family order, that are ALL of:++ * from a different family than ``current_id`` (and than every entry in+ ``exclude_family`` — pass the families a session already burned so a long+ dictation does not walk back into one that is still rate-limited);+ * one entry per family, never two ids drawing on the same credential;+ * backed by a credential this host actually holds, AND registered as a+ ``jarvis.stt`` entry-point — we never promise a provider we cannot build.++ ``exclude_family`` accepts a single value or an iterable, and each value may+ be a provider id or a family id from :func:`stt_family_id`.++ An empty tuple is the honest answer, not an error: this user has exactly one+ keyed STT family and the caller must degrade the way it always has (an+ honest message, or the key-free local floor via ``_build_local_fallback`` /+ ``jarvis.speech.stt_fallback.alternate_provider_names``, which is the one+ option no quota can take away). The local engine is deliberately NOT in this+ chain — it is a floor, not a family, and it is absent on a base install.++ Names only, nothing built: constructing an alternate here would put a model+ load on whatever path called us (AP-26). The caller builds the one it needs+ via ``build_named_stt_provider`` and keeps it. The caller also owns the+ user-facing message; this function stays quiet so a per-failure call cannot+ turn into log spam.+ """+ excluded = {stt_family_id(current_id)}+ if isinstance(exclude_family, str):+ exclude_family = (exclude_family,)+ for name in exclude_family:+ family = stt_family_id(str(name))+ if family:+ excluded.add(family)+ excluded.discard("")++ chain: list[str] = []+ seen: set[str] = set()+ for cand in _STT_CROSS_FAMILY_ORDER:+ family = stt_family_id(cand)+ if family in excluded or family in seen:+ continue+ if not _stt_family_has_key(cand) or _load_provider_class(cand) is None:+ continue+ seen.add(family)+ chain.append(cand)+ logger.debug(+ "STT runtime fallback for {!r} (excluding {}): {}",+ current_id,+ sorted(excluded),+ ", ".join(chain) or "<none — this host has one keyed STT family>",+ )+ return tuple(chain)++def _load_provider_class(name: str) -> type | None:"""Resolve an STT provider class by its entry-point ``name`` (e.g. ``groq-api``)."""eps = importlib_metadata.entry_points()@@ -190,6 +294,22 @@ def build_stt_from_config(stt_cfg: Any) -> Any:kwargs["language"] = languageif bias_prompt:kwargs["prompt"] = bias_prompt+ # Per-request timeout. Forwarded only when the config actually carries+ # one, so every provider keeps its own documented default otherwise. It+ # matters most for Gemini: google-genai FORCES ``timeout=None`` on its+ # HTTP client unless it is told otherwise, and its call runs in an+ # uncancellable thread — so without a value arriving here there is no+ # layer left that could bound the request (the pipeline's ``wait_for``+ # stops waiting, it cannot stop the thread).+ timeout_s = getattr(stt_cfg, "timeout_s", None)+ try:+ if timeout_s is not None and float(timeout_s) > 0:+ kwargs["timeout_s"] = float(timeout_s)+ except (TypeError, ValueError):+ logger.debug(+ "STT timeout_s {!r} is not a number; using the provider default.",+ timeout_s,+ )# Team-proxy mode (2026-06-20 spec §4): route the cloud STT through the# key proxy with the per-user token instead of the real vendor key. Only# groq-api (the cloud STT exposing `endpoint` + `api_key` constructor@@ -222,16 +342,22 @@ def build_stt_from_config(stt_cfg: Any) -> Any:)return instanceexcept TypeError as exc:- # The provider class refused one of our kwargs — most likely because- # it predates the bias_prompt addition. Retry without it so a stale- # third-party plugin still loads. (faster-whisper local path is- # handled below as the explicit fallback.)- if "prompt" in kwargs:- kwargs.pop("prompt", None)+ # The provider class refused one of our OPTIONAL kwargs — most+ # likely a third-party plugin that predates ``prompt`` or+ # ``timeout_s``. Retry with all of them dropped (we cannot tell from+ # a TypeError WHICH one offended) so a stale plugin still loads;+ # only ``language`` and the proxy pair are load-bearing.+ # (faster-whisper local path is handled below as the explicit+ # fallback.)+ refused = [k for k in _OPTIONAL_PROVIDER_KWARGS if k in kwargs]+ if refused:+ for key in refused:+ kwargs.pop(key, None)logger.warning(- "STT provider {!r} does not accept bias_prompt yet ({}); "- "retrying without it.",+ "STT provider {!r} does not accept {} yet ({}); retrying "+ "without those.",provider_name,+ " / ".join(refused),exc,)try:@@ -940,6 +1066,8 @@ __all__ = ["build_stt_from_config","build_wake_whisper","mark_wake_gpu_bad",+ "resolve_keyed_stt_fallback","start_wake_model_prefetch",+ "stt_family_id","wake_gpu_probe_cached",]diff --git a/jarvis/plugins/stt/errors.py b/jarvis/plugins/stt/errors.pynew file mode 100644index 0000000000..3f0c88b156--- /dev/null+++ b/jarvis/plugins/stt/errors.py@@ -0,0 +1,249 @@+"""One classifiable HTTP error shape for every cloud STT plugin.++WHY THIS EXISTS. The speech pipeline decides whether a failed transcription is+worth another attempt from the HTTP status behind it — 429 and 5xx are a blip+worth retrying, 401 (dead key) and 400 (bad audio) are not — and it decides how+long to wait from the server's ``Retry-After``. It could only ever read those+facts off an ``httpx.HTTPStatusError``, which exactly ONE of the four cloud STT+plugins raised. The other three flattened every status into a bare+``RuntimeError``, so the whole retry ladder was dead code for them: whoever's+key was not a Groq key lost the entire turn to the first rate limit, while+those plugins' own docstrings promised they "degrade honestly (AP-22)". That is+AP-23 in miniature — the maintainer's provider was the only one that worked.++``STTHTTPError`` carries the two machine-readable facts a caller needs (the+``status`` and the requested ``retry_after`` in seconds) and stays a+``RuntimeError``, so every existing ``except RuntimeError`` / "degrade to the+key-free local floor" path behaves exactly as it does today; only code that+WANTS the status has to know this type exists.++It also keeps the legacy ``exc.response.status_code`` / ``exc.response.headers``+shape alive (see :class:`_ErrorResponseView`). That is deliberate, not+nostalgia: a typed ``.status`` that only a future consumer reads would have left+the retry ladder just as dead as it is now, whereas mirroring the shape the+current consumer already duck-types makes all four providers classifiable the+moment they raise this.++Deliberately dependency-free — no ``httpx``, no ``jarvis.*``. The plugin modules+stay import-clean (the entry-point contract), response objects are duck-typed+rather than imported, and a caller holding nothing but a status code can still+raise a useful error.+"""+from __future__ import annotations++from collections.abc import Mapping+from datetime import UTC, datetime+from email.utils import parsedate_to_datetime+from typing import Any++__all__ = [+ "STTHTTPError",+ "http_error_from_response",+ "parse_retry_after",+ "status_from_exception",+]+++def parse_retry_after(value: Any, *, now: float | None = None) -> float | None:+ """Seconds to wait, read from a ``Retry-After`` header value.++ RFC 9110 allows TWO forms and real providers send both: a delta in seconds+ (``"30"``) and an HTTP-date (``"Wed, 21 Oct 2015 07:28:00 GMT"``). The+ OpenAI-compatible audio APIs send the delta form; a gateway or CDN sitting+ in front of one of them sends the date form. Understanding only one of them+ means silently falling back to blind exponential backoff for half the+ install base — the kind of "works for me" gap AP-23 is about — so both are+ handled here, once, instead of in four plugins.++ ``now`` (epoch seconds) exists so the date branch is testable without+ waiting for a clock. Returns ``None`` for an absent or unparseable value and+ NEVER raises: a malformed header must degrade to the caller's own backoff,+ not kill the turn. A date already in the past (or a skewed clock) clamps to+ ``0.0`` — "retry now", never a negative sleep.+ """+ if value is None:+ return None+ raw = str(value).strip()+ if not raw:+ return None+ try:+ return max(0.0, float(raw))+ except ValueError:+ pass+ try:+ when = parsedate_to_datetime(raw)+ except (TypeError, ValueError):+ return None+ if when is None: # pragma: no cover — older stdlib returned None instead+ return None+ if when.tzinfo is None:+ # An HTTP-date with no zone is UTC by definition (RFC 9110 §5.6.7).+ when = when.replace(tzinfo=UTC)+ reference = datetime.now(UTC) if now is None else datetime.fromtimestamp(now, tz=UTC)+ return max(0.0, (when - reference).total_seconds())+++def status_from_exception(exc: BaseException | None) -> int | None:+ """The HTTP status behind ``exc``, or ``None`` when it is not an HTTP error.++ Duck-typed across the three shapes the STT tier actually sees, in order of+ precision: our own :class:`STTHTTPError` (``.status``), the google-genai+ SDK's ``APIError`` (``.code`` — an int status, and the SDK is NOT importable+ on a base install, so it can only ever be duck-typed), and the+ ``httpx.HTTPStatusError`` family (``.response.status_code``). Anything else+ — a transport error, a timeout, a bug — is not an HTTP status and returns+ ``None`` so the caller treats it as such rather than inventing one.+ """+ if exc is None:+ return None+ for candidate in (+ getattr(exc, "status", None),+ getattr(exc, "code", None),+ getattr(getattr(exc, "response", None), "status_code", None),+ ):+ if isinstance(candidate, bool):+ # ``True`` is an int in Python; a boolean flag is never a status.+ continue+ if isinstance(candidate, int) and 100 <= candidate <= 599:+ return candidate+ return None+++class _ErrorHeaders(Mapping):+ """Case-insensitive, read-only COPY of a failed response's headers.++ A copy, not the live response: an exception can outlive the call that+ produced it (it is stored, re-raised, logged), and pinning the provider's+ response object inside it would keep its buffers — and on some clients its+ connection — alive far past the request. Case-insensitivity is not a nicety+ either: HTTP header names are case-insensitive and providers genuinely vary+ between ``Retry-After`` and ``retry-after``, so a case-sensitive lookup+ silently loses the delay for half of them.+ """++ __slots__ = ("_items",)++ def __init__(self, source: Any = None) -> None:+ items: dict[str, str] = {}+ try:+ pairs = source.items() if hasattr(source, "items") else (source or ())+ for key, value in pairs:+ items[str(key).lower()] = str(value)+ except Exception: # noqa: BLE001 — unreadable headers must not mask the error+ items = {}+ self._items = items++ def __getitem__(self, key: str) -> str:+ return self._items[str(key).lower()]++ def __iter__(self): # noqa: ANN204 — Mapping protocol+ return iter(self._items)++ def __len__(self) -> int:+ return len(self._items)++ def __repr__(self) -> str: # pragma: no cover — logging nicety+ return f"_ErrorHeaders({self._items!r})"+++class _ErrorResponseView:+ """The two response facts a caller needs, without the response object.++ Exposed on the exception as ``.response`` ON PURPOSE. The pipeline's current+ classifier reads ``exc.response.status_code`` and its backoff reads+ ``exc.response.headers.get("retry-after")`` — the ``httpx.HTTPStatusError``+ shape Groq alone used to raise. Mirroring exactly those two attributes is+ what turns the other three plugins from unclassifiable into classifiable+ without a coordinated change on the consumer side, and it keeps Groq's+ behaviour bit-for-bit identical when it starts raising this type instead.+ """++ __slots__ = ("headers", "status_code")++ def __init__(self, status_code: int, headers: Any = None) -> None:+ self.status_code = status_code+ self.headers = _ErrorHeaders(headers)+++class STTHTTPError(RuntimeError):+ """A cloud STT provider answered with an HTTP error status.++ ``status`` is that status. ``retry_after`` is the delay the server asked+ for, in SECONDS, or ``None`` when it asked for none (or asked+ unintelligibly) — the caller then uses its own backoff. When it is not+ passed explicitly it is read from the response's ``Retry-After`` header, so+ a plugin only has to hand over the headers it already has.++ The message stays the plugin's own English sentence: this type ADDS+ machine-readable facts, it never replaces the human-readable reason a user+ or a log reader sees. Subclassing ``RuntimeError`` keeps every existing+ handler (the STT factory's local-floor fallback, the pipeline's honest+ apology) working unchanged.+ """++ def __init__(+ self,+ message: str,+ *,+ status: int,+ retry_after: float | None = None,+ headers: Any = None,+ ) -> None:+ super().__init__(message)+ self.status = int(status)+ self.response = _ErrorResponseView(self.status, headers)+ if retry_after is None:+ retry_after = parse_retry_after(self.response.headers.get("retry-after"))+ self.retry_after = None if retry_after is None else max(0.0, float(retry_after))+++def _error_detail(response: Any) -> str:+ """The provider's own explanation for a failure, best-effort.++ These APIs answer with ``{"error": {"message": ...}}`` (or occasionally a+ plain string), but an overloaded gateway answers with HTML — so a JSON parse+ failure falls back to a short slice of the raw body instead of dropping the+ only clue the user gets. Never raises.+ """+ try:+ payload = response.json()+ except Exception: # noqa: BLE001 — body may not be JSON at all+ try:+ return (getattr(response, "text", "") or "").strip()[:200]+ except Exception: # noqa: BLE001 — an unreadable body is simply no detail+ return ""+ if isinstance(payload, dict):+ err = payload.get("error")+ if isinstance(err, dict):+ return str(err.get("message", "")).strip()+ if isinstance(err, str):+ return err.strip()+ return ""+++def http_error_from_response(response: Any, *, vendor: str) -> STTHTTPError:+ """Build the typed error for an HTTP error ``response`` from ``vendor``.++ One helper for every OpenAI-shaped STT plugin, so four plugins cannot drift+ into four different sentences for the same 429 — and so a fifth plugin gets+ the classification for free instead of re-deriving it. The wording is+ exactly what those plugins already shipped (``"<vendor> STT failed:+ <reason> (<detail>)"``); only the TYPE changed.++ ``response`` is duck-typed (``status_code`` / ``headers`` / ``json()`` /+ ``text``), so this module needs no HTTP client of its own and a test can+ hand it a plain stub.+ """+ status = int(getattr(response, "status_code", 0) or 0)+ reason = {+ 401: f"invalid or missing {vendor} API key",+ 402: f"{vendor} account out of credit",+ 429: f"{vendor} rate limit / quota exceeded",+ }.get(status, f"{vendor} STT HTTP {status}")+ message = f"{vendor} STT failed: {reason}"+ detail = _error_detail(response)+ if detail:+ message = f"{message} ({detail})"+ return STTHTTPError(+ message, status=status, headers=getattr(response, "headers", None)+ )diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.pyindex fbff920e83..c32b144f16 100644--- a/jarvis/plugins/stt/fwhisper.py+++ b/jarvis/plugins/stt/fwhisper.py@@ -153,6 +153,32 @@ def _multilingual_equivalent(model: str) -> str | None:return None+def _is_english_only(model: str) -> bool:+ """True when ``model`` is a checkpoint that only ever produces English."""+ return _multilingual_equivalent(model) is not None+++#: The per-call ``language`` value that REQUESTS detection. Spelled out here (and+#: in every other STT plugin) because plugins may not import from ``jarvis.*``.+AUTO_LANGUAGE = "auto"+++def _detect_or(language: str | None, configured: str | None) -> str | None:+ """The language for ONE call. ``None`` means "let the model detect".++ Three cases, and the middle one is the whole point:++ * a concrete code (``"de"``) — transcribe as that language;+ * ``"auto"`` — an explicit request to DETECT, which clears ``configured`` for+ this call. Treating it as "no argument given" is what let dictation's auto+ mode inherit ``[stt].language`` and write German speech in English;+ * ``None`` / empty — no per-call opinion, so the configured pin stands.+ """+ if language is None or not str(language).strip():+ return configured+ return None if str(language).strip().lower() == AUTO_LANGUAGE else str(language)++def _cpu_safe_compute_type(compute_type: str) -> str:"""Downgrade CUDA-only compute types to a CPU-compatible one.@@ -364,6 +390,9 @@ class FasterWhisperProvider:# 2026-06-29) or return garbage. This lock makes the model call mutually# exclusive per instance so the two callers serialize instead of racing.self._infer_lock = threading.Lock()+ # One-shot latch for the "auto-detect on an English-only model" warning+ # below, so a long dictation cannot fill the log with the same line.+ self._warned_english_only_autodetect = False# True once ``warm_up`` completed (model constructed + one priming# inference). Boot-time consumers (the rolling-whisper wake poll loop,# the heavy-backend gate) wait on this instead of poking the model@@ -574,6 +603,19 @@ class FasterWhisperProvider:ignore_initial_prompt,)+ def _warn_english_only_autodetect(self) -> None:+ """Warn ONCE that this model cannot honour an auto-detect request."""+ if getattr(self, "_warned_english_only_autodetect", False):+ return+ self._warned_english_only_autodetect = True+ log.warning(+ "STT model %r is English-only, so this auto-detect request can only "+ "produce English. Set the recognition language to 'auto' (which picks "+ "a multilingual model) or choose a multilingual model to transcribe "+ "other languages.",+ self._model_name,+ )+def _transcribe_sync(self, audio_np: np.ndarray, sample_rate: int,language: str | None = None,@@ -584,8 +626,20 @@ class FasterWhisperProvider:# A resample would be needed here — but we expect 16 kHz from captureraise ValueError(f"Expected 16 kHz, got {sample_rate} Hz")- # Per-call override takes precedence over self._language- effective_lang = language if language is not None else self._language+ # Per-call override takes precedence over self._language. ``"auto"`` is+ # an explicit REQUEST to detect, not an absent argument: it must clear a+ # configured pin for THIS call, never inherit it. Without that, dictation+ # in auto mode silently transcribed every language as whatever+ # ``[stt].language`` happened to be (live bug 2026-07-28: German spoken,+ # English written, because the recognition language was pinned to "en").+ effective_lang = _detect_or(language, self._language)+ if effective_lang is None and _is_english_only(self._model_name):+ # A deliberate "en" pin keeps the fast English-only checkpoint (see+ # __init__), so a later auto-detect call can still land on a model+ # that only knows English. Say so once instead of quietly mangling+ # the speech — the honest fix is a multilingual model or an "auto"+ # recognition language.+ self._warn_english_only_autodetect()# NON-BLOCKING acquire across BOTH the transcribe() call and the lazy# generator materialization (``list(segments_iter)`` runs the actualdiff --git a/jarvis/plugins/stt/gemini_api.py b/jarvis/plugins/stt/gemini_api.pyindex 94e7299fb9..d0cf204fb5 100644--- a/jarvis/plugins/stt/gemini_api.py+++ b/jarvis/plugins/stt/gemini_api.py@@ -57,6 +57,27 @@ from typing import Any# override it in the STT model field. Kept in step with the Gemini brain default.DEFAULT_MODEL = "gemini-3-flash-preview"+#: The per-call ``language`` value that REQUESTS detection instead of a pinned+#: language. Spelled out per plugin because plugins may not import ``jarvis.*``.+AUTO_LANGUAGE = "auto"+++def _detect_or(language: str | None, configured: str | None) -> str | None:+ """The language for ONE call. ``None`` means "let the model detect".++ Three cases, and the middle one is the whole point:++ * a concrete code (``"de"``) — transcribe as that language;+ * ``"auto"`` — an explicit request to DETECT, which clears ``configured`` for+ this call. Treating it as "no argument given" is what let dictation's auto+ mode inherit ``[stt].language`` and write German speech in English+ (live bug 2026-07-28);+ * ``None`` / empty — no per-call opinion, so the configured pin stands.+ """+ if language is None or not str(language).strip():+ return configured+ return None if str(language).strip().lower() == AUTO_LANGUAGE else str(language)+# The transcription directive. Tight on purpose: a generative model must be told# to emit ONLY the verbatim words, or it wraps the transcript in commentary. The# output cleanup below is a light safety net, not a content filter (AP-27): it@@ -121,6 +142,9 @@ class GeminiSTT:# the model favours those spellings; never treated as required content.self._prompt = (prompt or "").strip() or Noneself._temperature = temperature+ # Wired into the SDK client below — see ``_http_options``. It used to be+ # assigned here and read by nothing at all, which meant this provider had+ # NO timeout at any layer.self._timeout_s = timeout_sself._client = client@@ -144,7 +168,7 @@ class GeminiSTT:wav_bytes = _wrap_pcm_as_wav(b"".join(pcm_pieces), sample_rate=sample_rate, channels=channels)- return await self._post_transcription(wav_bytes)+ return await self._post_transcription(wav_bytes, language=self._language)async def stream_transcribe(self, audio: AsyncIterator[Any]@@ -164,18 +188,16 @@ class GeminiSTT:The speech pipeline delivers a full VAD-segmented utterance as raw int16PCM (mono, 16 kHz by default). We wrap it in a WAV container and send itas a single inline-audio request.++ ``language="auto"`` forces per-utterance detection for THIS call even+ when a language is configured — see :func:`_detect_or`."""if not pcm_bytes:return Transcript(text="", language="unknown", confidence=0.0)wav_bytes = _wrap_pcm_as_wav(pcm_bytes, sample_rate=sample_rate, channels=1)- if language and language != "auto":- previous = self._language- self._language = language- try:- return await self._post_transcription(wav_bytes)- finally:- self._language = previous- return await self._post_transcription(wav_bytes)+ return await self._post_transcription(+ wav_bytes, language=_detect_or(language, self._language)+ )def _ensure_model(self) -> None:"""No-op compat shim — cloud STT has nothing to warm up.@@ -193,6 +215,30 @@ class GeminiSTT:# Internals# ------------------------------------------------------------------+ def _http_options(self) -> dict[str, int]:+ """Transport options for the google-genai client — the request timeout.++ This is the ONLY thing standing between a stalled Gemini request and a+ permanently stuck lane. google-genai does not merely lack a default+ timeout, it actively FORCES ``timeout=None`` onto its own HTTP client+ when the caller passes no ``http_options`` (``_api_client.py``:+ ``if 'timeout' not in args: args['timeout'] = None``), which also+ overrides httpx's own defaults. And ``generate_content`` is synchronous,+ so it runs in ``asyncio.to_thread`` — a thread nothing can cancel, so no+ ``wait_for`` above this line can actually stop the call; it only stops+ WAITING for it while the thread leaks. A Gemini-only user could hang the+ dictation lane forever with the microphone already closed.++ ``HttpOptions.timeout`` is in MILLISECONDS, not seconds — verified+ against the installed google-genai (its ``get_timeout_in_seconds``+ divides by 1000), and the field description says so. Getting that wrong+ by 1000x is the whole reason this is a named, unit-tested method instead+ of an inline literal. The floor of one second keeps a nonsensical+ configured value (0, negative) from becoming "time out instantly", which+ would brick the provider rather than bound it.+ """+ return {"timeout": int(max(1.0, float(self._timeout_s)) * 1000)}+def _ensure_client(self) -> Any:"""Return the google-genai client, building it lazily from the key.@@ -224,20 +270,29 @@ class GeminiSTT:"Gemini STT needs the 'google-genai' package (installed with the ""'[full]' extra). Install it, or use a different STT provider.") from exc- self._client = genai.Client(api_key=key)+ # A plain dict is an accepted ``HttpOptionsDict`` at runtime; the local+ # ``Any`` keeps that fact from needing a types import the plugin must+ # not make (the SDK is absent on a base install).+ http_options: Any = self._http_options()+ self._client = genai.Client(api_key=key, http_options=http_options)return self._client- def _build_contents(self, wav_bytes: bytes) -> list[dict[str, Any]]:+ def _build_contents(+ self, wav_bytes: bytes, *, language: str | None = None+ ) -> list[dict[str, Any]]:"""Build the raw-dict ``contents`` payload (no google-genai types import).The SDK accepts a plain dict with an ``inline_data`` part whose ``data``is a base64 string — the exact shape the Gemini brain uses for images —so building it here keeps the module import-clean and unit-testable witha fake client.++ A ``language`` of None leaves the sentence out entirely, which is what+ asks the model to transcribe whatever language it actually hears."""instruction = _TRANSCRIBE_INSTRUCTION- if self._language:- instruction += f" The spoken language is '{self._language}'."+ if language:+ instruction += f" The spoken language is '{language}'."if self._prompt:instruction += (f" Expected vocabulary and proper nouns (favour these spellings): "@@ -251,9 +306,11 @@ class GeminiSTT:}return [{"role": "user", "parts": [audio_part, {"text": instruction}]}]- async def _post_transcription(self, wav_bytes: bytes) -> Transcript:+ async def _post_transcription(+ self, wav_bytes: bytes, *, language: str | None = None+ ) -> Transcript:client = self._ensure_client()- contents = self._build_contents(wav_bytes)+ contents = self._build_contents(wav_bytes, language=language)# ``config`` as a plain dict is accepted by google-genai; temperature 0.0# keeps the transcription as deterministic as a generative model allows.config = {"temperature": self._temperature}@@ -267,8 +324,30 @@ class GeminiSTT:config=config,)except Exception as exc: # noqa: BLE001 — degrade honestly (AP-22)- raise RuntimeError(f"Gemini STT request failed: {exc}") from exc- return _response_to_transcript(response, self._language)+ # Imported here, not at module top, to keep the plugin+ # ``jarvis.*``-free at import time (the entry-point purity contract)+ # — the same lazy seam the credential lookup uses. This runs only on+ # an already-failed request.+ from jarvis.plugins.stt.errors import STTHTTPError, status_from_exception++ message = f"Gemini STT request failed: {exc}"+ # The SDK raises its own ``APIError``, which carries the HTTP status+ # as ``.code``. Flattening that into a bare RuntimeError threw away+ # the one fact the caller needs to tell a retryable 429 from a+ # hopeless 401 — so the retry ladder never ran for a Gemini user and+ # a bursty rate limit ate the turn. We cannot import the SDK's error+ # type (google-genai is absent on a base install), hence the+ # duck-typed lookup. A transport error / timeout has no status and+ # stays a plain RuntimeError: inventing one would be a lie.+ status = status_from_exception(exc)+ if status is None:+ raise RuntimeError(message) from exc+ raise STTHTTPError(+ message,+ status=status,+ headers=getattr(getattr(exc, "response", None), "headers", None),+ ) from exc+ return _response_to_transcript(response, language)# ----------------------------------------------------------------------diff --git a/jarvis/plugins/stt/groq_api.py b/jarvis/plugins/stt/groq_api.pyindex 659768794d..86acde60f9 100644--- a/jarvis/plugins/stt/groq_api.py+++ b/jarvis/plugins/stt/groq_api.py@@ -39,6 +39,28 @@ import httpxDEFAULT_ENDPOINT = "https://api.groq.com/openai/v1/audio/transcriptions"DEFAULT_MODEL = "whisper-large-v3"+#: The per-call ``language`` value that REQUESTS detection instead of a pinned+#: language. Spelled out per plugin because plugins may not import ``jarvis.*``.+AUTO_LANGUAGE = "auto"+++def _detect_or(language: str | None, configured: str | None) -> str | None:+ """The language for ONE call. ``None`` means "let the service detect".++ Three cases, and the middle one is the whole point:++ * a concrete code (``"de"``) — transcribe as that language;+ * ``"auto"`` — an explicit request to DETECT, which clears ``configured`` for+ this call. Treating it as "no argument given" is what let dictation's auto+ mode inherit ``[stt].language`` and write German speech in English+ (live bug 2026-07-28);+ * ``None`` / empty — no per-call opinion, so the configured pin stands.+ """+ if language is None or not str(language).strip():+ return configured+ return None if str(language).strip().lower() == AUTO_LANGUAGE else str(language)++# Whisper accepts up to 224 prompt tokens; ~1000 chars is a safe cap that# stays under that even for token-dense German compounds (avg ~4 chars/token).# Going over makes Groq reject the whole turn with HTTP 400 and the user@@ -120,7 +142,7 @@ class GroqWhisperAPI:wav_bytes = _wrap_pcm_as_wav(b"".join(pcm_pieces), sample_rate=sample_rate, channels=channels)- return await self._post_transcription(wav_bytes)+ return await self._post_transcription(wav_bytes, language=self._language)async def stream_transcribe(self, audio: AsyncIterator[Any]@@ -141,19 +163,16 @@ class GroqWhisperAPI:full VAD-segmented utterance as raw int16 PCM. The Groq endpointaccepts a single WAV upload, so we wrap and POST directly without theAsyncIterator dance.++ ``language="auto"`` forces per-utterance detection for THIS call even+ when a language is configured — see :func:`_detect_or`."""if not pcm_bytes:return Transcript(text="", language="unknown", confidence=0.0)wav_bytes = _wrap_pcm_as_wav(pcm_bytes, sample_rate=sample_rate, channels=1)- # Optional per-call language override- if language and language != "auto":- previous = self._language- self._language = language- try:- return await self._post_transcription(wav_bytes)- finally:- self._language = previous- return await self._post_transcription(wav_bytes)+ return await self._post_transcription(+ wav_bytes, language=_detect_or(language, self._language)+ )def _ensure_model(self) -> None:"""No-op compat shim — cloud STT has nothing to warm up.@@ -192,17 +211,16 @@ class GroqWhisperAPI:"""if not data:return Transcript(text="", language="unknown", confidence=0.0)- if language and language != "auto":- previous = self._language- self._language = language- try:- return await self._post_transcription(data, filename=filename)- finally:- self._language = previous- return await self._post_transcription(data, filename=filename)+ return await self._post_transcription(+ data, filename=filename, language=_detect_or(language, self._language)+ )async def _post_transcription(- self, wav_bytes: bytes, *, filename: str = "audio.wav"+ self,+ wav_bytes: bytes,+ *,+ filename: str = "audio.wav",+ language: str | None = None,) -> Transcript:if not self._api_key:raise RuntimeError(@@ -219,8 +237,10 @@ class GroqWhisperAPI:"response_format": "verbose_json","temperature": str(self._temperature),}- if self._language:- data["language"] = self._language+ # Omitted entirely when None — that is what asks Whisper to detect the+ # spoken language instead of decoding it as a pinned one.+ if language:+ data["language"] = languageif self._prompt:data["prompt"] = self._prompt@@ -229,6 +249,17 @@ class GroqWhisperAPI:response = await client.post(self._endpoint, headers=headers, data=data, files=files)+ # ``httpx.HTTPStatusError`` carries the status on ``.response.status_code``+ # and the ``Retry-After`` header on ``.response.headers`` — which is+ # exactly why the pipeline's transient-error retry ladder worked for THIS+ # provider and for no other one, and what the shared+ # ``jarvis.plugins.stt.errors.STTHTTPError`` reproduces for the plugins+ # that used to flatten every status into a bare RuntimeError. This plugin+ # deliberately does NOT raise that shared type: it is the one STT plugin+ # held to a total ``jarvis.*``-import ban (CLAUDE.md §5, pinned by+ # tests/contract/test_stt_protocol.py), even for a lazy import inside a+ # method. It already emits the classifiable shape, so there is nothing to+ # gain and a purity contract to lose. Do not "unify" this line.response.raise_for_status()payload = response.json()return _payload_to_transcript(payload)diff --git a/jarvis/plugins/stt/openai_api.py b/jarvis/plugins/stt/openai_api.pyindex 93d24241e5..be145436be 100644--- a/jarvis/plugins/stt/openai_api.py+++ b/jarvis/plugins/stt/openai_api.py@@ -70,6 +70,27 @@ DEFAULT_MODEL = "whisper-1"# total silence — never worth saving a few extra words._MAX_PROMPT_CHARS = 1024+#: The per-call ``language`` value that REQUESTS detection instead of a pinned+#: language. Spelled out per plugin because plugins may not import ``jarvis.*``.+AUTO_LANGUAGE = "auto"+++def _detect_or(language: str | None, configured: str | None) -> str | None:+ """The language for ONE call. ``None`` means "let the service detect".++ Three cases, and the middle one is the whole point:++ * a concrete code (``"de"``) — transcribe as that language;+ * ``"auto"`` — an explicit request to DETECT, which clears ``configured`` for+ this call. Treating it as "no argument given" is what let dictation's auto+ mode inherit ``[stt].language`` and write German speech in English+ (live bug 2026-07-28);+ * ``None`` / empty — no per-call opinion, so the configured pin stands.+ """+ if language is None or not str(language).strip():+ return configured+ return None if str(language).strip().lower() == AUTO_LANGUAGE else str(language)+@dataclass(frozen=True, slots=True)class Transcript:@@ -156,7 +177,7 @@ class OpenAIWhisperAPI:wav_bytes = _wrap_pcm_as_wav(b"".join(pcm_pieces), sample_rate=sample_rate, channels=channels)- return await self._post_transcription(wav_bytes)+ return await self._post_transcription(wav_bytes, language=self._language)async def stream_transcribe(self, audio: AsyncIterator[Any]@@ -176,19 +197,16 @@ class OpenAIWhisperAPI:The speech pipeline delivers a full VAD-segmented utterance as raw int16PCM (mono, 16 kHz by default). We wrap it in a WAV container and POST itas a single multipart request.++ ``language="auto"`` forces per-utterance detection for THIS call even+ when a language is configured — see :func:`_detect_or`."""if not pcm_bytes:return Transcript(text="", language="unknown", confidence=0.0)wav_bytes = _wrap_pcm_as_wav(pcm_bytes, sample_rate=sample_rate, channels=1)- # Optional per-call language override (restore afterwards).- if language and language != "auto":- previous = self._language- self._language = language- try:- return await self._post_transcription(wav_bytes)- finally:- self._language = previous- return await self._post_transcription(wav_bytes)+ return await self._post_transcription(+ wav_bytes, language=_detect_or(language, self._language)+ )async def transcribe_container(self, data: bytes, *, filename: str = "recording", language: str | None = None@@ -207,14 +225,9 @@ class OpenAIWhisperAPI:"""if not data:return Transcript(text="", language="unknown", confidence=0.0)- if language and language != "auto":- previous = self._language- self._language = language- try:- return await self._post_transcription(data, filename=filename)- finally:- self._language = previous- return await self._post_transcription(data, filename=filename)+ return await self._post_transcription(+ data, filename=filename, language=_detect_or(language, self._language)+ )def _ensure_model(self) -> None:"""No-op compat shim — cloud STT has nothing to warm up.@@ -288,7 +301,11 @@ class OpenAIWhisperAPI:return self._endpoint_urlasync def _post_transcription(- self, wav_bytes: bytes, *, filename: str = "audio.wav"+ self,+ wav_bytes: bytes,+ *,+ filename: str = "audio.wav",+ language: str | None = None,) -> Transcript:url = self._ensure_endpoint()# The NAME is how the service identifies the container, so an imported@@ -302,8 +319,10 @@ class OpenAIWhisperAPI:"response_format": "verbose_json","temperature": str(self._temperature),}- if self._language:- data["language"] = self._language+ # Omitted entirely when None — that is what asks Whisper to detect the+ # spoken language instead of decoding it as a pinned one.+ if language:+ data["language"] = languageif self._prompt:data["prompt"] = self._prompt@@ -355,34 +374,24 @@ def _wrap_pcm_as_wav(pcm: bytes, *, sample_rate: int, channels: int) -> bytes:def _http_error_to_runtime(response: httpx.Response) -> RuntimeError:- """Map an HTTP error status to a clear English RuntimeError.+ """Map an HTTP error status to a clear English, CLASSIFIABLE error.401 (bad/dead key), 402 (out of credit), 429 (rate limited) and any other- 4xx/5xx all become a RuntimeError so the caller degrades honestly to the- local floor rather than bricking the STT tier (AP-22).+ 4xx/5xx all become an ``STTHTTPError`` — still a ``RuntimeError``, so the+ caller degrades honestly to the local floor exactly as before (AP-22), but+ now carrying the ``status`` and the server's ``Retry-After``. Without those+ the pipeline's transient-error retry ladder was dead code for this plugin+ (it could only read a status off the one provider that raised an+ ``httpx.HTTPStatusError``), so an OpenAI-key user lost the whole turn to the+ first rate limit. The English wording is unchanged; only the type is."""- status = response.status_code- detail = ""- try:- payload = response.json()- if isinstance(payload, dict):- err = payload.get("error")- if isinstance(err, dict):- detail = str(err.get("message", "")).strip()- elif isinstance(err, str):- detail = err.strip()- except Exception: # noqa: BLE001 — body may not be JSON- detail = (response.text or "").strip()[:200]-- reason = {- 401: "invalid or missing OpenAI API key",- 402: "OpenAI account out of credit",- 429: "OpenAI rate limit / quota exceeded",- }.get(status, f"OpenAI STT HTTP {status}")- msg = f"OpenAI STT failed: {reason}"- if detail:- msg = f"{msg} ({detail})"- return RuntimeError(msg)+ # Imported here, not at module top, to keep the plugin ``jarvis.*``-free at+ # import time (the entry-point purity contract) — the same lazy seam the+ # credential lookup uses. This runs only on an already-failed request, so+ # the import costs nothing on the happy path.+ from jarvis.plugins.stt.errors import http_error_from_response++ return http_error_from_response(response, vendor="OpenAI")def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:diff --git a/jarvis/plugins/stt/openrouter_stt.py b/jarvis/plugins/stt/openrouter_stt.pyindex fd3d0a0b66..3a698ed030 100644--- a/jarvis/plugins/stt/openrouter_stt.py+++ b/jarvis/plugins/stt/openrouter_stt.py@@ -66,6 +66,28 @@ DEFAULT_BASE_URL = "https://openrouter.ai/api/v1"# in the model dropdown; the picker only offers transcription-capable models.DEFAULT_MODEL = "openai/whisper-large-v3"+#: The per-call ``language`` value that REQUESTS detection instead of a pinned+#: language. Spelled out per plugin because plugins may not import ``jarvis.*``.+AUTO_LANGUAGE = "auto"+++def _detect_or(language: str | None, configured: str | None) -> str | None:+ """The language for ONE call. ``None`` means "let the model detect".++ Three cases, and the middle one is the whole point:++ * a concrete code (``"de"``) — transcribe as that language;+ * ``"auto"`` — an explicit request to DETECT, which clears ``configured`` for+ this call. Treating it as "no argument given" is what let dictation's auto+ mode inherit ``[stt].language`` and write German speech in English+ (live bug 2026-07-28);+ * ``None`` / empty — no per-call opinion, so the configured pin stands.+ """+ if language is None or not str(language).strip():+ return configured+ return None if str(language).strip().lower() == AUTO_LANGUAGE else str(language)++# The OpenRouter attribution headers (same values the brain adapter sends)._ATTRIBUTION_HEADERS = {"HTTP-Referer": "https://github.com/PersonalJarvis",@@ -158,7 +180,7 @@ class OpenRouterSTT:wav_bytes = _wrap_pcm_as_wav(b"".join(pcm_pieces), sample_rate=sample_rate, channels=channels)- return await self._post_transcription(wav_bytes)+ return await self._post_transcription(wav_bytes, language=self._language)async def stream_transcribe(self, audio: AsyncIterator[Any]@@ -178,19 +200,16 @@ class OpenRouterSTT:The speech pipeline delivers a full VAD-segmented utterance as raw int16PCM (mono, 16 kHz by default). We wrap it in a WAV container and POST itas a single JSON request.++ ``language="auto"`` forces per-utterance detection for THIS call even+ when a language is configured — see :func:`_detect_or`."""if not pcm_bytes:return Transcript(text="", language="unknown", confidence=0.0)wav_bytes = _wrap_pcm_as_wav(pcm_bytes, sample_rate=sample_rate, channels=1)- # Optional per-call language override (restore afterwards).- if language and language != "auto":- previous = self._language- self._language = language- try:- return await self._post_transcription(wav_bytes)- finally:- self._language = previous- return await self._post_transcription(wav_bytes)+ return await self._post_transcription(+ wav_bytes, language=_detect_or(language, self._language)+ )def _ensure_model(self) -> None:"""No-op compat shim — cloud STT has nothing to warm up.@@ -258,7 +277,9 @@ class OpenRouterSTT:self._endpoint_url = base.rstrip("/") + "/audio/transcriptions"return self._endpoint_url- async def _post_transcription(self, wav_bytes: bytes) -> Transcript:+ async def _post_transcription(+ self, wav_bytes: bytes, *, language: str | None = None+ ) -> Transcript:import base64url = self._ensure_endpoint()@@ -269,8 +290,10 @@ class OpenRouterSTT:"format": "wav",},}- if self._language:- body["language"] = self._language+ # Omitted entirely when None — that is what asks the model to detect the+ # spoken language instead of decoding it as a pinned one.+ if language:+ body["language"] = language# Temperature is omitted unless explicitly configured: keeping the body# minimal maximises portability across the ~10 transcription backends the# gateway fronts (some reject unexpected fields).@@ -384,34 +407,24 @@ def _wrap_pcm_as_wav(pcm: bytes, *, sample_rate: int, channels: int) -> bytes:def _http_error_to_runtime(response: httpx.Response) -> RuntimeError:- """Map an HTTP error status to a clear English RuntimeError.+ """Map an HTTP error status to a clear English, CLASSIFIABLE error.401 (bad/dead key), 402 (out of credit), 429 (rate limited) and any other- 4xx/5xx all become a RuntimeError so the caller degrades honestly to the- local floor rather than bricking the STT tier (AP-22).+ 4xx/5xx all become an ``STTHTTPError`` — still a ``RuntimeError``, so the+ caller degrades honestly to the local floor exactly as before (AP-22), but+ now carrying the ``status`` and the server's ``Retry-After``. Without those+ the pipeline's transient-error retry ladder was dead code for this plugin+ (it could only read a status off the one provider that raised an+ ``httpx.HTTPStatusError``), so an OpenRouter-key user lost the whole turn to+ the first rate limit. The English wording is unchanged; only the type is."""- status = response.status_code- detail = ""- try:- payload = response.json()- if isinstance(payload, dict):- err = payload.get("error")- if isinstance(err, dict):- detail = str(err.get("message", "")).strip()- elif isinstance(err, str):- detail = err.strip()- except Exception: # noqa: BLE001 — body may not be JSON- detail = (response.text or "").strip()[:200]-- reason = {- 401: "invalid or missing OpenRouter API key",- 402: "OpenRouter account out of credit",- 429: "OpenRouter rate limit / quota exceeded",- }.get(status, f"OpenRouter STT HTTP {status}")- msg = f"OpenRouter STT failed: {reason}"- if detail:- msg = f"{msg} ({detail})"- return RuntimeError(msg)+ # Imported here, not at module top, to keep the plugin ``jarvis.*``-free at+ # import time (the entry-point purity contract) — the same lazy seam the+ # credential lookup uses. This runs only on an already-failed request, so+ # the import costs nothing on the happy path.+ from jarvis.plugins.stt.errors import http_error_from_response++ return http_error_from_response(response, vendor="OpenRouter")def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:diff --git a/tests/unit/plugins/stt/test_auto_language_detection.py b/tests/unit/plugins/stt/test_auto_language_detection.pynew file mode 100644index 0000000000..592fdd8138--- /dev/null+++ b/tests/unit/plugins/stt/test_auto_language_detection.py@@ -0,0 +1,284 @@+"""Every STT provider must treat a per-call ``language="auto"`` as DETECT.++The regression these lock down (live bug 2026-07-28): dictation's language+setting offered "Automatic", and "automatic" was implemented as *not passing a+language at all*. But an absent argument does not mean "detect" to a provider —+it means "no per-call opinion", so the transcription fell back to the language+configured in ``[stt].language``. With the recognition language pinned to English+a user dictating German got English words back, and nothing in the dictation view+could fix it because the dictation view was not the setting in charge.++So the contract is now explicit, and these tests pin it for all five providers:++* a concrete code → transcribe as that language;+* ``"auto"`` → DETECT, clearing the configured language for this call;+* nothing passed → the configured language stands (unchanged behaviour).++Cloud providers are exercised through ``httpx.MockTransport`` / a hand-rolled+fake client (never ``unittest.mock``), asserting on the actual outgoing request.+"""+from __future__ import annotations++from dataclasses import dataclass+from types import SimpleNamespace+from typing import Any++import httpx+import pytest++from jarvis.plugins.stt.gemini_api import GeminiSTT+from jarvis.plugins.stt.groq_api import GroqWhisperAPI+from jarvis.plugins.stt.openai_api import OpenAIWhisperAPI+from jarvis.plugins.stt.openrouter_stt import OpenRouterSTT++_PCM = b"\x00\x00" * 1600 # 0.1 s of silence at 16 kHz+++# ---------------------------------------------------------------------------+# Multipart helpers (Groq + OpenAI post form data)+# ---------------------------------------------------------------------------++def _form_field(body: bytes, name: str) -> str | None:+ """The value of one text field in a multipart body, or None when absent."""+ needle = f'name="{name}"'.encode()+ idx = body.find(needle)+ if idx == -1:+ return None+ head_end = body.find(b"\r\n\r\n", idx)+ if head_end == -1:+ return None+ start = head_end + 4+ end = body.find(b"\r\n--", start)+ return body[start:end].decode("utf-8") if end != -1 else None+++def _capturing_client(captured: dict[str, Any], payload: dict[str, Any]):+ async def handler(request: httpx.Request) -> httpx.Response:+ captured["content"] = request.content+ return httpx.Response(200, json=payload)++ return httpx.AsyncClient(transport=httpx.MockTransport(handler))+++_MULTIPART_OK = {"text": "guten morgen", "language": "german", "segments": []}+_JSON_OK = {"text": "guten morgen"}+++# ---------------------------------------------------------------------------+# Groq / OpenAI — identical multipart shape, so one parametrised suite+# ---------------------------------------------------------------------------+[email protected]("provider_cls", [GroqWhisperAPI, OpenAIWhisperAPI])+async def test_auto_clears_a_configured_language(provider_cls) -> None:+ """The core regression: a configured "en" must NOT survive an auto call."""+ captured: dict[str, Any] = {}+ stt = provider_cls(+ api_key="test-key",+ language="en",+ http_client=_capturing_client(captured, _MULTIPART_OK),+ )++ await stt.transcribe_pcm(_PCM, language="auto")++ # Omitting the field entirely is how Whisper is asked to detect. Sending+ # "auto" would be just as wrong — it is not a language code.+ assert _form_field(captured["content"], "language") is None++[email protected]("provider_cls", [GroqWhisperAPI, OpenAIWhisperAPI])+async def test_a_concrete_language_still_overrides_the_configured_one(+ provider_cls,+) -> None:+ captured: dict[str, Any] = {}+ stt = provider_cls(+ api_key="test-key",+ language="en",+ http_client=_capturing_client(captured, _MULTIPART_OK),+ )++ await stt.transcribe_pcm(_PCM, language="de")++ assert _form_field(captured["content"], "language") == "de"++[email protected]("provider_cls", [GroqWhisperAPI, OpenAIWhisperAPI])+async def test_passing_nothing_keeps_the_configured_language(provider_cls) -> None:+ """Unchanged behaviour — the voice path relies on it."""+ captured: dict[str, Any] = {}+ stt = provider_cls(+ api_key="test-key",+ language="en",+ http_client=_capturing_client(captured, _MULTIPART_OK),+ )++ await stt.transcribe_pcm(_PCM)++ assert _form_field(captured["content"], "language") == "en"++[email protected]("provider_cls", [GroqWhisperAPI, OpenAIWhisperAPI])+async def test_the_configured_language_is_not_mutated_by_one_call(+ provider_cls,+) -> None:+ """A per-call override must not leak into the NEXT call.++ The previous implementation swapped ``self._language`` for the duration of+ the request, which two concurrent transcriptions (a dictation while a voice+ turn finishes) could interleave into the wrong language.+ """+ captured: dict[str, Any] = {}+ stt = provider_cls(+ api_key="test-key",+ language="en",+ http_client=_capturing_client(captured, _MULTIPART_OK),+ )++ await stt.transcribe_pcm(_PCM, language="auto")+ await stt.transcribe_pcm(_PCM)++ assert _form_field(captured["content"], "language") == "en"+++# ---------------------------------------------------------------------------+# OpenRouter — JSON body+# ---------------------------------------------------------------------------++def _openrouter(captured: dict[str, Any], language: str | None) -> OpenRouterSTT:+ async def handler(request: httpx.Request) -> httpx.Response:+ import json++ captured["body"] = json.loads(request.content)+ return httpx.Response(200, json=_JSON_OK)++ return OpenRouterSTT(+ api_key="test-key",+ language=language,+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ )+++async def test_openrouter_auto_clears_a_configured_language() -> None:+ captured: dict[str, Any] = {}+ stt = _openrouter(captured, "en")++ await stt.transcribe_pcm(_PCM, language="auto")++ assert "language" not in captured["body"]+++async def test_openrouter_keeps_the_configured_language_without_an_override() -> None:+ captured: dict[str, Any] = {}+ stt = _openrouter(captured, "en")++ await stt.transcribe_pcm(_PCM)++ assert captured["body"]["language"] == "en"+++# ---------------------------------------------------------------------------+# Gemini — the language rides in the prompt text, not a request field+# ---------------------------------------------------------------------------++@dataclass+class _FakeResponse:+ text: str+++class _FakeModels:+ def __init__(self, captured: dict[str, Any]) -> None:+ self._captured = captured++ def generate_content(self, *, model, contents, config): # noqa: ANN001+ self._captured["contents"] = contents+ return _FakeResponse("guten morgen")+++class _FakeClient:+ def __init__(self, captured: dict[str, Any]) -> None:+ self.models = _FakeModels(captured)+++def _instruction(captured: dict[str, Any]) -> str:+ parts = captured["contents"][0]["parts"]+ return " ".join(str(p.get("text", "")) for p in parts)+++async def test_gemini_auto_drops_the_language_sentence() -> None:+ """Telling a generative model "the spoken language is English" is what makes+ it write English — so an auto call must not tell it anything."""+ captured: dict[str, Any] = {}+ stt = GeminiSTT(client=_FakeClient(captured), language="en")++ await stt.transcribe_pcm(_PCM, language="auto")++ assert "spoken language" not in _instruction(captured)+++async def test_gemini_keeps_the_configured_language_without_an_override() -> None:+ captured: dict[str, Any] = {}+ stt = GeminiSTT(client=_FakeClient(captured), language="en")++ await stt.transcribe_pcm(_PCM)++ assert "The spoken language is 'en'." in _instruction(captured)+++# ---------------------------------------------------------------------------+# faster-whisper — local engine, so assert on the decode argument+# ---------------------------------------------------------------------------++class _FakeWhisperModel:+ """Records the ``language`` faster-whisper is asked to decode with."""++ def __init__(self, captured: dict[str, Any]) -> None:+ self._captured = captured++ def transcribe(self, audio, **kwargs): # noqa: ANN001+ self._captured["language"] = kwargs.get("language")+ info = SimpleNamespace(language="de", language_probability=0.99)+ return iter(()), info+++def _fwhisper(captured: dict[str, Any], language: str | None):+ from jarvis.plugins.stt import fwhisper as fwhisper_mod++ provider = fwhisper_mod.FasterWhisperProvider(language=language)+ provider._model = _FakeWhisperModel(captured)+ # The lazy builder would try to load real weights; the fake model is already+ # in place, so keep _ensure_model a no-op for this instance.+ provider._ensure_model = lambda: None # type: ignore[method-assign]+ return provider+++def test_fwhisper_auto_clears_a_configured_language() -> None:+ captured: dict[str, Any] = {}+ provider = _fwhisper(captured, "en")++ provider._transcribe_sync(_pcm_as_float(), 16_000, "auto")++ # None is faster-whisper's own "detect the language" value; the string+ # "auto" is not a language it knows and would decode as garbage.+ assert captured["language"] is None+++def test_fwhisper_keeps_the_configured_language_without_an_override() -> None:+ captured: dict[str, Any] = {}+ provider = _fwhisper(captured, "en")++ provider._transcribe_sync(_pcm_as_float(), 16_000, None)++ assert captured["language"] == "en"+++def _pcm_as_float():+ import numpy as np++ return np.zeros(1600, dtype=np.float32)diff --git a/tests/unit/plugins/stt/test_stt_cross_family_fallback.py b/tests/unit/plugins/stt/test_stt_cross_family_fallback.pynew file mode 100644index 0000000000..5487acea17--- /dev/null+++ b/tests/unit/plugins/stt/test_stt_cross_family_fallback.py@@ -0,0 +1,250 @@+"""Runtime cross-family STT fallback: the resolver half (AP-22).++``_resolve_keyed_stt_provider`` decides at BUILD time and only when a key is+entirely MISSING. A provider that HAS a key and then answers 429 / 402 / 401+mid-session was the end of the transcription — a depleted Groq key bricked+dictation for a whole session even with a valid OpenAI or Gemini key sitting in+the keyring. ``resolve_keyed_stt_fallback`` is the missing primitive: which+provider does this host actually have left, from a family that is not the one+that just failed.++The load-bearing invariant is the FAMILY one. Crossing from a rate-limited+provider to a second id that reads the SAME credential slot is not a fallback,+it is the same 429 twice — the single-provider brick AP-22 names. So "family" is+defined by the credential, never by the provider name (AP-21), and these tests+prove the resolver cannot be tricked by two ids that share a key.++No ``unittest.mock``: credential presence and entry-point registration are both+substituted with plain functions, the way the existing STT factory tests do it.+"""+from __future__ import annotations++from typing import Any++import pytest++import jarvis.core.config as cfg+import jarvis.plugins.stt as stt_pkg+from jarvis.core.config import ResolvedEndpoint, STTConfig+++class _FakeCloudSTT:+ """Stands in for any registered cloud STT entry-point class."""++ def __init__(self, **kwargs: Any) -> None:+ self.kwargs = kwargs+++def _keys(*slots: str):+ """A ``get_secret_any`` double where ONLY ``slots`` resolve to a credential."""++ def _fake(candidates) -> str | None:+ names = {c[0] for c in candidates}+ return "real-key" if names & set(slots) else None++ return _fake++[email protected](autouse=True)+def _no_proxy_all_registered(monkeypatch: pytest.MonkeyPatch) -> None:+ """Direct mode (no team proxy) and every family registered as an entry-point.++ Both are prerequisites of the thing under test rather than the thing itself:+ the proxy would hand ``groq-api`` a credential it has not got, and an+ unregistered family is skipped for a different, separately tested reason.+ """+ monkeypatch.setattr(+ cfg,+ "resolve_provider_endpoint",+ lambda pid, **kw: ResolvedEndpoint(+ base_url=None, credential=None, via_proxy=False+ ),+ )+ monkeypatch.setattr(stt_pkg, "_load_provider_class", lambda name: _FakeCloudSTT)+++# ---------------------------------------------------------------------------+# The family definition+# ---------------------------------------------------------------------------+++def test_family_is_the_credential_slot_not_the_provider_name() -> None:+ """Ids that read one keyring entry are ONE family, however they are spelled."""+ assert stt_pkg.stt_family_id("groq-api") == "groq_api_key"+ assert stt_pkg.stt_family_id("openrouter-stt") == "openrouter_api_key"+ assert stt_pkg.stt_family_id("openai-api") == "openai_api_key"+ assert stt_pkg.stt_family_id("gemini-api") == "gemini_api_key"+ # The key-free local engine has no credential to exhaust.+ assert stt_pkg.stt_family_id("faster-whisper") == "local"+ # An unknown / third-party id is its own family: we cannot prove it shares a+ # credential with anything, and dropping it would lose a working provider.+ assert stt_pkg.stt_family_id("some-third-party-stt") == "some-third-party-stt"+++def test_the_shipped_cross_family_order_really_is_one_per_family() -> None:+ """A future second id for an existing vendor must not slip into the order.++ Asserted non-empty first, so a table that stopped parsing fails loudly+ instead of passing trivially.+ """+ order = stt_pkg._STT_CROSS_FAMILY_ORDER+ assert len(order) >= 2, "the cross-family order is empty — nothing was checked"++ families = [stt_pkg.stt_family_id(name) for name in order]+ assert len(set(families)) == len(families), (+ f"two shipped STT ids share one credential family: {families}"+ )+++# ---------------------------------------------------------------------------+# The chain+# ---------------------------------------------------------------------------+++def test_it_crosses_to_the_other_families_the_user_has_a_key_for(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A depleted Groq key must reach the OpenAI and Gemini keys in the keyring."""+ monkeypatch.setattr(+ cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key", "gemini_api_key")+ )++ chain = stt_pkg.resolve_keyed_stt_fallback("groq-api")++ assert chain == ("openai-api", "gemini-api"), (+ "the chain must offer every OTHER keyed family, in the shipped order, "+ "and never the one that just failed"+ )+++def test_one_keyed_family_gives_an_honest_empty_chain(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """No other key means no fallback — say so, do not invent one.++ An empty tuple is the honest answer: the caller then degrades exactly as it+ does today (an honest message, or the key-free local floor). Promising a+ provider the host cannot authenticate would turn one failure into two.+ """+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key"))++ assert stt_pkg.resolve_keyed_stt_fallback("groq-api") == ()+++def test_it_never_returns_two_providers_from_one_credential_family(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Two ids sharing a key are the same 429 twice — the AP-22 brick.++ Simulated with a second id pointed at the OpenAI credential slot, which is+ exactly the shape a future ``openai-realtime-stt`` (or a renamed provider+ kept as an alias) would take.+ """+ monkeypatch.setitem(+ stt_pkg._STT_SECRET_CANDIDATES,+ "openai-second-id",+ (("openai_api_key", "OPENAI_API_KEY"),),+ )+ monkeypatch.setattr(+ stt_pkg,+ "_STT_CROSS_FAMILY_ORDER",+ ("groq-api", "openai-api", "openai-second-id", "gemini-api"),+ )+ monkeypatch.setattr(+ cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key", "gemini_api_key")+ )++ chain = stt_pkg.resolve_keyed_stt_fallback("groq-api")++ assert chain == ("openai-api", "gemini-api")+ families = [stt_pkg.stt_family_id(name) for name in chain]+ assert len(set(families)) == len(families)+++def test_excluding_a_family_removes_every_id_that_shares_its_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A session that already burned a family must not walk back into it.++ ``exclude_family`` takes a provider id or a family id, because the caller+ knows the provider it just tried, not the keyring slot behind it.+ """+ monkeypatch.setattr(+ cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key", "gemini_api_key")+ )++ by_provider_id = stt_pkg.resolve_keyed_stt_fallback(+ "groq-api", exclude_family="openai-api"+ )+ by_family_id = stt_pkg.resolve_keyed_stt_fallback(+ "groq-api", exclude_family=("openai_api_key",)+ )++ assert by_provider_id == ("gemini-api",)+ assert by_family_id == ("gemini-api",)+++def test_a_keyed_but_unregistered_family_is_skipped(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Never promise a provider we cannot build — the caller would just crash."""+ monkeypatch.setattr(+ stt_pkg,+ "_load_provider_class",+ lambda name: _FakeCloudSTT if name == "gemini-api" else None,+ )+ monkeypatch.setattr(+ cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key", "gemini_api_key")+ )++ assert stt_pkg.resolve_keyed_stt_fallback("groq-api") == ("gemini-api",)+++def test_the_local_engine_is_not_part_of_this_chain(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """faster-whisper is a floor, not a family.++ It is key-free, so a credential-derived chain would always end on it — but+ it is absent from a base/headless install and slow without a GPU, so it+ belongs at the END of the caller's own ordering+ (``jarvis.speech.stt_fallback.alternate_provider_names``), not in the middle+ of a credential chain.+ """+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key"))++ assert "faster-whisper" not in stt_pkg.resolve_keyed_stt_fallback("groq-api")+++def test_an_unknown_current_provider_still_gets_the_whole_chain(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A third-party STT that fails must still reach the user's real keys."""+ monkeypatch.setattr(cfg, "get_secret_any", _keys("openai_api_key"))++ assert stt_pkg.resolve_keyed_stt_fallback("some-third-party-stt") == ("openai-api",)+++# ---------------------------------------------------------------------------+# The promise the chain makes: every entry is buildable+# ---------------------------------------------------------------------------+++def test_every_chain_entry_can_actually_be_built(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The chain is names, not instances (AP-26) — but the names must resolve.++ Building on demand is what keeps a model load off the caller's path; it also+ means a name that cannot be built would only blow up at the worst possible+ moment, mid-failure. So the resolver's registration check is verified here+ against the real build entry point.+ """+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key"))++ chain = stt_pkg.resolve_keyed_stt_fallback("groq-api")+ assert chain, "expected at least one alternate for this key set"++ for name in chain:+ built = stt_pkg.build_named_stt_provider(name, STTConfig(provider="groq-api"))+ assert isinstance(built, _FakeCloudSTT)diff --git a/tests/unit/plugins/stt/test_stt_error_classification.py b/tests/unit/plugins/stt/test_stt_error_classification.pynew file mode 100644index 0000000000..dc2281aa5e--- /dev/null+++ b/tests/unit/plugins/stt/test_stt_error_classification.py@@ -0,0 +1,466 @@+"""A failing cloud STT must be CLASSIFIABLE, and a hanging one must be BOUNDED.++The retry ladder in ``jarvis.speech.pipeline`` decides "retry this / give up on+this" from the HTTP status behind a failed transcription, and how long to wait+from the server's ``Retry-After``. Before ``jarvis.plugins.stt.errors`` existed+it could only read those off an ``httpx.HTTPStatusError`` — which exactly ONE of+the four cloud plugins raised. For the other three the ladder was dead code: the+first 429 ended the turn, silently, for every downloader whose key is not a Groq+key, while those plugins' docstrings promised they "degrade honestly (AP-22)".+That is AP-23 — only the maintainer's provider actually worked.++These tests pin the contract from BOTH ends: each plugin raises the typed error+with the right status and delay, and the pipeline's own classifier agrees. The+second half is what makes this a guard rather than a restatement — a plugin that+raises a beautifully typed error the consumer cannot read is the bug we had.++The last section covers the failure that produces no error at all: Gemini STT+had NO timeout at any layer. Its ``timeout_s`` was assigned and read by nothing,+google-genai forces ``timeout=None`` onto its own HTTP client unless told+otherwise, and the call runs in an uncancellable thread — so a Gemini-only user+could hang the dictation lane forever with the microphone already closed.++No ``unittest.mock``: the HTTP plugins get an ``httpx.MockTransport``, Gemini+gets a hand-rolled fake client, exactly like the existing plugin tests.+"""+from __future__ import annotations++import asyncio+from datetime import UTC, datetime, timedelta+from email.utils import format_datetime+from typing import Any++import httpx+import pytest++from jarvis.plugins.stt.errors import (+ STTHTTPError,+ http_error_from_response,+ parse_retry_after,+ status_from_exception,+)+from jarvis.plugins.stt.gemini_api import GeminiSTT+from jarvis.plugins.stt.groq_api import GroqWhisperAPI+from jarvis.plugins.stt.openai_api import OpenAIWhisperAPI+from jarvis.plugins.stt.openrouter_stt import OpenRouterSTT+from jarvis.speech.pipeline import (+ _is_transient_stt_error,+ _stt_error_status,+ _stt_retry_delay,+)+++def _fake_pcm(seconds: float = 0.2, sample_rate: int = 16_000) -> bytes:+ return b"\x00\x00" * int(sample_rate * seconds)+++def _mock_client(handler) -> httpx.AsyncClient:+ return httpx.AsyncClient(transport=httpx.MockTransport(handler))+++def _responder(status: int, headers: dict[str, str] | None = None):+ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ status, json={"error": {"message": "slow down"}}, headers=headers or {}+ )++ return handler+++# ---------------------------------------------------------------------------+# Fake google-genai error + client (the SDK is optional, so it is duck-typed)+# ---------------------------------------------------------------------------+++class _FakeGenaiAPIError(Exception):+ """The shape google-genai's ``APIError`` presents: an int ``code``.++ Hand-rolled on purpose. The SDK is absent on a base install, so the plugin+ duck-types it and the test must too — importing the real class here would+ make this test pass for a reason the shipped code never relies on.+ """++ def __init__(self, code: int, message: str, headers: dict[str, str] | None = None):+ super().__init__(f"{code} {message}")+ self.code = code+ self.response = type("_Resp", (), {"headers": headers or {}})()+++class _RaisingModels:+ def __init__(self, exc: BaseException) -> None:+ self._exc = exc++ def generate_content(self, **_kwargs: Any): # noqa: ANN204 — fake SDK surface+ raise self._exc+++class _RaisingGenaiClient:+ def __init__(self, exc: BaseException) -> None:+ self.models = _RaisingModels(exc)+++# ---------------------------------------------------------------------------+# The four plugins: a 429 with Retry-After is transient and carries the delay+# ---------------------------------------------------------------------------+++def _raise_from_openai(status: int, headers: dict[str, str] | None = None) -> BaseException:+ provider = OpenAIWhisperAPI(+ api_key="k", http_client=_mock_client(_responder(status, headers))+ )+ with pytest.raises(Exception) as excinfo: # noqa: PT011 — type is the assertion+ asyncio.run(provider.transcribe_pcm(_fake_pcm()))+ return excinfo.value+++def _raise_from_openrouter(status: int, headers: dict[str, str] | None = None) -> BaseException:+ provider = OpenRouterSTT(+ api_key="k", http_client=_mock_client(_responder(status, headers))+ )+ with pytest.raises(Exception) as excinfo: # noqa: PT011 — type is the assertion+ asyncio.run(provider.transcribe_pcm(_fake_pcm()))+ return excinfo.value+++def _raise_from_groq(status: int, headers: dict[str, str] | None = None) -> BaseException:+ provider = GroqWhisperAPI(+ api_key="k", http_client=_mock_client(_responder(status, headers))+ )+ with pytest.raises(Exception) as excinfo: # noqa: PT011 — type is the assertion+ asyncio.run(provider.transcribe_pcm(_fake_pcm()))+ return excinfo.value+++def _raise_from_gemini(status: int, headers: dict[str, str] | None = None) -> BaseException:+ provider = GeminiSTT(+ client=_RaisingGenaiClient(_FakeGenaiAPIError(status, "RESOURCE_EXHAUSTED", headers))+ )+ with pytest.raises(Exception) as excinfo: # noqa: PT011 — type is the assertion+ asyncio.run(provider.transcribe_pcm(_fake_pcm()))+ return excinfo.value+++#: Every cloud STT plugin, by provider id. The behaviour these share is a+#: CAPABILITY — "the pipeline can read a status off my failure" — not a type+#: (AP-21). Groq reaches it through ``httpx.HTTPStatusError`` because that+#: plugin may not import ``jarvis.*`` at all, not even lazily (CLAUDE.md §5,+#: pinned by tests/contract/test_stt_protocol.py); the other three reach it+#: through the shared ``STTHTTPError``. Both satisfy the consumer, which is the+#: only thing that decides whether a user's turn survives a 429.+_RAISERS = {+ "openai-api": _raise_from_openai,+ "openrouter-stt": _raise_from_openrouter,+ "groq-api": _raise_from_groq,+ "gemini-api": _raise_from_gemini,+}++#: The subset that raises the shared typed error (see above for Groq's exemption).+_TYPED = ("openai-api", "openrouter-stt", "gemini-api")++[email protected]("provider_id", sorted(_RAISERS))+def test_a_429_is_classifiable_and_carries_the_retry_after(provider_id: str) -> None:+ """The whole point of F1: all four, not just the one with httpx's error."""+ exc = _RAISERS[provider_id](429, {"Retry-After": "7"})++ assert _stt_error_status(exc) == 429+ assert _is_transient_stt_error(exc) is True+ assert _stt_retry_delay(exc, 0) == pytest.approx(2.0), (+ "the pipeline must honour the server's delay (capped at its own ceiling), "+ "not fall through to its 0.4 s first-attempt guess"+ )++[email protected]("provider_id", sorted(_RAISERS))+def test_a_401_is_not_transient_and_is_never_retried(provider_id: str) -> None:+ """A dead key is not a blip. Retrying it only hammers the provider."""+ exc = _RAISERS[provider_id](401)++ assert _stt_error_status(exc) == 401+ assert _is_transient_stt_error(exc) is False++[email protected]("provider_id", sorted(_TYPED))+def test_the_typed_error_exposes_status_and_retry_after(provider_id: str) -> None:+ """The machine-readable facts, for a caller that wants them directly."""+ throttled = _RAISERS[provider_id](429, {"Retry-After": "7"})+ dead_key = _RAISERS[provider_id](401)++ assert isinstance(throttled, STTHTTPError)+ assert throttled.status == 429+ assert throttled.retry_after == 7.0+ assert isinstance(dead_key, STTHTTPError)+ assert dead_key.status == 401+ assert dead_key.retry_after is None++[email protected]("provider_id", sorted(_TYPED))+def test_the_typed_error_is_still_a_runtime_error(provider_id: str) -> None:+ """Existing ``except RuntimeError`` degradation paths must be untouched.++ The STT factory and the pipeline both treat a RuntimeError as "degrade to+ the local floor / apologise honestly". If the new type escaped those+ handlers, F1 would have traded a dead retry ladder for a crash.+ """+ exc = _RAISERS[provider_id](500)+ assert isinstance(exc, RuntimeError)+ assert _is_transient_stt_error(exc) is True+++def test_groq_keeps_raising_the_httpx_error_it_always_raised() -> None:+ """Groq's exemption is intentional — pin it so nobody "unifies" it.++ That plugin is under a total ``jarvis.*``-import ban (it re-implements even+ the keyring read for that reason), so it cannot reach the shared error type.+ It never needed it: its failure was already the one the pipeline could read,+ which is exactly why the retry ladder worked here and nowhere else.+ """+ exc = _raise_from_groq(429, {"Retry-After": "7"})++ assert isinstance(exc, httpx.HTTPStatusError)+ assert _stt_error_status(exc) == 429+ assert _stt_retry_delay(exc, 0) == pytest.approx(2.0)+++ "provider_id,needle",+ [+ ("openai-api", "OpenAI STT failed: OpenAI rate limit / quota exceeded"),+ ("openrouter-stt", "OpenRouter STT failed: OpenRouter rate limit / quota exceeded"),+ ],+)+def test_the_english_message_is_unchanged(provider_id: str, needle: str) -> None:+ """The human-readable reason is what a user sees in a log; only the TYPE moved."""+ exc = _RAISERS[provider_id](429)+ assert needle in str(exc)+ assert "slow down" in str(exc), "the provider's own detail must survive"+++def test_gemini_keeps_its_own_message_and_a_status_less_failure_stays_plain() -> None:+ """Gemini has no HTTP wire here — a transport error must NOT invent a status."""+ provider = GeminiSTT(client=_RaisingGenaiClient(TimeoutError("read timed out")))+ with pytest.raises(RuntimeError) as excinfo:+ asyncio.run(provider.transcribe_pcm(_fake_pcm()))++ assert not isinstance(excinfo.value, STTHTTPError), (+ "a timeout has no HTTP status; claiming one would be a lie"+ )+ assert "Gemini STT request failed" in str(excinfo.value)+ assert _stt_error_status(excinfo.value) is None+++# ---------------------------------------------------------------------------+# Retry-After parsing — both RFC 9110 forms+# ---------------------------------------------------------------------------+++def test_retry_after_accepts_the_delta_seconds_form() -> None:+ assert parse_retry_after("30") == 30.0+ assert parse_retry_after(" 2.5 ") == 2.5+++def test_retry_after_accepts_the_http_date_form() -> None:+ """A gateway in front of the provider answers with a date, not a delta."""+ now = datetime(2026, 7, 29, 12, 0, 0, tzinfo=UTC)+ header = format_datetime(now + timedelta(seconds=45), usegmt=True)++ delay = parse_retry_after(header, now=now.timestamp())++ assert delay == pytest.approx(45.0, abs=1.0)+++def test_retry_after_never_returns_a_negative_or_raises() -> None:+ """A past date, a clock skew, or garbage must degrade — never blow up."""+ now = datetime(2026, 7, 29, 12, 0, 0, tzinfo=UTC)+ past = format_datetime(now - timedelta(seconds=60), usegmt=True)++ assert parse_retry_after(past, now=now.timestamp()) == 0.0+ assert parse_retry_after("in a little while") is None+ assert parse_retry_after("") is None+ assert parse_retry_after(None) is None+++def test_retry_after_header_lookup_is_case_insensitive() -> None:+ """Providers send ``Retry-After``; the classifier looks for ``retry-after``."""+ exc = _raise_from_openai(429, {"RETRY-AFTER": "3"})+ assert exc.retry_after == 3.0+ assert exc.response.headers.get("retry-after") == "3"+++# ---------------------------------------------------------------------------+# The primitives themselves+# ---------------------------------------------------------------------------+++def test_status_from_exception_reads_all_three_shapes() -> None:+ typed = STTHTTPError("x", status=503)+ sdk_shaped = _FakeGenaiAPIError(429, "quota")+ httpx_shaped = httpx.HTTPStatusError(+ "boom",+ request=httpx.Request("POST", "https://example.invalid"),+ response=httpx.Response(502),+ )++ assert status_from_exception(typed) == 503+ assert status_from_exception(sdk_shaped) == 429+ assert status_from_exception(httpx_shaped) == 502+ assert status_from_exception(ValueError("nothing http here")) is None+ assert status_from_exception(None) is None+++def test_status_from_exception_ignores_a_non_status_integer() -> None:+ """``.code`` is not always an HTTP status — a subprocess exit code is not one."""++ class _ProcessError(Exception):+ code = 1++ assert status_from_exception(_ProcessError()) is None+++def test_http_error_from_response_falls_back_to_the_raw_body() -> None:+ """An overloaded gateway answers HTML; the only clue must still reach the log."""+ response = httpx.Response(503, text="<html>upstream is down</html>")++ exc = http_error_from_response(response, vendor="OpenRouter")++ assert exc.status == 503+ assert "OpenRouter STT HTTP 503" in str(exc)+ assert "upstream is down" in str(exc)+++def test_the_error_holds_no_reference_to_the_response_object() -> None:+ """The headers are copied, so a stored exception cannot pin a live response."""+ response = httpx.Response(429, json={}, headers={"Retry-After": "1"})++ exc = http_error_from_response(response, vendor="OpenAI")++ assert exc.response is not response+ assert exc.response.status_code == 429+ assert exc.response.headers.get("retry-after") == "1"+++# ---------------------------------------------------------------------------+# The Gemini timeout — the failure that raises nothing at all+# ---------------------------------------------------------------------------+++def test_gemini_timeout_is_expressed_in_milliseconds() -> None:+ """``HttpOptions.timeout`` is milliseconds, not seconds.++ Off by 1000x in the safe direction it is a 30-second wait that looks fine+ until a stall; in the other direction it times out every healthy request.+ Neither would be caught by a test that only asserted "a timeout is set".+ """+ assert GeminiSTT(timeout_s=2.5)._http_options() == {"timeout": 2500}+ assert GeminiSTT(timeout_s=30.0)._http_options() == {"timeout": 30_000}+++def test_gemini_timeout_has_a_floor_so_a_bad_value_cannot_brick_it() -> None:+ """0 or a negative value must bound the call, not reject every request."""+ assert GeminiSTT(timeout_s=0)._http_options() == {"timeout": 1000}+ assert GeminiSTT(timeout_s=-5)._http_options() == {"timeout": 1000}+++def test_gemini_client_is_built_with_the_timeout(monkeypatch: pytest.MonkeyPatch) -> None:+ """The wiring itself: without this the value is computed and thrown away."""+ genai = pytest.importorskip("google.genai")+ captured: dict[str, Any] = {}++ class _RecordingClient:+ def __init__(self, **kwargs: Any) -> None:+ captured.update(kwargs)++ monkeypatch.setattr(genai, "Client", _RecordingClient)++ GeminiSTT(api_key="k", timeout_s=4.0)._ensure_client()++ assert captured["api_key"] == "k"+ assert captured["http_options"] == {"timeout": 4000}+++def test_the_factory_forwards_a_configured_timeout(monkeypatch: pytest.MonkeyPatch) -> None:+ """A timeout in the config has to reach the provider constructor.++ Nothing else can bound a Gemini call: the pipeline's ``wait_for`` stops+ WAITING for the worker thread, it cannot stop the request inside it.+ """+ import jarvis.plugins.stt as stt_pkg+ from jarvis.core import config as cfg++ built: dict[str, Any] = {}++ class _Recording:+ def __init__(self, **kwargs: Any) -> None:+ built.update(kwargs)++ monkeypatch.setattr(stt_pkg, "_load_provider_class", lambda _name: _Recording)+ monkeypatch.setattr(cfg, "get_secret_any", lambda _candidates: "real-key")+ monkeypatch.setattr(+ cfg,+ "resolve_provider_endpoint",+ lambda pid, **kw: cfg.ResolvedEndpoint(+ base_url=None, credential=None, via_proxy=False+ ),+ )++ class _CfgWithTimeout:+ provider = "gemini-api"+ language = "auto"+ bias_prompt = ""+ timeout_s = 8.0++ stt_pkg.build_stt_from_config(_CfgWithTimeout())+ assert built["timeout_s"] == 8.0++ built.clear()++ class _CfgWithout:+ provider = "gemini-api"+ language = "auto"+ bias_prompt = ""++ stt_pkg.build_stt_from_config(_CfgWithout())+ assert "timeout_s" not in built, (+ "with nothing configured the provider must keep its own documented "+ "default rather than being handed a value the user never chose"+ )+++def test_a_provider_that_refuses_the_optional_kwargs_still_builds(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A third-party plugin predating ``timeout_s`` must not fall to local whisper.++ The retry used to drop only ``prompt``; a plugin that refuses ``timeout_s``+ would have failed the retry too and dead-ended on an engine the base install+ does not ship.+ """+ import jarvis.plugins.stt as stt_pkg+ from jarvis.core import config as cfg++ accepted: dict[str, Any] = {}++ class _OldPlugin:+ def __init__(self, *, language: str | None = None) -> None:+ accepted["language"] = language++ monkeypatch.setattr(stt_pkg, "_load_provider_class", lambda _name: _OldPlugin)+ monkeypatch.setattr(cfg, "get_secret_any", lambda _candidates: "real-key")+ monkeypatch.setattr(+ cfg,+ "resolve_provider_endpoint",+ lambda pid, **kw: cfg.ResolvedEndpoint(+ base_url=None, credential=None, via_proxy=False+ ),+ )++ class _Cfg:+ provider = "gemini-api"+ language = "de"+ bias_prompt = "Jarvis, Ruben"+ timeout_s = 8.0++ provider = stt_pkg.build_stt_from_config(_Cfg())++ assert isinstance(provider, _OldPlugin)+ assert accepted["language"] == "de"