Skip to content

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

fix(dictation): say why a transcription failed, not which library raised

Ruben Lütkec3fe646ebc83
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index effe89fe3f..2868ce1679 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -128,6 +128,11 @@ from jarvis.speech.hangup import (
from jarvis.speech.pending_buffer import PendingPromptBuffer
from jarvis.speech.persona import PhrasePicker, iter_all_start_ack
from jarvis.speech.rolling_whisper_wake import RollingWhisperWake
+from jarvis.speech.stt_failure import (
+ classify_stt_failure,
+ normalize_stt_failure,
+ stt_failure_message,
+)
from jarvis.speech.wake_verifier import (
CUSTOM_WAKE_MIN_RMS,
pcm_tail_rms,
@@ -938,8 +943,61 @@ from jarvis.speech.wake_constants import ( # noqa: E402
STT_HALLUCINATION_RE as _STT_HALLUCINATION_RE,
)
-# Paraphrase-Prefixes die Gemini/Claude bei Unsicherheit voranstellen.
-# Werden als Post-Processing vor dem TTS abgeschnitten.
+# Longest recording the silence-hallucination filter is allowed to judge. Above
+# it the filter stands down entirely: a person who spoke for three seconds said
+# something, and "thank you very much for the update" is a real sentence that
+# happens to open with the same words as the boilerplate. Below it there is
+# barely room for a real utterance, which is exactly the window in which a
+# near-silent microphone makes a Whisper-family model produce its subtitle
+# credits.
+_DICTATION_HALLUCINATION_MAX_S = 2.5
+
+# Words that occur in the hallucination markers themselves, DERIVED from the one
+# shared pattern rather than written out a second time — a second list would
+# stop agreeing with the first the day either is touched (BUG-008). Regex
+# metacharacters contribute the odd single letter, so anything shorter than two
+# characters is dropped; digits never enter, which is what lets a boilerplate
+# year ("copyright 2020") count as covered.
+_HALLUCINATION_WORD_RE = re.compile(r"[^\W\d_]{2,}", re.UNICODE)
+_HALLUCINATION_VOCABULARY: frozenset[str] = frozenset(
+ _HALLUCINATION_WORD_RE.findall(_STT_HALLUCINATION_RE.pattern.lower())
+)
+
+
+def _is_silence_hallucination(text: str, duration_s: float) -> bool:
+ """Is *text* boilerplate a silent microphone produced, not speech?
+
+ Two independent conditions, and BOTH are needed — either one alone gets a
+ real dictation deleted:
+
+ * **The recording is short.** Whisper hallucinates on near-silence, so the
+ filter only judges recordings too short to hold much else. The audio
+ length is the honest measure here (see the caller), not the wall clock.
+ * **The boilerplate is the WHOLE utterance.** ``_STT_HALLUCINATION_RE``
+ matches a substring, which is the right shape for the voice lane — there
+ the question is "may this reach the brain". On a transcript the question
+ is different: "thank you very much for the update" contains a marker and
+ is a sentence the user dictated. So a match is necessary but not
+ sufficient; every word of the transcript must also come from the markers'
+ own vocabulary. "Thank you for watching!" passes that test (the shared
+ pattern spells the outro "thanks for watching", and the vocabulary covers
+ the other spelling for free); "vielen Dank für das Update" does not,
+ because "update" is nobody's boilerplate.
+
+ Digits are ignored on purpose: the markers carry years, and a year is not
+ what distinguishes a hallucination from a sentence.
+ """
+ if duration_s >= _DICTATION_HALLUCINATION_MAX_S:
+ return False
+ body = (text or "").strip()
+ if not body or _STT_HALLUCINATION_RE.search(body) is None:
+ return False
+ words = _HALLUCINATION_WORD_RE.findall(body.lower())
+ return bool(words) and all(word in _HALLUCINATION_VOCABULARY for word in words)
+
+
+# Paraphrase prefixes Gemini/Claude put in front of an answer when unsure.
+# Cut off as post-processing before the TTS call.
_PARAPHRASE_PREFIXES: tuple[str, ...] = (
"ich verstehe, du moechtest", "ich verstehe du moechtest",
"ich verstehe, du möchtest", "ich verstehe du möchtest",
@@ -8373,7 +8431,7 @@ class SpeechPipeline:
DictationCompleted(
source_layer="speech.dictation",
outcome="failed",
- detail="No speech-to-text provider is available.",
+ detail=stt_failure_message("no_stt"),
error="no_stt",
)
)
@@ -8421,7 +8479,20 @@ class SpeechPipeline:
# the end: it is what separates "the provider rejected us" from "you
# said nothing", and without it a 401 arrives in the history looking
# exactly like silence — with no hint that a key needs fixing.
+ #
+ # A REASON CODE from ``jarvis.speech.stt_failure``, never the provider's
+ # own error text. This value is stored in the history and rendered under
+ # the user's words, and what it used to render was a Python exception
+ # class plus a vendor URL plus a link to an HTTP specification — three
+ # things that answer no question a person dictating a sentence has, and
+ # a string no locale can translate. The technical text is not lost; it
+ # rides along in ``stt_error_detail`` and goes to the log in full.
stt_error: str | None = None
+ # The provider's own words for the same failure. Log-only, deliberately:
+ # it is the half that names the endpoint and the client library, which
+ # is exactly what a debugger needs and exactly what a user must not be
+ # handed.
+ stt_error_detail: str = ""
# ``[dictation].language`` as chosen by the user. ``auto`` is passed
# THROUGH to the provider rather than dropped: omitting the argument
# means "no opinion", which lands on whatever ``[stt].language`` is
@@ -8449,7 +8520,7 @@ class SpeechPipeline:
nothing anywhere saying so. That is the reported "I said more than
this" bug in its entirety.
"""
- nonlocal stt_error
+ nonlocal stt_error, stt_error_detail
inference_active.set()
try:
try:
@@ -8462,12 +8533,14 @@ class SpeechPipeline:
# choice a failure — precedent: rolling_whisper_wake.
transcript = await stt.transcribe_pcm(pcm)
except Exception as exc: # noqa: BLE001 — one failed call is not fatal
- log.debug("dictation transcribe failed: %s", exc)
- stt_error = f"{type(exc).__name__}: {exc}".strip()
+ stt_error_detail = f"{type(exc).__name__}: {exc}".strip()
+ stt_error = classify_stt_failure(exc)
+ log.debug("dictation transcribe failed: %s", stt_error_detail)
return "", "", False
finally:
inference_active.clear()
stt_error = None
+ stt_error_detail = ""
text = (getattr(transcript, "text", "") or "").strip()
lang = str(getattr(transcript, "language", "") or "")
return text, lang, True
@@ -8530,9 +8603,10 @@ class SpeechPipeline:
# retries it, and the final pass sees it regardless.
log.info(
"dictation segment kept open after a failed "
- "transcription (%s) — backing off rather than dropping "
- "%.1fs of audio.",
- stt_error or "unknown error",
+ "transcription (%s: %s) — backing off rather than "
+ "dropping %.1fs of audio.",
+ stt_error or "unknown",
+ stt_error_detail or "no detail",
cut / bytes_per_second,
)
return False
@@ -8659,7 +8733,7 @@ class SpeechPipeline:
"consecutive failed pieces (%s) — %.1fs of audio kept "
"for a later retry rather than making you wait.",
dead_streak,
- stt_error or "unknown error",
+ stt_error_detail or stt_error or "unknown error",
len(remaining) / bytes_per_second,
)
break
@@ -8696,7 +8770,7 @@ class SpeechPipeline:
log.info(
"final dictation transcription failed (%s) — "
"retry %d/%d in %.1fs.",
- stt_error or "unknown error",
+ stt_error_detail or stt_error or "unknown error",
attempt + 1,
_DICTATION_FINAL_ATTEMPTS - 1,
delay,
@@ -8763,11 +8837,15 @@ class SpeechPipeline:
# as the whole thing.
drain_exc = drain_task.exception()
if drain_exc is not None:
- capture_error = (
- f"{type(drain_exc).__name__}: {drain_exc}".strip()
- )
+ # The stored value is the reason CODE, for the same
+ # reason ``stt_error`` is one: this ends up under the
+ # user's own words in the history. The exception text
+ # goes to the log, where it is useful.
+ capture_error = "recording_interrupted"
log.warning(
- "dictation recording ended early — %s", capture_error
+ "dictation recording ended early — %s: %s",
+ capture_error,
+ f"{type(drain_exc).__name__}: {drain_exc}".strip(),
)
else:
# A source that simply RAN OUT is not a fault — it is
@@ -8818,7 +8896,19 @@ class SpeechPipeline:
raw_text = " ".join([*closed_parts, tail_text]).strip()
final_text = raw_text
- duration_s = max(0.0, time.monotonic() - started_at)
+ # How long the user SPOKE — measured from the audio, not the clock.
+ # The clock starts before the microphone opens and stops after the
+ # last provider call, retry sleeps included, so a slow or
+ # rate-limited provider inflated the stored duration by seconds. That
+ # number is not decoration: the statistics sidecar divides the word
+ # count by it, so an inflated duration under-reports the user's words
+ # per minute and stretches every streak built on it. The captured PCM
+ # cannot drift — the capture contract is 16 kHz mono int16
+ # (``jarvis.audio.capture.SAMPLE_RATE``), so the byte count IS the
+ # recording length. The wall clock stays for the log line, where
+ # "spoke for 4 s, waited 11 s" is precisely the useful sentence.
+ wall_clock_s = max(0.0, time.monotonic() - started_at)
+ duration_s = len(buffer) / bytes_per_second
finished = True
result = await self._finish_dictation(
raw_text=raw_text,
@@ -8834,14 +8924,19 @@ class SpeechPipeline:
)
final_text = result
log.info(
- "🎙️ dictation ended (%d chars, %.1fs, target=%s, %.1fs silence "
- "skipped%s%s%s).",
+ "🎙️ dictation ended (%d chars, %.1fs spoken / %.1fs elapsed, "
+ "target=%s, %.1fs silence skipped%s%s%s).",
len(final_text),
duration_s,
+ wall_clock_s,
target,
skipped_silence_bytes / bytes_per_second,
", hung up" if hung_up else "",
- f", stt error: {stt_error}" if stt_error else "",
+ (
+ f", stt error: {stt_error} ({stt_error_detail or 'no detail'})"
+ if stt_error
+ else ""
+ ),
f", capture: {capture_error}" if capture_error else "",
)
except Exception as exc: # noqa: BLE001 — dictation must never break voice
@@ -8860,10 +8955,12 @@ class SpeechPipeline:
await self._finish_dictation(
raw_text="",
language=language,
- duration_s=max(0.0, time.monotonic() - started_at),
+ # Audio-derived here too: a crash mid-dictation must not
+ # write a row whose duration is mostly the crash.
+ duration_s=len(buffer) / bytes_per_second,
target=target,
hung_up=False,
- stt_error=f"{type(exc).__name__}: {exc}".strip(),
+ stt_error=classify_stt_failure(exc),
audio=bytes(buffer),
)
except Exception: # noqa: BLE001 — the fallback must not raise either
@@ -8894,7 +8991,9 @@ class SpeechPipeline:
source_layer="speech.dictation",
outcome="cancelled",
detail="The dictation ended before it produced text.",
- duration_s=max(0.0, time.monotonic() - started_at),
+ # Same measure as every other exit: what was recorded,
+ # not how long the machinery took to give up.
+ duration_s=len(buffer) / bytes_per_second,
)
)
@@ -8920,11 +9019,19 @@ class SpeechPipeline:
``stt_error`` is the transcription failure, if there was one. It is what
makes ``failed`` distinguishable from ``empty``, so it is carried into
the completion event and the history row rather than logged and dropped.
+ It is normalised to a reason code HERE rather than trusted from the
+ caller: this method is the one place the value is persisted and
+ published, and a raw provider string reaching it is exactly how a Python
+ exception class and a vendor URL ended up rendered under a user's own
+ dictated words. A backstop at the store beats a rule every future caller
+ has to remember.
+
``audio`` is the session's raw PCM; it is written to a local sidecar
only when the dictation produced nothing usable AND the user allows it
(``[dictation].keep_failed_audio``), which is what a later Restore
transcribes again.
"""
+ stt_error = normalize_stt_failure(stt_error)
cleaned = raw_text
removed_words = 0
cleanup_reason = ""
@@ -8936,34 +9043,61 @@ class SpeechPipeline:
# reason="no_rules", i.e. no cleanup at all despite an explicit pin.
pinned = str(getattr(cfg, "language", "auto") or "auto").strip().lower()
effective_language = pinned if pinned not in ("", "auto") else language
- # Last resort: read the language off the TEXT. Not every provider
- # reports one — ``transcribe_pcm`` is only contracted to return text —
- # and on ``[dictation].language = auto`` (the shipped default) a silent
- # provider left ``effective_language`` empty, which the cleanup can only
- # answer with "no rules for this language". The observable consequence
- # is the whole filler removal never running: every "äh" and "ähm" the
- # user hesitated with shipped straight into the text while the setting
- # said it was on. Resolved through the ONE canonical language resolver
- # (CLAUDE.md §1: no layer invents its own detection), and only when
- # nothing better is known — a provider that DID report a language keeps
- # the last word.
- if raw_text and not hung_up:
+ # Which language the cleanup rules run in. Three signals can answer that
+ # and the ORDER between them is the whole fix:
+ #
+ # 1. The user's pin wins, always. It is the one signal a person can set,
+ # so overruling it would leave them no way to be right — which is why
+ # this block does not run at all once ``pinned`` names a language.
+ # 2. Otherwise the TEXT outranks a provider tag that CONTRADICTS it. The
+ # cloud Whisper APIs report a language on every request and report it
+ # confidently when it is wrong: the live 2026-07-28 history has German
+ # dictations tagged "English". The old gate only consulted the text
+ # when the tag was UNPARSEABLE, and ``normalize_language_tag`` turns
+ # "English" into "en", never "unknown" — so a confidently wrong tag
+ # always won. What that costs is not cosmetic. The English filler list
+ # used to contain "er", a top-frequency German pronoun, so a German
+ # sentence tagged English came back with its pronouns deleted and the
+ # cleanup reported a clean success.
+ # 3. A tag we cannot place stays exactly as it is. ``detect_text_language``
+ # only knows de/en/es, so letting it overrule a "French" or "ja" tag
+ # would relabel that dictation as whichever of the three it scored
+ # highest on and then run THAT language's filler rules over it.
+ # Keeping the tag makes the cleanup a documented no-op
+ # (``reason="no_rules"``), which is the honest answer for ~95 of the
+ # 100 recognition languages this feature supports.
+ #
+ # A provider that reports nothing at all is the one case where the text
+ # is the only signal there is: ``[dictation].language = auto`` (the
+ # shipped default) plus a silent provider used to leave the cleanup with
+ # "no rules for this language", so every "äh" the user hesitated with
+ # shipped straight into the text while the setting said it was on.
+ # Everything resolves through the canonical resolver's helpers — no layer
+ # invents its own detection (CLAUDE.md §1).
+ if raw_text and not hung_up and pinned in ("", "auto"):
try:
from jarvis.core.turn_language import (
detect_text_language,
normalize_language_tag,
)
- if normalize_language_tag(effective_language) == "unknown":
- detected = detect_text_language(raw_text)
- if detected != "unknown":
- log.debug(
- "dictation language resolved from the transcript: %s "
- "(the provider reported %r)",
- detected,
- language,
- )
- effective_language = detected
+ reported = str(effective_language or "").strip().lower()
+ tag_code = normalize_language_tag(reported)
+ detected = detect_text_language(raw_text)
+ if detected != "unknown" and (
+ # Nothing to contradict: no tag at all, or one that says
+ # "I could not tell".
+ reported in ("", "auto", "unknown", "und")
+ # A tag we CAN place, which the text disagrees with.
+ or (tag_code != "unknown" and tag_code != detected)
+ ):
+ log.debug(
+ "dictation language resolved from the transcript: %s "
+ "(the provider reported %r)",
+ detected,
+ language,
+ )
+ effective_language = detected
except Exception: # noqa: BLE001 — a detection hiccup is not fatal
log.debug("dictation language detection failed", exc_info=True)
@@ -8987,6 +9121,54 @@ class SpeechPipeline:
exc_info=True)
cleaned = raw_text
+ # Two kinds of text must never reach a document, and both used to.
+ #
+ # (a) Whisper's silence boilerplate. Every Whisper-family model answers a
+ # near-silent microphone with the same handful of subtitle credits
+ # and video outros — 12 of the first 26 rows of the live history are
+ # "Thank you." or "Thank you for watching!", none of them spoken. The
+ # repo has owned the marker list for months and the voice lane
+ # filters on it in four places; the dictation lane never did.
+ # (b) A transcript with no WORDS in it. A bare "." was pasted into a live
+ # document (history row 2026-07-28T18:10:30) and the clipboard was
+ # then restored over it, so the user was left holding a stray full
+ # stop and no way back to what they had copied.
+ #
+ # Blanking the text HERE, rather than only skipping the insertion, is
+ # deliberate: the final transcript published below also feeds the chat
+ # composer and the bar, and a dictation that reports "empty" while its
+ # text already sits in the composer is the same defect in a different
+ # window. ``raw_text`` is untouched, so the history row still shows what
+ # the provider returned and a later Restore can transcribe the audio
+ # again. Fail-open like every other step here: a broken gate costs the
+ # gate, never the user's words.
+ rejected_detail = ""
+ if cleaned.strip() and not hung_up:
+ try:
+ from jarvis.dictation.cleanup import count_words
+
+ if count_words(cleaned) == 0:
+ rejected_detail = (
+ "The dictation produced punctuation but no words, so "
+ "nothing was inserted."
+ )
+ elif _is_silence_hallucination(cleaned, duration_s):
+ rejected_detail = (
+ "The audio was too quiet to resolve, so nothing was "
+ "inserted."
+ )
+ if rejected_detail:
+ log.info(
+ "dictation delivery refused (%.1fs of audio, %r): %s",
+ duration_s,
+ cleaned[:80],
+ rejected_detail,
+ )
+ cleaned = ""
+ except Exception: # noqa: BLE001 — a broken guard never eats the text
+ log.debug("dictation delivery gate failed", exc_info=True)
+ rejected_detail = ""
+
# Publish the final transcript first: the chat composer and the bar
# both listen for it, and they should update even if insertion fails.
try:
@@ -9023,6 +9205,18 @@ class SpeechPipeline:
# this branch: a provider error is a "failed" the user can act on
# (fix the key, switch provider), silence is just an "empty".
outcome_name = "failed" if stt_error else "empty"
+ if stt_error:
+ # ``detail`` is the sentence surfaces without a locale of their
+ # own show verbatim (the Jarvis Bar, the CLI) — and until now a
+ # failed dictation left it empty, so the bar said nothing at all
+ # about why the words never arrived. The localized half is the
+ # reason CODE on ``error``, which the UI translates.
+ detail = stt_failure_message(stt_error)
+ elif rejected_detail:
+ # Nothing arrived because what arrived was not speech. Saying so
+ # is the difference between "your microphone heard nothing" and
+ # an unexplained empty result after the user clearly spoke.
+ detail = rejected_detail
elif resolved_target == "insert":
insert_result = await asyncio.to_thread(self._insert_dictation, cleaned)
outcome_name = insert_result.status
diff --git a/jarvis/speech/stt_dictionary.py b/jarvis/speech/stt_dictionary.py
index 80b647aa47..38c5842da5 100644
--- a/jarvis/speech/stt_dictionary.py
+++ b/jarvis/speech/stt_dictionary.py
@@ -479,8 +479,16 @@ class DictionaryCorrectingSTT:
@property
def provider_label(self) -> str:
- """Human-readable inner provider name for log lines."""
- return type(self._inner).__name__
+ """Human-readable inner provider name for log lines.
+
+ Delegates when the inner object carries a label of its own. Since the
+ runtime fallback chain started wrapping the real provider, the class
+ name here resolved to ``FallbackSTT`` and the transcription log stopped
+ naming which provider actually ran — the one fact you need when a
+ provider is the thing failing, which is exactly when someone reads it.
+ """
+ inner = getattr(self._inner, "provider_label", "")
+ return str(inner) if inner else type(self._inner).__name__
def __getattr__(self, name: str) -> Any:
return getattr(self._inner, name)
diff --git a/jarvis/speech/stt_failure.py b/jarvis/speech/stt_failure.py
new file mode 100644
index 0000000000..f200c47250
--- /dev/null
+++ b/jarvis/speech/stt_failure.py
@@ -0,0 +1,325 @@
+"""Why a transcription failed, in ONE word every layer can act on.
+
+Why this file exists
+--------------------
+A failed transcription used to be recorded as whatever string the provider's
+HTTP client happened to raise, and that string was rendered verbatim in the
+dictation history. What a user actually saw under their own words was::
+
+ HTTPStatusError: Client error '429 Too Many Requests' for url
+ 'https://api.groq.com/openai/v1/audio/transcriptions' For more information
+ check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429
+
+Three things are wrong with that, and only the first one is cosmetic:
+
+* it is a stack-trace fragment shown to a person who wanted to dictate a
+ sentence — it names a Python exception class, a vendor URL and a link to an
+ HTTP specification, and none of those answer "what do I do now";
+* it hard-codes the identity of a provider into the user-visible surface, which
+ is exactly what §3 forbids — the message must read the same for whoever's key
+ is configured, and it must not leak an endpoint into a stored history file;
+* it is untranslatable. The string is assembled by a third-party library, so no
+ locale can ever render it, and the runtime output-language doctrine (one
+ resolver, ALL user-facing output) simply cannot reach it.
+
+So the pipeline stores a **reason code** — the same discipline
+``jarvis.dictation.outcomes`` already applies to how a dictation ended — and the
+UI translates it through ``dictation.failure.<reason>``. The technical detail is
+not lost: it keeps going to the log, in full, where the person debugging it
+actually looks.
+
+Deliberately string-matched, not type-matched
+--------------------------------------------
+The STT tier has five providers behind four different HTTP clients (httpx,
+aiohttp, the google-genai SDK, and a bare ``OSError`` from the local engine), so
+there is no shared exception type to switch on and a status attribute exists on
+some of them only. Classification therefore runs over
+``"<ExceptionType>: <message>"`` — a capability question ("could another
+provider survive this?"), never a provider-identity one (AP-21).
+
+This module is the single source of that judgement:
+:mod:`jarvis.speech.stt_fallback` derives its own crossable/not-crossable answer
+from :func:`classify_stt_failure` rather than keeping a second marker table,
+because two tables that must agree are two tables that will not.
+"""
+
+from __future__ import annotations
+
+from typing import Final
+
+#: Every reason a transcription can fail, as stored on
+#: ``DictationCompleted.error`` and in the dictation history sidecar. Mirrored
+#: in TypeScript as ``STT_FAILURE_REASONS`` and pinned by a parity test — a
+#: value missing from the mirror renders as a raw identifier at the user, which
+#: is the drift this repo has hit four times (AP-4 / BUG-008).
+#:
+#: ``rate_limited``
+#: The provider accepted the key and refused the request: too many calls in
+#: its window. Waiting fixes it; changing anything else does not.
+#: ``no_credit``
+#: The account behind the key is out of credit or past its billing quota.
+#: ``bad_key``
+#: The key was missing, expired or rejected. The one reason that needs the
+#: user to go and do something in the API-keys view.
+#: ``unavailable``
+#: The service could not be reached — a 5xx, a timeout, a dropped
+#: connection. Nothing is wrong with the account or the audio.
+#: ``rejected``
+#: The provider understood the request and refused it (a 400-class answer:
+#: unsupported format, audio too large). Another provider would refuse the
+#: same bytes, so this is the one class that must NOT be retried elsewhere.
+#: ``engine_busy``
+#: The local engine was still working on the previous call. A real and
+#: recurring shape here (AP-24 / BUG-036), and worth its own sentence: it is
+#: the one failure that is nobody's fault and fixes itself.
+#: ``recording_interrupted``
+#: The microphone stream ended before the user stopped dictating. Not a
+#: transcription failure at all — but it is the reason the transcript is
+#: short, and presenting a truncated result as complete is the worse lie.
+#: ``no_stt``
+#: No speech-to-text provider is configured or installed.
+#: ``unknown``
+#: Anything else. Kept as an explicit member rather than an empty string so
+#: "it failed and we cannot say why" stays distinguishable from "it did not
+#: fail".
+STT_FAILURE_REASONS: Final[tuple[str, ...]] = (
+ "rate_limited",
+ "no_credit",
+ "bad_key",
+ "unavailable",
+ "rejected",
+ "engine_busy",
+ "recording_interrupted",
+ "no_stt",
+ "unknown",
+)
+
+# Ordered most-specific first: a 429 body frequently also says "quota", and a
+# credential error frequently also says "invalid request", so the first match
+# wins and the order below IS the precedence.
+
+#: Deliberately narrow. A bare ``"busy"`` would also match a microphone the OS
+#: refused, which is a different problem with a different answer.
+_ENGINE_BUSY_MARKERS: Final[tuple[str, ...]] = (
+ "transcribebusy",
+ "already in flight",
+ "resource busy",
+ "device busy",
+)
+_RATE_LIMITED_MARKERS: Final[tuple[str, ...]] = (
+ "429",
+ "too many requests",
+ "rate limit",
+ "rate_limit",
+ "ratelimit",
+)
+
+_NO_CREDIT_MARKERS: Final[tuple[str, ...]] = (
+ "402",
+ "payment required",
+ "insufficient_quota",
+ "insufficient quota",
+ "quota",
+ "billing",
+ "credit balance",
+ "out of credit",
+)
+
+_BAD_KEY_MARKERS: Final[tuple[str, ...]] = (
+ "401",
+ "403",
+ "unauthorized",
+ "invalid api key",
+ "invalid_api_key",
+ "api_key missing",
+ "api key missing",
+ "authentication",
+ "permission denied",
+)
+
+_UNAVAILABLE_MARKERS: Final[tuple[str, ...]] = (
+ "500",
+ "502",
+ "503",
+ "504",
+ "internal server error",
+ "bad gateway",
+ "service unavailable",
+ "gateway timeout",
+ "overloaded",
+ "temporarily",
+ "timeout",
+ "timed out",
+ "connection",
+ "connecterror",
+ "readerror",
+ "remoteprotocolerror",
+)
+
+_REJECTED_MARKERS: Final[tuple[str, ...]] = (
+ "400",
+ "413",
+ "415",
+ "422",
+ "bad request",
+ "invalid request",
+ "unsupported",
+ "too large",
+)
+
+#: reason -> the markers that identify it, in precedence order.
+_MARKERS: Final[tuple[tuple[str, tuple[str, ...]], ...]] = (
+ ("engine_busy", _ENGINE_BUSY_MARKERS),
+ ("rate_limited", _RATE_LIMITED_MARKERS),
+ ("no_credit", _NO_CREDIT_MARKERS),
+ ("bad_key", _BAD_KEY_MARKERS),
+ ("unavailable", _UNAVAILABLE_MARKERS),
+ ("rejected", _REJECTED_MARKERS),
+)
+
+#: The reasons another provider deserves a shot at the SAME audio. ``rejected``
+#: is excluded on purpose: the provider understood the request and refused it,
+#: so re-sending those bytes elsewhere burns a second quota for the same answer.
+#: ``unknown`` is excluded because an unclassified failure is, by definition,
+#: not known to be survivable. ``engine_busy`` is excluded to keep the chain
+#: behaving exactly as it did before this vocabulary existed: a busy local
+#: engine is the normal "try again in a moment" of AP-24's non-blocking lock,
+#: and turning every one of those into a cloud call would spend a request to
+#: avoid a wait of milliseconds.
+CROSSABLE_REASONS: Final[frozenset[str]] = frozenset(
+ {"rate_limited", "no_credit", "bad_key", "unavailable"}
+)
+
+#: English sentences for the surfaces that have no locale of their own — the
+#: log, the CLI, ``DictationCompleted.detail``. The UI does NOT read these; it
+#: translates the reason code through ``dictation.failure.<reason>`` so the
+#: message follows the user's language like every other user-facing string.
+#: Deliberately provider-neutral: the sentence must read the same whichever key
+#: the downloader configured (§3).
+_MESSAGES: Final[dict[str, str]] = {
+ "rate_limited": "Speech recognition hit the provider's rate limit.",
+ "no_credit": "The speech recognition account is out of credit.",
+ "bad_key": "The speech recognition key was rejected.",
+ "unavailable": "The speech recognition service could not be reached.",
+ "rejected": "The speech recognition service could not process this audio.",
+ "engine_busy": "The speech recognition engine was still busy.",
+ "recording_interrupted": "The recording ended before you stopped it.",
+ "no_stt": "No speech-to-text provider is available.",
+ "unknown": "Speech recognition failed.",
+}
+
+
+def classify_stt_failure(exc: BaseException | str | None) -> str:
+ """One member of :data:`STT_FAILURE_REASONS` for ``exc``.
+
+ Accepts an exception or an already-formatted string, because the failure
+ crosses a couple of layers before it is stored and re-classifying a string
+ must give the same answer as classifying the exception it came from.
+
+ ``None`` and an empty string classify as ``"unknown"`` rather than raising:
+ this runs on the path that is ALREADY handling a failure, and a classifier
+ that can itself fail would turn a recoverable dictation into a crash.
+ """
+ if exc is None:
+ return "unknown"
+ if isinstance(exc, str):
+ blob = exc.lower()
+ else:
+ blob = f"{type(exc).__name__}: {exc}".lower()
+ if not blob.strip():
+ return "unknown"
+ # An explicit status beats text matching when the provider gave us one: the
+ # message body of a 503 can easily contain the word "quota". Duck-typed
+ # across the three shapes the STT tier raises (our own typed error, the
+ # google-genai SDK's ``.code``, the httpx ``.response.status_code``) so this
+ # module needs no HTTP client and no provider import.
+ status = _status_of(exc)
+ if status is not None:
+ by_status = _reason_for_status(status)
+ if by_status is not None:
+ return by_status
+ for reason, markers in _MARKERS:
+ if any(marker in blob for marker in markers):
+ return reason
+ return "unknown"
+
+
+def normalize_stt_failure(value: BaseException | str | None) -> str | None:
+ """A reason code for ``value``, passing an already-valid code through.
+
+ The backstop that belongs at the STORE, not at each caller.
+ :func:`classify_stt_failure` is deliberately not idempotent — ``"bad_key"``
+ contains none of the markers that identify a bad key, so classifying an
+ already-classified value would answer ``"unknown"`` and quietly destroy the
+ reason. Every path that persists or publishes a failure goes through here
+ instead, so a caller that hands over a raw provider string cannot put one
+ back in front of the user, and one that hands over a code keeps it.
+
+ ``None`` (and a blank string) stays ``None``: "no failure" must remain
+ distinguishable from "failed for an unknown reason".
+ """
+ if value is None:
+ return None
+ if isinstance(value, str):
+ if not value.strip():
+ return None
+ if value in STT_FAILURE_REASONS:
+ return value
+ return classify_stt_failure(value)
+
+
+def stt_failure_message(reason: str | None) -> str:
+ """The English sentence for ``reason``, for logs / CLI / API ``detail``.
+
+ An unrecognised reason degrades to the ``unknown`` sentence rather than
+ echoing the raw value, so a newer backend talking to an older consumer still
+ produces a sentence instead of an identifier.
+ """
+ return _MESSAGES.get(str(reason or ""), _MESSAGES["unknown"])
+
+
+def is_crossable_failure(reason: str | None) -> bool:
+ """``True`` when another provider deserves a shot at the same audio."""
+ return str(reason or "") in CROSSABLE_REASONS
+
+
+def _status_of(exc: BaseException | str | None) -> int | None:
+ """The HTTP status behind ``exc``, or ``None`` when there is not one."""
+ if exc is None or isinstance(exc, str):
+ return None
+ for candidate in (
+ getattr(exc, "status", None),
+ getattr(exc, "code", None),
+ getattr(getattr(exc, "response", None), "status_code", None),
+ ):
+ # ``True`` is an int in Python; a boolean flag is never a status.
+ if isinstance(candidate, bool):
+ continue
+ if isinstance(candidate, int) and 100 <= candidate <= 599:
+ return candidate
+ return None
+
+
+def _reason_for_status(status: int) -> str | None:
+ """The reason a bare HTTP status implies, or ``None`` when it implies none."""
+ if status == 429:
+ return "rate_limited"
+ if status == 402:
+ return "no_credit"
+ if status in (401, 403):
+ return "bad_key"
+ if status >= 500:
+ return "unavailable"
+ if 400 <= status < 500:
+ return "rejected"
+ return None
+
+
+__all__ = [
+ "CROSSABLE_REASONS",
+ "STT_FAILURE_REASONS",
+ "classify_stt_failure",
+ "is_crossable_failure",
+ "normalize_stt_failure",
+ "stt_failure_message",
+]
diff --git a/jarvis/speech/stt_fallback.py b/jarvis/speech/stt_fallback.py
index 28ad9ed154..c9fb9657f4 100644
--- a/jarvis/speech/stt_fallback.py
+++ b/jarvis/speech/stt_fallback.py
@@ -46,64 +46,27 @@ RATE_LIMIT_COOLDOWN_S = 60.0
#: as soon as it can.
TRANSIENT_COOLDOWN_S = 15.0
-#: Substrings identifying a failure ANOTHER provider could survive. Matched
-#: against ``"<ExceptionType>: <message>"`` rather than against a status-code
-#: attribute, because the providers raise whatever their own HTTP client raises
-#: (httpx, aiohttp, google-genai, a bare OSError) and there is no shared type to
-#: switch on. Capability, not provider identity (AP-21).
-_QUOTA_MARKERS = (
- "429",
- "too many requests",
- "rate limit",
- "ratelimit",
- "quota",
- "insufficient_quota",
- "402",
- "payment required",
- "billing",
- "credit balance",
-)
-
-_AVAILABILITY_MARKERS = (
- "500", "502", "503", "504",
- "internal server error",
- "bad gateway",
- "service unavailable",
- "gateway timeout",
- "overloaded",
- "timeout",
- "timed out",
- "connection",
- "connecterror",
- "readerror",
- "remoteprotocolerror",
- "temporarily",
-)
-
-#: An expired / missing / rejected credential. Crossing over is the honest move:
-#: the user has another key that works, and telling them "dictation is broken"
-#: while a working provider sits unused is the single-provider brick AP-22 names.
-_CREDENTIAL_MARKERS = (
- "401",
- "403",
- "unauthorized",
- "invalid api key",
- "invalid_api_key",
- "authentication",
- "permission denied",
-)
+#: Reasons whose cooldown is the LONG one. A quota window and a rejected key
+#: both need real time to change; a 5xx or a dropped connection does not.
+_LONG_COOLDOWN_REASONS = frozenset({"rate_limited", "no_credit", "bad_key"})
def _classify(exc: BaseException) -> str:
- """``"quota"`` / ``"transient"`` / ``"credential"`` / ``""`` (do not cross)."""
- blob = f"{type(exc).__name__}: {exc}".lower()
- if any(m in blob for m in _QUOTA_MARKERS):
- return "quota"
- if any(m in blob for m in _CREDENTIAL_MARKERS):
- return "credential"
- if any(m in blob for m in _AVAILABILITY_MARKERS):
- return "transient"
- return ""
+ """The failure reason when another provider deserves a shot, else ``""``.
+
+ Delegates to :func:`jarvis.speech.stt_failure.classify_stt_failure` rather
+ than keeping a second marker table. The same judgement is what the dictation
+ history stores and what the UI translates, and two tables that must agree
+ are two tables that will not (AP-4).
+
+ A ``rejected`` (400-class) answer deliberately returns ``""``: the provider
+ understood the request and refused it, so another one would refuse the same
+ bytes and only burn a second quota to say so.
+ """
+ from jarvis.speech.stt_failure import classify_stt_failure, is_crossable_failure
+
+ reason = classify_stt_failure(exc)
+ return reason if is_crossable_failure(reason) else ""
def _is_crossable(exc: BaseException) -> bool:
@@ -171,7 +134,11 @@ class FallbackSTT:
return time.monotonic() >= until
def _penalize(self, name: str, kind: str) -> None:
- seconds = RATE_LIMIT_COOLDOWN_S if kind in ("quota", "credential") else TRANSIENT_COOLDOWN_S
+ seconds = (
+ RATE_LIMIT_COOLDOWN_S
+ if kind in _LONG_COOLDOWN_REASONS
+ else TRANSIENT_COOLDOWN_S
+ )
self._cooldown[name] = time.monotonic() + seconds
def _instance(self, name: str) -> Any:
diff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.ts
index 27910ec8ba..246dce3875 100644
--- a/jarvis/ui/web/frontend/src/hooks/useDictation.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts
@@ -29,6 +29,33 @@ export const DICTATION_OUTCOMES = [
export type DictationOutcome = (typeof DICTATION_OUTCOMES)[number];
+/**
+ * Why a transcription failed, mirroring
+ * `jarvis.speech.stt_failure.STT_FAILURE_REASONS`.
+ *
+ * The backend stores a reason CODE rather than the provider's own error text,
+ * because that text was a Python exception class plus a vendor URL plus a link
+ * to an HTTP specification — rendered verbatim under the user's own words, and
+ * untranslatable by any locale. Same rule as the outcomes above: never render a
+ * raw reason, always translate through `dictation.failure.{name}`.
+ *
+ * The TypeScript half of a cross-layer parity test; the Python tuple and this
+ * list must stay set-equal.
+ */
+export const STT_FAILURE_REASONS = [
+ "rate_limited",
+ "no_credit",
+ "bad_key",
+ "unavailable",
+ "rejected",
+ "engine_busy",
+ "recording_interrupted",
+ "no_stt",
+ "unknown",
+] as const;
+
+export type SttFailureReason = (typeof STT_FAILURE_REASONS)[number];
+
/** Languages dictation can be pinned to; `auto` lets the provider decide. */
export type DictationLanguage = "auto" | "de" | "en" | "es";
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 04b2711297..beaa8856e1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -289,6 +289,17 @@
"empty": "Nichts gehört",
"cancelled": "Abgebrochen",
"failed": "Fehlgeschlagen"
+ },
+ "failure": {
+ "rate_limited": "Die Spracherkennung hat ihr Anfragelimit erreicht — es können Wörter fehlen.",
+ "no_credit": "Das Guthaben für die Spracherkennung ist aufgebraucht.",
+ "bad_key": "Der Schlüssel für die Spracherkennung wurde abgelehnt — prüfe ihn unter API-Keys.",
+ "unavailable": "Die Spracherkennung war nicht erreichbar.",
+ "rejected": "Die Spracherkennung konnte diese Aufnahme nicht verarbeiten.",
+ "engine_busy": "Die Spracherkennung war noch beschäftigt — versuch es gleich noch einmal.",
+ "recording_interrupted": "Die Aufnahme endete, bevor du gestoppt hast.",
+ "no_stt": "Es ist noch keine Spracherkennung eingerichtet.",
+ "unknown": "Die Spracherkennung ist fehlgeschlagen."
}
},
"voice": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index dec8636edc..1ba33609ad 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -289,6 +289,17 @@
"empty": "Nothing heard",
"cancelled": "Cancelled",
"failed": "Failed"
+ },
+ "failure": {
+ "rate_limited": "Speech recognition hit its request limit — words may be missing.",
+ "no_credit": "The speech recognition account is out of credit.",
+ "bad_key": "The speech recognition key was rejected — check it under API Keys.",
+ "unavailable": "The speech recognition service could not be reached.",
+ "rejected": "Speech recognition could not process this recording.",
+ "engine_busy": "Speech recognition was still busy — try again in a moment.",
+ "recording_interrupted": "The recording ended before you stopped it.",
+ "no_stt": "No speech recognition is set up yet.",
+ "unknown": "Speech recognition failed."
}
},
"voice": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 92dacc983a..de6dabba6a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -289,6 +289,17 @@
"empty": "No se oyó nada",
"cancelled": "Cancelado",
"failed": "Fallido"
+ },
+ "failure": {
+ "rate_limited": "El reconocimiento de voz alcanzó su límite de peticiones: pueden faltar palabras.",
+ "no_credit": "La cuenta de reconocimiento de voz se quedó sin saldo.",
+ "bad_key": "La clave de reconocimiento de voz fue rechazada: revísala en Claves de API.",
+ "unavailable": "No se pudo contactar con el servicio de reconocimiento de voz.",
+ "rejected": "El reconocimiento de voz no pudo procesar esta grabación.",
+ "engine_busy": "El reconocimiento de voz seguía ocupado: inténtalo de nuevo en un momento.",
+ "recording_interrupted": "La grabación terminó antes de que la detuvieras.",
+ "no_stt": "Todavía no hay reconocimiento de voz configurado.",
+ "unknown": "El reconocimiento de voz falló."
}
},
"voice": {
diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx
index 9a42d67737..85a1804e5c 100644
--- a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx
@@ -3,6 +3,7 @@ import { Check, Copy, RotateCcw, Trash2, Volume2 } from "lucide-react";
import {
DICTATION_OUTCOMES,
+ STT_FAILURE_REASONS,
type DictationEntry,
} from "@/hooks/useDictation";
import { useT } from "@/i18n";
@@ -113,8 +114,11 @@ function HistoryRow({
</p>
)}
{entry.error && (
- <p className="mt-0.5 break-words text-[11px] text-destructive">
- {entry.error}
+ <p
+ className="mt-0.5 break-words text-[11px] text-destructive"
+ data-testid="dictation-failure-reason"
+ >
+ {failureLabel(t, entry.error)}
</p>
)}
<div className="mt-1 flex flex-wrap items-center gap-2 text-[10px] text-muted-foreground">
@@ -224,6 +228,8 @@ function HistoryRow({
const KNOWN_OUTCOMES: ReadonlySet<string> = new Set(DICTATION_OUTCOMES);
+const KNOWN_FAILURES: ReadonlySet<string> = new Set(STT_FAILURE_REASONS);
+
/**
* Translates an outcome through its i18n key. A value this bundle does not
* know (newer backend, older frontend) falls back to the raw string rather
@@ -232,3 +238,20 @@ const KNOWN_OUTCOMES: ReadonlySet<string> = new Set(DICTATION_OUTCOMES);
function outcomeLabel(t: (key: string) => string, outcome: string): string {
return KNOWN_OUTCOMES.has(outcome) ? t(`dictation.outcome.${outcome}`) : outcome;
}
+
+/**
+ * Translates a transcription failure through its i18n key.
+ *
+ * Unlike `outcomeLabel`, an unknown value does NOT fall through to the raw
+ * string. This line exists to tell a person why their words did not arrive, and
+ * the raw value here is either a stack-trace fragment stored by an older
+ * version — the exact thing this replaced — or a reason code from a newer
+ * backend, which is an identifier and explains nothing either. Both are better
+ * served by the honest generic sentence; the technical detail is in the log,
+ * where whoever needs it is already looking.
+ */
+function failureLabel(t: (key: string) => string, reason: string): string {
+ return KNOWN_FAILURES.has(reason)
+ ? t(`dictation.failure.${reason}`)
+ : t("dictation.failure.unknown");
+}
diff --git a/tests/unit/dictation/test_delivery_and_bar.py b/tests/unit/dictation/test_delivery_and_bar.py
index 1fb89edecc..d9189a2078 100644
--- a/tests/unit/dictation/test_delivery_and_bar.py
+++ b/tests/unit/dictation/test_delivery_and_bar.py
@@ -183,7 +183,13 @@ async def test_a_transcription_failure_is_reported_as_failed_not_empty() -> None
)
completed = next(e for e in events if isinstance(e, DictationCompleted))
assert completed.outcome == "failed"
- assert "401" in (completed.error or "")
+ # Normalised at the store: a caller handing over the provider's raw text
+ # must not be able to put a stack-trace fragment in front of the user.
+ assert completed.error == "bad_key"
+ assert "401" not in (completed.error or ""), "raw provider text is back"
+ # ``detail`` is what surfaces without a locale of their own (the bar, the
+ # CLI) show verbatim, so a failed dictation must not leave it empty.
+ assert completed.detail.strip()
@pytest.mark.asyncio
@@ -367,7 +373,9 @@ async def test_a_wordless_failure_is_still_recorded(audio_spy) -> None:
)
added = _FakeHistory.instances[-1].added
assert added and added[0]["outcome"] == "failed"
- assert added[0]["error"] == "RuntimeError: engine wedged"
+ # Stored as a reason code. This particular text matches no known shape, so
+ # the honest answer is the catch-all rather than the raw exception string.
+ assert added[0]["error"] == "unknown"
@pytest.mark.asyncio
@@ -489,11 +497,19 @@ async def test_the_pinned_language_reaches_the_provider(
@pytest.mark.asyncio
-async def test_auto_sends_no_language_at_all(
+async def test_auto_asks_the_provider_to_detect_instead_of_staying_silent(
monkeypatch: pytest.MonkeyPatch, audio_spy
) -> None:
- """``auto`` means "provider, you decide" — pinning it to a detected value
- would defeat per-utterance detection."""
+ """``auto`` is REQUESTED, never left unsaid.
+
+ This test used to assert the opposite — that auto sends no language at all —
+ and that is exactly how the bug worked: an absent argument means "no opinion"
+ to every provider, so the transcription fell back to whatever
+ ``[stt].language`` was pinned to. With the recognition language on English, a
+ user dictating German got English words back, and no setting in the dictation
+ view could fix it because the dictation view was not the setting in charge
+ (live bug 2026-07-28).
+ """
import jarvis.speech.pipeline as pipeline_mod
seen: list[dict] = []
@@ -510,7 +526,7 @@ async def test_auto_sends_no_language_at_all(
_STT(), DictationConfig(language="auto", partial_interval_s=0.0)
)
await pipe._dictation_session()
- assert seen == [{}]
+ assert seen == [{"language": "auto"}]
@pytest.mark.asyncio
@@ -562,7 +578,7 @@ async def test_a_provider_error_ends_the_session_as_failed(
await pipe._dictation_session()
completed = next(e for e in events if isinstance(e, DictationCompleted))
assert completed.outcome == "failed"
- assert "401" in (completed.error or "")
+ assert completed.error == "bad_key"
@pytest.mark.asyncio
@@ -590,7 +606,10 @@ async def test_a_crashed_session_is_recorded_instead_of_vanishing(
await pipe._dictation_session()
completed = next(e for e in events if isinstance(e, DictationCompleted))
assert completed.outcome == "failed"
- assert "no input device" in (completed.error or "")
+ # A microphone that never opened is not a classifiable STT failure, so the
+ # honest answer is the catch-all — never the raw OSError text.
+ assert completed.error == "unknown"
+ assert "no input device" not in (completed.error or "")
added = _FakeHistory.instances[-1].added
assert added and added[0]["outcome"] == "failed"
diff --git a/tests/unit/dictation/test_stt_failure_parity.py b/tests/unit/dictation/test_stt_failure_parity.py
new file mode 100644
index 0000000000..15c4a8d6aa
--- /dev/null
+++ b/tests/unit/dictation/test_stt_failure_parity.py
@@ -0,0 +1,206 @@
+"""Cross-layer parity guard for the transcription-failure vocabulary (AP-4).
+
+``jarvis.speech.stt_failure.STT_FAILURE_REASONS`` is the single source of truth
+for "why did this transcription fail". The value is written by the speech
+pipeline, carried on ``DictationCompleted.error``, stored in the history
+sidecar, serialised by the REST layer and finally turned into a sentence by the
+UI — the same five-layer shape that has drifted four times in this repo
+(BUG-008), and the reason the sibling ``test_outcome_parity`` exists.
+
+This one additionally pins the behaviour that made the vocabulary necessary: the
+history row must never carry a provider's raw error text again. What the user
+saw under their own words was a Python exception class, a vendor endpoint and a
+link to an HTTP specification — untranslatable, provider-identifying, and no
+answer to "what do I do now".
+
+Every parsed set is asserted NON-EMPTY before comparison, so a regex that stops
+matching fails loudly instead of going trivially green against an empty set.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+from jarvis.speech.stt_failure import (
+ CROSSABLE_REASONS,
+ STT_FAILURE_REASONS,
+ classify_stt_failure,
+ is_crossable_failure,
+ stt_failure_message,
+)
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+_FRONTEND = _REPO_ROOT / "jarvis" / "ui" / "web" / "frontend" / "src"
+_DICTATION_TS = _FRONTEND / "hooks" / "useDictation.ts"
+_HISTORY_GROUP_TSX = _FRONTEND / "views" / "voice" / "DictationHistoryGroup.tsx"
+_LOCALES = _FRONTEND / "i18n" / "locales"
+
+SUPPORTED_LOCALES = ("de", "en", "es")
+
+#: The live 429 the maintainer was shown, verbatim from the log. Kept as a
+#: literal so the classifier is pinned against a REAL provider error rather than
+#: a tidy invented one.
+LIVE_GROQ_429 = (
+ "HTTPStatusError: Client error '429 Too Many Requests' for url "
+ "'https://api.groq.com/openai/v1/audio/transcriptions' For more information "
+ "check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429"
+)
+
+
+def _ts_reasons() -> list[str]:
+ """Members of ``export const STT_FAILURE_REASONS = [...] as const``."""
+ assert _DICTATION_TS.exists(), f"frontend hook missing: {_DICTATION_TS}"
+ source = _DICTATION_TS.read_text(encoding="utf-8")
+ match = re.search(
+ r"export const STT_FAILURE_REASONS\s*=\s*\[(.*?)\]\s*as const",
+ source,
+ re.DOTALL,
+ )
+ assert match is not None, (
+ f"STT_FAILURE_REASONS array not found in {_DICTATION_TS.name}"
+ )
+ return re.findall(r'"([a-z_]+)"', match.group(1))
+
+
+def _locale(name: str) -> dict:
+ path = _LOCALES / f"{name}.json"
+ assert path.exists(), f"locale file missing: {path}"
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def test_the_python_vocabulary_is_a_usable_set() -> None:
+ assert STT_FAILURE_REASONS, "STT_FAILURE_REASONS is empty"
+ assert len(set(STT_FAILURE_REASONS)) == len(STT_FAILURE_REASONS)
+ assert "unknown" in STT_FAILURE_REASONS, "the catch-all must stay a member"
+
+
+def test_ts_reason_array_mirrors_the_python_vocabulary() -> None:
+ members = _ts_reasons()
+ assert members, f"parsed no reasons from {_DICTATION_TS.name}"
+ assert len(members) == len(set(members)), members
+ assert set(members) == set(STT_FAILURE_REASONS)
+
+
+def test_every_reason_has_a_sentence_in_every_locale() -> None:
+ for name in SUPPORTED_LOCALES:
+ table = _locale(name).get("dictation", {}).get("failure", {})
+ assert isinstance(table, dict) and table, (
+ f"{name}.json: dictation.failure missing"
+ )
+ for reason in STT_FAILURE_REASONS:
+ value = table.get(reason)
+ assert isinstance(value, str) and value.strip(), (
+ f"{name}.json: dictation.failure.{reason}"
+ )
+
+
+def test_no_locale_carries_a_reason_the_backend_never_emits() -> None:
+ """A stale key is drift in the other direction — dead copy nobody maintains."""
+ for name in SUPPORTED_LOCALES:
+ table = _locale(name).get("dictation", {}).get("failure", {})
+ assert set(table) == set(STT_FAILURE_REASONS), f"{name}.json: {sorted(table)}"
+
+
+def test_no_locale_sentence_names_a_provider() -> None:
+ """The message must read the same whichever key the downloader configured.
+
+ A sentence that says "Groq" is wrong for the ~99.9 % of installs that are
+ not the maintainer's (§3), and it is also just untrue as soon as the runtime
+ fallback chain moves the work to a different provider mid-dictation.
+ """
+ vendors = ("groq", "openai", "gemini", "openrouter", "whisper", "anthropic")
+ for name in SUPPORTED_LOCALES:
+ table = _locale(name).get("dictation", {}).get("failure", {})
+ for reason, sentence in table.items():
+ lowered = sentence.lower()
+ for vendor in vendors:
+ assert vendor not in lowered, f"{name}.json {reason}: {sentence}"
+ assert "http" not in lowered, f"{name}.json {reason} leaks a URL"
+
+
+def test_the_renderer_derives_its_known_set_from_the_shared_array() -> None:
+ """The UI must not keep a second, hand-written copy of the vocabulary."""
+ assert _HISTORY_GROUP_TSX.exists(), f"missing: {_HISTORY_GROUP_TSX}"
+ source = _HISTORY_GROUP_TSX.read_text(encoding="utf-8")
+ assert "new Set(STT_FAILURE_REASONS)" in source, (
+ f"{_HISTORY_GROUP_TSX.name} no longer derives its known-failure set "
+ "from the shared array"
+ )
+
+
+def test_the_renderer_never_prints_a_raw_error_string() -> None:
+ """The whole point: an unknown value falls back to a sentence, not the value.
+
+ This is the regression that was actually reported — a raw
+ ``{entry.error}`` in the JSX, which is how a Python exception class and a
+ vendor URL ended up rendered under a user's dictated text.
+ """
+ source = _HISTORY_GROUP_TSX.read_text(encoding="utf-8")
+ assert "{entry.error}" not in source, (
+ f"{_HISTORY_GROUP_TSX.name} renders the raw error string again"
+ )
+ assert "failureLabel(t, entry.error)" in source, _HISTORY_GROUP_TSX.name
+
+
+def test_the_live_rate_limit_classifies_as_rate_limited() -> None:
+ """The exact string from the reported incident, not a tidied-up stand-in."""
+ assert classify_stt_failure(LIVE_GROQ_429) == "rate_limited"
+
+
+def test_the_local_engines_busy_error_is_named_rather_than_generic() -> None:
+ """``TranscribeBusy`` is a real recurring shape here (AP-24 / BUG-036)."""
+ from jarvis.plugins.stt.fwhisper import TranscribeBusy
+
+ busy = TranscribeBusy("a transcription is already in flight on this model")
+ assert classify_stt_failure(busy) == "engine_busy"
+ # NOT crossable: the non-blocking lock means "try again in a moment", and
+ # spending a cloud request to skip a millisecond wait is the wrong trade.
+ assert is_crossable_failure("engine_busy") is False
+
+
+def test_normalization_is_idempotent_and_keeps_none_as_none() -> None:
+ """The backstop at the store: a code survives, raw text is converted."""
+ from jarvis.speech.stt_failure import normalize_stt_failure
+
+ for reason in STT_FAILURE_REASONS:
+ assert normalize_stt_failure(reason) == reason, reason
+ assert normalize_stt_failure(LIVE_GROQ_429) == "rate_limited"
+ # "no failure" must stay distinguishable from "failed, reason unknown".
+ assert normalize_stt_failure(None) is None
+ assert normalize_stt_failure("") is None
+ assert normalize_stt_failure(" ") is None
+
+
+def test_every_reason_has_an_english_sentence() -> None:
+ """The log / CLI half. An identifier there helps nobody either."""
+ for reason in STT_FAILURE_REASONS:
+ message = stt_failure_message(reason)
+ assert message and not message.startswith(reason), reason
+ assert message.endswith("."), reason
+ # Unknown input degrades to a sentence rather than echoing the raw value.
+ assert stt_failure_message("something_from_a_newer_install") == (
+ stt_failure_message("unknown")
+ )
+ assert stt_failure_message(None) == stt_failure_message("unknown")
+
+
+def test_crossable_reasons_are_a_real_subset_that_excludes_a_refusal() -> None:
+ """``rejected`` must never cross: another provider refuses the same bytes."""
+ assert CROSSABLE_REASONS < set(STT_FAILURE_REASONS)
+ assert "rejected" not in CROSSABLE_REASONS
+ assert "unknown" not in CROSSABLE_REASONS
+ for reason in STT_FAILURE_REASONS:
+ assert is_crossable_failure(reason) is (reason in CROSSABLE_REASONS), reason
+ assert is_crossable_failure(None) is False
+
+
+def test_classification_never_raises_on_the_shapes_it_actually_sees() -> None:
+ """It runs on the path already handling a failure; it may not add one."""
+ assert classify_stt_failure(None) == "unknown"
+ assert classify_stt_failure("") == "unknown"
+ assert classify_stt_failure(" ") == "unknown"
+ assert classify_stt_failure(RuntimeError("something nobody predicted")) == "unknown"
+ for reason in (classify_stt_failure(x) for x in (None, "", TimeoutError())):
+ assert reason in STT_FAILURE_REASONS
diff --git a/tests/unit/speech/test_dictation_pause_does_not_truncate.py b/tests/unit/speech/test_dictation_pause_does_not_truncate.py
index 093ba976dd..08feda6b49 100644
--- a/tests/unit/speech/test_dictation_pause_does_not_truncate.py
+++ b/tests/unit/speech/test_dictation_pause_does_not_truncate.py
@@ -333,6 +333,9 @@ async def test_a_recording_that_ends_early_is_reported(monkeypatch) -> None:
assert pipe.start_dictation(target="chat") is True
await asyncio.wait_for(pipe._dictation_task, timeout=10.0)
- assert "replay window" in str(captured.get("stt_error") or ""), (
+ # The reason CODE, not the exception text: this value ends up under the
+ # user's own words in the history, where a stack-trace fragment explains
+ # nothing. The exception itself goes to the log.
+ assert str(captured.get("stt_error") or "") == "recording_interrupted", (
"the recording died and the dictation reported nothing about it"
)
diff --git a/tests/unit/speech/test_pipeline_lightweight_wake.py b/tests/unit/speech/test_pipeline_lightweight_wake.py
index d574bdfa12..be336e0726 100644
--- a/tests/unit/speech/test_pipeline_lightweight_wake.py
+++ b/tests/unit/speech/test_pipeline_lightweight_wake.py
@@ -55,10 +55,13 @@ def test_lightweight_mode_instantiates_no_faster_whisper() -> None:
)
assert pipe._stt is None
assert pipe._whisper_wake is None
- # The utterance STT is wrapped by the user-dictionary corrector; the
- # resolved provider underneath must still be the configured Groq cloud STT.
+ # The utterance STT is wrapped by the user-dictionary corrector and, under
+ # it, by the runtime fallback chain; the resolved provider must still be the
+ # configured Groq cloud STT, and the label must still NAME it rather than
+ # naming a wrapper — the log line that reports which provider transcribed is
+ # the first thing anyone reads when a provider starts failing.
assert type(pipe._utterance_stt).__name__ == "DictionaryCorrectingSTT"
- assert pipe._utterance_stt.provider_label == "GroqWhisperAPI"
+ assert pipe._utterance_stt.provider_label == "groq-api"
def test_heavy_mode_keeps_faster_whisper_by_default() -> None: