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): reject hallucinations, trust the text over the tag, measure the audio

Ruben Lütkeb9bcb6b6d9e8
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 3270a88018..f2a111d583 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -157,6 +157,28 @@ class DictationCompleted(Event):
#: makes ``outcome="failed"`` distinguishable from ``outcome="empty"``:
#: before it existed, a provider 401 and plain silence looked identical.
error: str | None = None
+ #: What the generative polish pass did to ``text``. One of
+ #: ``jarvis.dictation.polish.POLISH_STATUSES`` — that tuple is the single
+ #: vocabulary for this value, imported rather than restated here for the
+ #: same reason ``outcome`` is (AP-4 / BUG-008). ``""`` on a completion the
+ #: pass never ran for at all (a hangup, a crash before delivery), which is
+ #: deliberately distinct from ``"off"`` (the user switched it off) and from
+ #: ``"unavailable"`` (nobody on this host holds a key for it).
+ #:
+ #: This is carried on the EVENT and not only in the history because the
+ #: user-visible claim "these are the words you said" changes when the pass
+ #: applies: a surface that shows the polished text without being able to say
+ #: it was polished cannot offer the raw text back.
+ polish_status: str = ""
+ #: The credential family that answered (``groq``/``gemini``/...), empty when
+ #: none was asked. A family id, never a model id — the model is a detail of
+ #: the family and changes without the user doing anything.
+ polish_provider: str = ""
+ #: Wall-clock cost of the pass, including a fallback hop and a rejected
+ #: answer. It is the number that decides whether the feature is worth its
+ #: place in the delivery path, so it is reported on every status, not only
+ #: on ``applied``.
+ polish_latency_ms: int = 0
#: Every reason a dictation start can be refused. Declared ONCE here, next to
diff --git a/jarvis/dictation/insert.py b/jarvis/dictation/insert.py
index 89eaa4a6a7..dd22193aa0 100644
--- a/jarvis/dictation/insert.py
+++ b/jarvis/dictation/insert.py
@@ -389,6 +389,27 @@ def describe_target() -> TargetReport:
return TargetReport(can_insert=True, reason="", detail="")
+def _word_count(text: str) -> int:
+ """How many words *text* holds, answered by the ONE shared counter.
+
+ ``jarvis.dictation.cleanup.count_words`` is what the history rows, the
+ statistics sidecar and the cleanup's destruction ceiling all count with; a
+ second word regex living here would stop agreeing with them the first time
+ either is touched. Imported lazily and degrading to "there is something" on
+ any failure, so a problem in the counter can never turn a working paste into
+ a refusal — this guard exists to stop a stray full stop, not to become a new
+ way of losing text.
+ """
+ try:
+ from jarvis.dictation.cleanup import count_words
+
+ return count_words(text)
+ except Exception: # noqa: BLE001 — a missing counter is not a reason to refuse
+ log.debug("word count unavailable; treating the text as insertable",
+ exc_info=True)
+ return 1
+
+
def insert_text(
text: str,
*,
@@ -408,7 +429,13 @@ def insert_text(
Either way the text is written to the clipboard FIRST, so every failure
path below degrades to "it is one Ctrl+V away" rather than to silence.
"""
- if not text or not text.strip():
+ # "Empty" has to mean "holds no WORDS", not "holds no characters". A live
+ # dictation once delivered a bare "." into a document and then restored the
+ # clipboard over it, which cost the user both the stray character and
+ # whatever they had copied before. The pipeline gates on the same rule
+ # before it ever gets here; this is the floor under every other caller,
+ # including the ones that do not exist yet.
+ if not text or not text.strip() or _word_count(text) == 0:
return InsertResult(
status="unavailable",
detail="Nothing was dictated.",
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 2868ce1679..ae32b9dbd2 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -581,13 +581,29 @@ def _playback_progress_stalled(last_write_ns: int, stall_s: float) -> bool:
def _stt_error_status(exc: BaseException) -> int | None:
- """HTTP status of an STT error, duck-typed so the plugin stays un-imported.
-
- ``httpx.HTTPStatusError`` (raised by the cloud STT plugins) carries the
- response on ``.response.status_code``; any provider that mirrors that shape
- is understood. Returns ``None`` for non-HTTP errors.
+ """HTTP status of an STT error, or ``None`` when it was not an HTTP error.
+
+ Delegates to ``jarvis.plugins.stt.errors.status_from_exception``, which is
+ the ONE place the shapes are enumerated: our own ``STTHTTPError.status``
+ first, then the google-genai SDK's ``.code``, then the
+ ``httpx.HTTPStatusError`` family's ``.response.status_code``. Keeping a
+ second table here is precisely the drift AP-4 is about — and the reason the
+ retry ladder used to work for exactly one provider was that this function
+ knew only the last of those three shapes.
+
+ The import is lazy and the legacy duck-type survives as the fallback, so
+ this stays correct on a host where the plugin package cannot be imported at
+ all (a stripped install, an import error mid-reload). Errors are rare, so
+ the cached import costs nothing worth measuring.
"""
- return getattr(getattr(exc, "response", None), "status_code", None)
+ try:
+ from jarvis.plugins.stt.errors import status_from_exception
+ except Exception: # noqa: BLE001 — an unimportable plugin package is not fatal
+ status = getattr(exc, "status", None)
+ if isinstance(status, int) and not isinstance(status, bool):
+ return status
+ return getattr(getattr(exc, "response", None), "status_code", None)
+ return status_from_exception(exc)
def _is_transient_stt_error(exc: BaseException) -> bool:
@@ -598,9 +614,20 @@ def _is_transient_stt_error(exc: BaseException) -> bool:
def _stt_retry_delay(exc: BaseException | None, attempt: int) -> float:
"""Backoff before the next final-STT attempt.
- Honours a server ``Retry-After`` header when present (seconds form),
- otherwise capped exponential backoff. Always within ``[0, cap]``.
+ Honours the delay the SERVER asked for when there is one, otherwise capped
+ exponential backoff. Always within ``[0, cap]``.
+
+ ``STTHTTPError`` already parsed the header into ``retry_after`` seconds, and
+ it understands BOTH forms RFC 9110 allows — the delta-seconds one every
+ provider sends directly and the HTTP-date one a CDN or gateway in front of
+ one sends. Reading that attribute first is therefore not a shortcut: parsing
+ the raw header here only ever understood the delta form, so a date-form
+ header silently fell through to blind backoff. The header read stays as the
+ fallback for the providers that raise a plain ``httpx.HTTPStatusError``.
"""
+ requested = getattr(exc, "retry_after", None)
+ if isinstance(requested, (int, float)) and not isinstance(requested, bool):
+ return min(_STT_RETRY_CAP_S, max(0.0, float(requested)))
resp = getattr(exc, "response", None)
headers = getattr(resp, "headers", None)
if headers is not None and hasattr(headers, "get"):
@@ -696,6 +723,128 @@ _DICTATION_FINAL_RETRY_DELAY_S = 0.6
# waiting for their text, so it may not inherit the probe's patient backoff.
_DICTATION_FINAL_RETRY_MAX_S = 2.0
+# Per-call ceiling on ONE dictation transcription, derived from the audio being
+# sent. Nothing bounded these calls before, which is only survivable while every
+# provider misbehaves in the same polite way: google-genai forces ``timeout=None``
+# onto its own HTTP client AND runs the request in an uncancellable thread, so a
+# Gemini user whose call never came back had the dictation lane wedged after the
+# microphone had already closed — no text, no error, no end.
+#
+# The bound SCALES with the piece rather than being a constant, because the same
+# helper transcribes an 8 s segment and, in the unsegmented legacy mode, a
+# recording that may be minutes long: one fixed number is either uselessly large
+# for the first or a guaranteed truncation for the second. The multiplier allows
+# comfortably worse than real time (a CPU-only local Whisper is the slow case;
+# every cloud provider returns in a fraction of it), so the ceiling can only ever
+# be reached by something that is genuinely stuck.
+_DICTATION_TRANSCRIBE_TIMEOUT_PER_AUDIO_S = 2.0
+
+
+def _dictation_retry_worthwhile(exc: BaseException | None) -> bool:
+ """Whether re-sending the SAME audio to this provider could work.
+
+ The dictation lane used to retry every failure three times, 0.6 s apart —
+ a dead key exactly as eagerly as a rate limit. That is wrong in both
+ directions: it hammers a provider that has already said "no, and not later"
+ (401 bad key, 402 out of credit, 400 unusable audio) while making the user
+ wait ~1.8 s to be told something the first answer already said, and it
+ re-fires into a rate-limit window far too early to be inside it.
+
+ A transient HTTP status (429 / 5xx) is worth another attempt. So is a
+ failure with NO status at all — a dropped socket, a TLS reset, a
+ provider-side read timeout — because those are exactly the blips a second
+ attempt survives. Everything else is a definitive refusal and stops the
+ ladder.
+
+ OUR OWN ceiling is the deliberate exception. Reaching it means this piece
+ already got more than twice its own length in wall-clock time and the
+ provider produced nothing, which is a wedge, not a blip — and asking again
+ would double a wait the user is already sitting through with the microphone
+ closed. The audio is kept as a sidecar either way, so "Restore" is a far
+ better answer than three ceilings in a row. Note this catches only the
+ ``TimeoutError`` raised by our ``wait_for``: a provider's own timeout
+ exception is a transport error with no status and is still retried.
+ """
+ if exc is None:
+ return False
+ if isinstance(exc, TimeoutError):
+ return False
+ status = _stt_error_status(exc)
+ if status is None:
+ return True
+ return status in _STT_TRANSIENT_STATUS
+
+
+def resolve_dictation_language(*, pinned: str, reported: str, text: str) -> str:
+ """Which language a finished dictation is treated as. Never raises.
+
+ Module-level and public because TWO paths finish a dictation — the live
+ delivery in ``_finish_dictation`` and the Restore route's re-transcription —
+ and a second copy of this decision is how the same recording would end up
+ cleaned under two different rule sets depending on which button produced it.
+
+ Three signals, 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.
+ 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 hesitation sound the user made shipped straight into the
+ text while the setting said the cleanup was on.
+
+ Everything resolves through the canonical resolver's helpers — no layer
+ invents its own detection (CLAUDE.md §1).
+ """
+ pin = str(pinned or "").strip().lower()
+ if pin not in ("", "auto"):
+ return pin
+ tag = str(reported or "")
+ if not text:
+ return tag
+ try:
+ from jarvis.core.turn_language import (
+ detect_text_language,
+ normalize_language_tag,
+ )
+
+ lowered = tag.strip().lower()
+ tag_code = normalize_language_tag(lowered)
+ detected = detect_text_language(text)
+ if detected != "unknown" and (
+ # Nothing to contradict: no tag at all, or one that says "I could
+ # not tell".
+ lowered 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,
+ tag,
+ )
+ return detected
+ except Exception: # noqa: BLE001 — a detection hiccup is not fatal
+ log.debug("dictation language detection failed", exc_info=True)
+ return tag
+
# After this many consecutive pieces have exhausted every attempt, the provider
# is not flaky, it is down — and continuing to retry each remaining piece would
# make a 300 s dictation spend minutes proving it. Stop and say so: the audio is
@@ -1501,6 +1650,12 @@ class SpeechPipeline:
# button), "insert" additionally pastes it into the focused field of
# whatever app is in front. Set per start_dictation call, never global.
self._dictation_target = "chat"
+ # The dictation lane's OWN transcription provider — built on the first
+ # press, never at boot (AP-26), and deliberately not the voice one: see
+ # ``_dictation_stt`` for why the voice bias prompt must not reach a
+ # dictation. ``None`` means "not built yet", which is also how a live
+ # provider/language switch invalidates it.
+ self._dictation_stt_instance: Any = None
# True while a hold-mode dictation key is physically down. Mirrors
# ``_ptt_mode`` for the dictation lane so a repeated press edge (the
# Windows backend polls and re-fires on_press while held) is idempotent.
@@ -2251,6 +2406,11 @@ class SpeechPipeline:
# language (AP-27: the wake never rides on the utterance setting).
if previous is not None and self._probe_stt is previous:
self._probe_stt = rebuilt
+ # The dictation lane holds its OWN instance (no voice bias prompt), so a
+ # switch that only rebuilt the voice one would leave dictation
+ # transcribing in the previous recognition language for the rest of the
+ # process — a setting that appears to apply and silently does not.
+ self._reset_dictation_stt()
log.info(
"STT-Live-Switch: recognition language is now %r (%s)",
language,
@@ -8392,6 +8552,163 @@ class SpeechPipeline:
self._dictation_stop_event.set()
return True
+ def _dictation_stt(self) -> Any:
+ """The provider this lane transcribes with — NOT the voice one (F14).
+
+ Two things are wrong with reusing ``self._utterance_stt`` here, and both
+ of them are silent.
+
+ **The bias prompt.** ``[stt].bias_prompt`` is decoder priming for the
+ VOICE path: a paragraph of vocabulary that steers Whisper towards the
+ words a conversation with this assistant tends to contain. The repo
+ already documents it as a silence-hallucination amplifier and
+ deliberately withholds it from the local engine for exactly that reason
+ — and then handed it to the dictation lane anyway, which is the one lane
+ whose input is long, whose pauses are frequent, and whose output goes
+ straight into somebody's document. It also biases decoding towards the
+ prompt's own language, which is the second half of the wrong-language
+ problem the delivery gates deal with. Dictation therefore builds its own
+ instance with the voice prompt REMOVED, honouring
+ ``[dictation].bias_prompt`` instead — absent by default, which is the
+ point: a dictation is not a conversation and has no vocabulary to guess.
+ The user's STT dictionary is NOT dropped: ``build_stt_from_config``
+ merges those words separately, and they are the one bias a person asked
+ for by name.
+
+ **The fallback chain (AP-22).** The lane binds one provider for the
+ whole session, so a depleted key ended the dictation even with three
+ other keyed families sitting unused. ``resolve_keyed_stt_fallback``
+ answers with one provider per CREDENTIAL family — never two ids reading
+ the same keyring slot, because a 429 on a key is not survived by a
+ sibling that draws on the same key — and ``FallbackSTT`` builds each of
+ them lazily, on the first call that actually needs it (AP-26).
+
+ Degrades to the voice instance on any failure: a dictation with the
+ wrong prompt is enormously better than a dictation with no provider.
+ Built once and cached, because the alternative is re-resolving keys and
+ re-constructing a client on every press.
+ """
+ cached = getattr(self, "_dictation_stt_instance", None)
+ if cached is not None:
+ return cached
+
+ fallback = getattr(self, "_utterance_stt", None)
+ config = getattr(self, "_config", None)
+ stt_cfg = getattr(config, "stt", None) if config is not None else None
+ if stt_cfg is None:
+ return fallback
+
+ try:
+ from jarvis.plugins.stt import build_stt_from_config
+
+ dictation_cfg = getattr(self, "_dictation_cfg", None)
+ # ``[dictation].bias_prompt`` is read through getattr so this is
+ # correct both before and after the key exists as a field: absent
+ # reads as empty, which is the shipped behaviour we want anyway.
+ own_prompt = str(getattr(dictation_cfg, "bias_prompt", "") or "").strip()
+ patched = stt_cfg.model_copy(update={"bias_prompt": own_prompt})
+ instance = build_stt_from_config(patched)
+ except Exception as exc: # noqa: BLE001 — never lose dictation over this
+ log.warning(
+ "Dictation-specific STT could not be built (%s); reusing the "
+ "voice provider, bias prompt included.",
+ exc,
+ )
+ return fallback
+
+ # The chain and the dictionary are each wrapped in their OWN guard:
+ # neither is worth losing the prompt-free instance we already have, and
+ # collapsing all three into one try meant an import error in either
+ # wrapper silently handed the voice provider — bias prompt included —
+ # back to the dictation lane.
+ try:
+ from jarvis.plugins.stt import (
+ build_named_stt_provider,
+ resolve_keyed_stt_fallback,
+ )
+
+ configured = str(getattr(stt_cfg, "provider", "") or "").strip()
+ alternates = list(resolve_keyed_stt_fallback(configured))
+ if alternates:
+ from jarvis.speech.stt_fallback import FallbackSTT
+
+ def _build(name: str) -> Any:
+ return build_named_stt_provider(name, patched)
+
+ instance = FallbackSTT(
+ instance, alternates, _build, primary_name=configured
+ )
+ log.info(
+ "Dictation STT chain armed: %s -> %s (no voice bias prompt).",
+ configured or type(instance).__name__,
+ ", ".join(alternates),
+ )
+ except Exception as exc: # noqa: BLE001 — one provider is still a provider
+ log.warning("Dictation STT fallback chain unavailable: %s", exc)
+
+ # The user's spoken-vocabulary corrections apply to dictation the same
+ # way they apply to a voice turn — they are post-STT string work, so
+ # they ride on TOP of the fallback chain rather than under it and
+ # survive a cross to another family.
+ try:
+ from jarvis.speech.stt_dictionary import wrap_stt_with_dictionary
+
+ instance = wrap_stt_with_dictionary(instance)
+ except Exception as exc: # noqa: BLE001 — corrections are not load-bearing
+ log.warning("STT dictionary wrapper unavailable for dictation: %s", exc)
+
+ self._dictation_stt_instance = instance
+ return instance
+
+ def _reset_dictation_stt(self) -> None:
+ """Drop the cached dictation provider so the next press rebuilds it.
+
+ Called from every place that swaps the voice provider or the recognition
+ language. Without it a live settings change would apply to conversations
+ and silently not to dictation — the exact class of divergence that makes
+ "it works here, not there" unanswerable.
+ """
+ self._dictation_stt_instance = None
+
+ def _dictation_protected_terms(self) -> tuple[str, ...]:
+ """Spellings the polish pass may not "correct" into something familiar.
+
+ The reference dictation tool's own documentation warns about this
+ failure direction explicitly: a rewrite model turns an unfamiliar
+ technical term into the common word it resembles, and the user cannot
+ tell it happened because the sentence still reads fine. So the words a
+ user has already told us they care about travel with the request and are
+ checked afterwards by the drift guard.
+
+ Three sources, all of them things the user chose: the STT dictionary
+ (words they added by hand for exactly this reason), the configured wake
+ word (a name, and names are what get "corrected"), and the assistant
+ name derived from it. Nothing here is a secret and nothing is free text
+ from a voice turn — AP-2 territory stays out of the prompt.
+
+ Never raises and never blocks: an unreadable dictionary costs the guard
+ its input, not the user their dictation.
+ """
+ terms: list[str] = []
+ try:
+ from jarvis.speech.stt_dictionary import dictionary_bias_words
+
+ terms.extend(dictionary_bias_words())
+ except Exception as exc: # noqa: BLE001 — an unreadable store is not fatal
+ log.debug("dictation protected terms: dictionary unavailable (%s)", exc)
+ phrase = getattr(self, "_wake_phrase_label", "") or ""
+ for word in str(phrase).split():
+ if len(word) >= 2:
+ terms.append(word)
+ seen: set[str] = set()
+ unique: list[str] = []
+ for term in terms:
+ key = term.strip().casefold()
+ if key and key not in seen:
+ seen.add(key)
+ unique.append(term.strip())
+ return tuple(unique)
+
async def _dictation_session(self) -> None:
"""Capture mic audio, transcribe it in segments, deliver the result.
@@ -8420,7 +8737,10 @@ class SpeechPipeline:
cancelling an ``asyncio.to_thread`` would only cancel the wrapper, not
the native call, and the next transcribe would then raise TranscribeBusy.
"""
- stt = self._utterance_stt
+ # NOT ``self._utterance_stt``: the dictation lane transcribes through its
+ # own provider, without the voice bias prompt and with its own
+ # cross-family fallback chain (see ``_dictation_stt``).
+ stt = self._dictation_stt()
if stt is None:
# ``start_dictation`` already refused this case; only a provider
# swapped out between the two calls can land here. Close the turn
@@ -8504,8 +8824,10 @@ class SpeechPipeline:
str(getattr(cfg, "language", "auto") or "auto").strip().lower() or "auto"
)
- async def _transcribe(pcm: bytes) -> tuple[str, str, bool]:
- """One transcription. ``(text, language, ok)``; never raises.
+ async def _transcribe(
+ pcm: bytes,
+ ) -> tuple[str, str, bool, BaseException | None]:
+ """One transcription. ``(text, language, ok, error)``; never raises.
Records the failure in ``stt_error`` instead of swallowing it. A
later successful call clears it again — a single flaky segment in an
@@ -8519,31 +8841,62 @@ class SpeechPipeline:
deleted eight seconds of speech from the middle of the result with
nothing anywhere saying so. That is the reported "I said more than
this" bug in its entirety.
+
+ ``error`` is the EXCEPTION OBJECT, and it is the reason this returns
+ four values instead of three. The reason code stored in
+ ``stt_error`` is a user-facing word; the retry ladder needs the HTTP
+ status behind it to tell a rate limit (wait and try again) from a
+ dead key (stop). Collapsing every failure into ``("", "", False)``
+ destroyed exactly that, which is why the ladder used to retry a 401
+ three times and re-fire into a 429 window 0.6 s after being told to
+ wait.
+
+ Every call is bounded. ``wait_for`` cancels our await, not a native
+ thread — so this is a ceiling on how long the LANE waits, never a
+ guarantee that the provider stopped working. That is still the whole
+ difference between a dictation that ends with an honest error and
+ one that never ends at all.
"""
nonlocal stt_error, stt_error_detail
+ ceiling = max(
+ float(getattr(self, "_stt_final_timeout_s", 8.0) or 8.0),
+ (len(pcm) / bytes_per_second)
+ * _DICTATION_TRANSCRIBE_TIMEOUT_PER_AUDIO_S,
+ )
inference_active.set()
try:
try:
- transcript = await stt.transcribe_pcm(
- pcm, language=dictation_language
+ transcript = await asyncio.wait_for(
+ stt.transcribe_pcm(pcm, language=dictation_language),
+ timeout=ceiling,
)
except TypeError:
# Provider predates the keyword (contract allows a bare
# ``transcribe_pcm(pcm)``). Fall back rather than call the
# choice a failure — precedent: rolling_whisper_wake.
- transcript = await stt.transcribe_pcm(pcm)
+ transcript = await asyncio.wait_for(
+ stt.transcribe_pcm(pcm), timeout=ceiling
+ )
+ except TimeoutError as exc:
+ stt_error_detail = (
+ f"the provider did not answer within {ceiling:.0f}s "
+ f"for {len(pcm) / bytes_per_second:.1f}s of audio"
+ )
+ stt_error = classify_stt_failure(exc)
+ log.warning("dictation transcribe timed out: %s", stt_error_detail)
+ return "", "", False, exc
except Exception as exc: # noqa: BLE001 — one failed call is not fatal
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
+ return "", "", False, exc
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
+ return text, lang, True, None
async def _close_finished_segments() -> bool:
"""Close every segment the buffer already holds. ``False`` on a
@@ -8590,7 +8943,7 @@ class SpeechPipeline:
closed_bytes += cut
skipped_silence_bytes += cut
continue
- text, lang, ok = await _transcribe(piece)
+ text, lang, ok, _exc = await _transcribe(piece)
if stop_event.is_set():
return True
if not ok:
@@ -8671,7 +9024,7 @@ class SpeechPipeline:
# screen; skipping a segment costs the user their words.
and preview_budget().try_spend()
):
- tail_text, lang, ok = await _transcribe(tail)
+ tail_text, lang, ok, _exc = await _transcribe(tail)
if stop_event.is_set():
return
if not ok:
@@ -8749,23 +9102,43 @@ class SpeechPipeline:
if is_silent_segment(piece, session_peak=session_peak):
continue
for attempt in range(_DICTATION_FINAL_ATTEMPTS):
- text, lang, ok = await _transcribe(piece)
+ text, lang, ok, exc = await _transcribe(piece)
language = lang or language
if ok:
if text:
parts.append(text)
dead_streak = 0
break
+ # A failure the provider will give us again is not worth
+ # asking for again. A 401 answered three times over 1.8 s is
+ # 1.8 s of the user staring at a spinner to learn what the
+ # first answer already said, and every one of those calls
+ # hits a provider that has already refused.
+ if not _dictation_retry_worthwhile(exc):
+ log.info(
+ "final dictation transcription refused (%s) — not "
+ "retrying: this is not a failure a second attempt "
+ "survives.",
+ stt_error_detail or stt_error or "unknown error",
+ )
+ dead_streak += 1
+ break
if attempt + 1 >= _DICTATION_FINAL_ATTEMPTS:
dead_streak += 1
else:
- # Widening, not fixed: three attempts inside one second
- # all land in the same rate-limit window, which is the
- # case this retry exists for. Still bounded — the user
+ # The server's own ``Retry-After`` wins when it sent
+ # one — re-firing 0.6 s into a window it just told us
+ # lasts 30 s only extends the window. Without a header,
+ # widening backoff: three attempts inside one second all
+ # land in the same rate-limit window, which is the case
+ # this retry exists for. Bounded either way — the user
# has stopped speaking and is waiting for their text.
delay = min(
_DICTATION_FINAL_RETRY_MAX_S,
- _DICTATION_FINAL_RETRY_DELAY_S * (2**attempt),
+ max(
+ _stt_retry_delay(exc, attempt),
+ _DICTATION_FINAL_RETRY_DELAY_S * (2**attempt),
+ ),
)
log.info(
"final dictation transcription failed (%s) — "
@@ -9042,64 +9415,16 @@ class SpeechPipeline:
# and a provider that answers "unknown" leaves every dictation with
# 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
- # 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,
- )
-
- 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)
+ # Which language the cleanup rules — and the polish pass — run in. The
+ # decision itself lives in ``resolve_dictation_language`` at module
+ # level, because the Restore route re-transcribes the same audio and has
+ # to reach the same answer. A hangup transcribed nothing, so there is no
+ # text to resolve from and the reported tag stands.
+ effective_language = resolve_dictation_language(
+ pinned=pinned,
+ reported=language,
+ text="" if hung_up else raw_text,
+ )
if raw_text and not hung_up:
try:
@@ -9121,6 +9446,23 @@ class SpeechPipeline:
exc_info=True)
cleaned = raw_text
+ # Punctuation repair runs UNCONDITIONALLY, next to the cleanup and
+ # deliberately outside its result. The two are not variants of one
+ # step: filler removal is a user preference that only applies to
+ # three languages, while the damage this repairs — "gesprochen....
+ # ist", a sentence restarting in lower case — is manufactured by our
+ # own segmented transcription and therefore exists in every
+ # dictation, in every language, whether or not a filler was found.
+ # Gating it on the cleanup's outcome (which is where it used to sit)
+ # is why the live history is full of stretches nothing ever touched.
+ try:
+ from jarvis.dictation.cleanup import tidy_transcript
+
+ cleaned = tidy_transcript(cleaned)
+ except Exception: # noqa: BLE001 — a tidy bug never costs the words
+ log.debug("dictation tidy failed; using the untidied transcript",
+ exc_info=True)
+
# Two kinds of text must never reach a document, and both used to.
#
# (a) Whisper's silence boilerplate. Every Whisper-family model answers a
@@ -9169,6 +9511,61 @@ class SpeechPipeline:
log.debug("dictation delivery gate failed", exc_info=True)
rejected_detail = ""
+ # The generative polish pass — the second read-over that turns a
+ # transcript into written prose (punctuation, sentence structure, the
+ # capitalisation our own ~8 s segment boundaries destroy). No regex can
+ # do this, which is why the deterministic cleanup above closes only half
+ # the gap.
+ #
+ # It sits HERE, after the delivery gates and before the publish, for two
+ # reasons. After the gates, so we never spend a model call polishing
+ # boilerplate we are about to throw away. Before the publish, so the
+ # chat composer, the Jarvis Bar and the insertion all see the SAME
+ # string — a polished paste next to an unpolished composer is the kind
+ # of divergence nobody can explain afterwards. ``raw_text`` is untouched
+ # and still reaches the history, so the user can always recover the
+ # words they actually said.
+ #
+ # Fail-open twice over: ``polish_transcript`` itself never raises and
+ # returns the raw text on every non-``applied`` status, and this block
+ # additionally catches anything the import or the call surfaces. The
+ # import is INSIDE the function (AP-26) exactly like ``clean_transcript``
+ # above — nothing about the polish pass may reach the boot path.
+ polish_status = ""
+ polish_provider = ""
+ polish_latency_ms = 0
+ if cleaned.strip() and not hung_up:
+ try:
+ from jarvis.dictation.polish import polish_enabled, polish_transcript
+
+ if polish_enabled(cfg):
+ result = await polish_transcript(
+ cleaned,
+ language=effective_language,
+ cfg=cfg,
+ protected_terms=self._dictation_protected_terms(),
+ style=str(getattr(cfg, "polish_style", "neutral") or "neutral"),
+ )
+ cleaned = result.text
+ polish_status = result.status
+ polish_provider = result.provider
+ polish_latency_ms = result.latency_ms
+ log.info(
+ "dictation polish: %s (%s, %d ms%s).",
+ polish_status,
+ polish_provider or "no provider",
+ polish_latency_ms,
+ f", {result.reason}" if result.reason else "",
+ )
+ else:
+ polish_status = "off"
+ except Exception: # noqa: BLE001 — never lose the text to the polish pass
+ log.warning(
+ "dictation polish failed; using the unpolished transcript",
+ exc_info=True,
+ )
+ polish_status = "provider_error"
+
# Publish the final transcript first: the chat composer and the bar
# both listen for it, and they should update even if insertion fails.
try:
@@ -9240,6 +9637,9 @@ class SpeechPipeline:
duration_s=duration_s,
removed_words=removed_words,
error=stt_error,
+ polish_status=polish_status,
+ polish_provider=polish_provider,
+ polish_latency_ms=polish_latency_ms,
)
)
except Exception as exc: # noqa: BLE001
@@ -9256,6 +9656,9 @@ class SpeechPipeline:
cleanup_reason=cleanup_reason,
stt_error=stt_error,
audio=audio,
+ polish_status=polish_status,
+ polish_provider=polish_provider,
+ polish_latency_ms=polish_latency_ms,
)
return cleaned
@@ -9272,6 +9675,9 @@ class SpeechPipeline:
cleanup_reason: str,
stt_error: str | None,
audio: bytes | None,
+ polish_status: str = "",
+ polish_provider: str = "",
+ polish_latency_ms: int = 0,
) -> None:
"""Write the history row and, when warranted, the audio sidecar.
@@ -9280,6 +9686,10 @@ class SpeechPipeline:
needs, so nothing in here is allowed to change what the user sees. All
of it is best-effort — a failed history write costs the history entry
and nothing else.
+
+ The ``polish_*`` values are offered to the store and dropped when it
+ does not want them yet — see the ``TypeError`` branch below. A history
+ row is worth more than the three fields describing how it was formatted.
"""
from jarvis.dictation.outcomes import is_recoverable
@@ -9298,8 +9708,7 @@ class SpeechPipeline:
from jarvis.dictation.history import DictationHistory
history = DictationHistory()
- entry = await asyncio.to_thread(
- history.add,
+ fields: dict[str, Any] = dict(
raw_text=raw_text,
text=cleaned,
language=language,
@@ -9312,6 +9721,25 @@ class SpeechPipeline:
max_entries=int(getattr(cfg, "history_max_entries", 200)),
retention_days=int(getattr(cfg, "history_retention_days", 30)),
)
+ extra = {
+ "polish_status": polish_status,
+ "polish_provider": polish_provider,
+ "polish_latency_ms": polish_latency_ms,
+ }
+ try:
+ entry = await asyncio.to_thread(history.add, **fields, **extra)
+ except TypeError:
+ # The store predates these fields. Writing the row WITHOUT them
+ # is the right degradation: the user's words are the payload,
+ # and "how it was formatted" is metadata about the payload. The
+ # alternative — letting the TypeError fall into the handler
+ # below — silently drops the whole dictation from the history,
+ # which is a far worse answer to a version skew.
+ log.debug(
+ "dictation history does not carry the polish fields yet; "
+ "storing the row without them."
+ )
+ entry = await asyncio.to_thread(history.add, **fields)
except Exception: # noqa: BLE001 — history is never worth a failure
log.debug("dictation history write failed", exc_info=True)
return
diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.py
index 500e7da702..0ed62f9032 100644
--- a/jarvis/ui/web/dictation_routes.py
+++ b/jarvis/ui/web/dictation_routes.py
@@ -14,6 +14,7 @@ Endpoints (mounted by the WebServer in ``_build_app()``):
POST /api/dictation/history/{id}/restore → un-discard, re-transcribe.
GET /api/dictation/settings → the [dictation] block.
PUT /api/dictation/settings → change one or more keys.
+ POST /api/dictation/polish/test → dry-run the polish pass on a sample.
Delete has two shapes on purpose. ``DELETE /history/{id}`` keeps hard-delete
semantics because that is the contract anyone scripting ``jarvis api dictation``
@@ -117,17 +118,168 @@ def _as_int(value: Any, fallback: int) -> int:
return fallback
-def _pinned_language(request: Request) -> str | None:
- """``[dictation].language`` as an STT argument — ``None`` means "detect"."""
- pinned = str(getattr(_dictation_cfg(request), "language", "auto") or "").strip()
- lowered = pinned.lower()
- return lowered if lowered and lowered != "auto" else None
+def _chosen_language(request: Request) -> str:
+ """``[dictation].language`` as an STT argument.
+
+ ``"auto"`` is returned as-is rather than as ``None``: the provider contract
+ treats an ABSENT argument as "no opinion", which falls back to whatever
+ ``[stt].language`` is pinned to, while an explicit ``"auto"`` forces
+ detection for that call. Dropping it here is what made a restore re-transcribe
+ in the recognition language instead of the spoken one (live bug 2026-07-28).
+ """
+ chosen = str(getattr(_dictation_cfg(request), "language", "auto") or "").strip()
+ return chosen.lower() or "auto"
+
+
+def _normalized_language(tag: str) -> str:
+ """One code per history row, resolved through the canonical helper.
+
+ ``de`` / ``en`` / ``es`` collapse to their code; ``auto`` / ``unknown`` /
+ ``und`` and the empty string all mean "not established" and store as ``""``.
+ Anything else — a language the shared resolver does not model — is KEPT,
+ lower-cased and reduced to its primary subtag. Coercing it would be worse
+ than the drift being fixed: relabelling a Japanese dictation as English is a
+ lie, and dropping the tag erases the only record of what was heard.
+ """
+ raw = str(tag or "").strip()
+ if not raw:
+ return ""
+ lowered = raw.lower()
+ if lowered in ("auto", "unknown", "und"):
+ return ""
+ try:
+ from jarvis.core.turn_language import normalize_language_tag
+
+ code = normalize_language_tag(lowered)
+ except Exception: # noqa: BLE001 — an unavailable resolver keeps the tag
+ return lowered.split("-")[0]
+ if code and code != "unknown":
+ return code
+ return lowered.split("-")[0]
+
+
+def _restore_stt(pipeline: Any) -> Any:
+ """The provider a Restore transcribes with — the DICTATION one, not voice.
+
+ The dictation lane holds its own instance: no ``[stt].bias_prompt`` (which
+ the config documents as a silence-hallucination amplifier) and its own
+ cross-family fallback chain. A restore that reached past it to the voice
+ provider would transcribe the same audio under different decoder priming
+ than the dictation that produced it, which is the one thing a "give me that
+ back" button must not do.
+
+ Falls back to the voice provider on an older pipeline object (and on the
+ duck-typed doubles the route tests build), so this can only ever add
+ correctness, never remove a working path.
+ """
+ if pipeline is None:
+ return None
+ builder = getattr(pipeline, "_dictation_stt", None)
+ if callable(builder):
+ try:
+ instance = builder()
+ except Exception as exc: # noqa: BLE001 — fall through to the voice one
+ log.debug("dictation-specific STT unavailable for restore: %s", exc)
+ else:
+ if instance is not None:
+ return instance
+ return getattr(pipeline, "_utterance_stt", None)
+
+
+async def _format_restored_text(
+ raw: str, *, reported: str, request: Request
+) -> tuple[str, str]:
+ """Run a re-transcription through the delivery chain. ``(text, language)``.
+
+ A Restore that produced different text than the original delivery would be
+ a quiet lie about what the button does, so this applies the SAME three
+ steps, in the same order and with the same decisions: resolve the language,
+ remove fillers, repair the punctuation our own segment boundaries broke,
+ and — when it is switched on and reachable — polish. Each step owns its own
+ decision in its own module; nothing is re-derived here.
+
+ Fail-open at every step, like the delivery path: the user asked for their
+ words back, and a formatting bug must never be the reason they do not get
+ them.
+ """
+ from jarvis.dictation.cleanup import clean_transcript, tidy_transcript
+
+ cfg = _dictation_cfg(request)
+ pinned = str(getattr(cfg, "language", "auto") or "auto")
+ language = pinned if pinned.strip().lower() not in ("", "auto") else reported
+ try:
+ # The decision itself lives with the live delivery path, so the two
+ # cannot drift into cleaning the same recording under different rules.
+ # The pipeline module is already imported by the time we get here — a
+ # provider answered, which means a pipeline is running — so this costs
+ # nothing; the guard is for the case where it somehow is not, and a
+ # failed import must never turn a restore into a 500.
+ from jarvis.speech.pipeline import resolve_dictation_language
+
+ language = resolve_dictation_language(
+ pinned=pinned, reported=reported, text=raw
+ )
+ except Exception: # noqa: BLE001 — fall back to pin-then-tag
+ log.debug("restore language resolution unavailable", exc_info=True)
+
+ text = raw
+ try:
+ outcome = clean_transcript(
+ raw,
+ language=language,
+ remove_fillers=bool(getattr(cfg, "remove_fillers", True)),
+ max_removed_fraction=float(
+ getattr(cfg, "filler_max_removed_fraction", 0.25)
+ ),
+ )
+ text = outcome.text
+ except Exception: # noqa: BLE001 — never lose the text to a cleanup bug
+ log.warning("restore cleanup failed; keeping the raw transcript", exc_info=True)
+ try:
+ text = tidy_transcript(text)
+ except Exception: # noqa: BLE001 — a tidy bug never costs the words
+ log.debug("restore tidy failed; keeping the untidied text", exc_info=True)
+
+ try:
+ from jarvis.dictation.polish import polish_enabled, polish_transcript
+
+ if text.strip() and polish_enabled(cfg):
+ pipeline = _pipeline()
+ terms = ()
+ getter = getattr(pipeline, "_dictation_protected_terms", None)
+ if callable(getter):
+ try:
+ terms = tuple(getter())
+ except Exception as exc: # noqa: BLE001 — a guard input, not a gate
+ log.debug("restore protected terms unavailable: %s", exc)
+ result = await polish_transcript(
+ text,
+ language=language,
+ cfg=cfg,
+ protected_terms=terms,
+ style=str(getattr(cfg, "polish_style", "neutral") or "neutral"),
+ )
+ text = result.text
+ log.info(
+ "restore polish: %s (%s, %d ms).",
+ result.status,
+ result.provider or "no provider",
+ result.latency_ms,
+ )
+ except Exception: # noqa: BLE001 — never lose the text to the polish pass
+ log.warning("restore polish failed; keeping the unpolished text", exc_info=True)
+
+ return text, language
async def _retranscribe_from_audio(
- entry: Any, *, language: str | None
-) -> tuple[str, str, str | None]:
- """Transcribe a kept audio sidecar again. ``(text, language, detail)``.
+ entry: Any, *, language: str, request: Request
+) -> tuple[str, str, str, str | None]:
+ """Transcribe a kept audio sidecar again. ``(raw, text, language, detail)``.
+
+ ``raw`` is what the provider returned and ``text`` is what the delivery
+ chain makes of it — the same split the live path keeps, so the history row
+ still holds the words as heard while the user gets the formatted version.
``detail`` is a plain-English explanation of why nothing came back, or
``None`` when it did. Every failure path returns one instead of raising:
@@ -136,40 +288,39 @@ async def _retranscribe_from_audio(
"""
from jarvis.dictation.audio import load_dictation_audio
- pipeline = _pipeline()
- # The pipeline's final-transcription provider is the right one to reuse:
- # it is already wrapped with the user's spoken-vocabulary corrections, so a
- # restore spells names the same way the original dictation would have.
- stt = getattr(pipeline, "_utterance_stt", None) if pipeline is not None else None
+ stt = _restore_stt(_pipeline())
if stt is None:
- return "", "", _NO_STT_DETAIL
+ return "", "", "", _NO_STT_DETAIL
# Reading and decoding a WAV is blocking work; it must not sit on the event
# loop that a live voice turn shares.
pcm = await asyncio.to_thread(load_dictation_audio, entry.audio_path)
if not pcm:
- return "", "", "The saved audio for this dictation could not be read."
+ return "", "", "", "The saved audio for this dictation could not be read."
try:
- if language is None:
+ try:
+ transcript = await stt.transcribe_pcm(pcm, language=language)
+ except TypeError:
+ # A provider that predates the keyword — the contract allows a bare
+ # ``transcribe_pcm(pcm)``. Falling back beats calling the user's
+ # language choice a failure (precedent: rolling_whisper_wake).
transcript = await stt.transcribe_pcm(pcm)
- else:
- try:
- transcript = await stt.transcribe_pcm(pcm, language=language)
- except TypeError:
- # A provider that predates the keyword — the contract allows a
- # bare ``transcribe_pcm(pcm)``. Falling back beats calling the
- # user's language pin a failure (precedent: rolling_whisper_wake).
- transcript = await stt.transcribe_pcm(pcm)
except Exception as exc: # noqa: BLE001 — a failed restore is never a 500
log.warning("dictation restore transcription failed: %s", exc, exc_info=True)
- return "", "", f"Transcribing the saved audio failed: {exc}"
-
- text = str(getattr(transcript, "text", "") or "").strip()
- detected = str(getattr(transcript, "language", "") or "")
- if not text:
- return "", detected, "The saved audio produced no text — it may be silence."
- return text, detected, None
+ return "", "", "", f"Transcribing the saved audio failed: {exc}"
+
+ raw = str(getattr(transcript, "text", "") or "").strip()
+ reported = str(getattr(transcript, "language", "") or "")
+ if not raw:
+ return (
+ "", "", reported,
+ "The saved audio produced no text — it may be silence.",
+ )
+ text, resolved = await _format_restored_text(
+ raw, reported=reported, request=request
+ )
+ return raw, text, resolved, None
def _read_for_restore(entry_id: str) -> tuple[Any, bool]:
@@ -265,6 +416,48 @@ class SettingsBody(BaseModel):
)
audio_retention_days: int | None = None
audio_max_files: int | None = None
+ # The polish pass. Every key here is also in ``DICTATION_SETTING_KEYS``, so
+ # it persists through this one route with no writer change — but FastAPI
+ # DROPS body keys a model does not declare, so a key missing from here is a
+ # setting the UI appears to save and silently loses on the next restart.
+ polish: bool | None = Field(
+ default=None,
+ description=(
+ "Let a fast model re-read the transcript and write it the way you "
+ "would have typed it: punctuation, sentence breaks, filler and "
+ "false starts removed. The words and the meaning are preserved, "
+ "and the raw transcript is always kept in the history. Falls back "
+ "to the plain transcript when no model is reachable."
+ ),
+ )
+ polish_provider: str | None = Field(
+ default=None,
+ description=(
+ "Which model family writes the polished text: auto (use whichever "
+ "key you already have) or a specific family"
+ ),
+ )
+ polish_model: str | None = Field(
+ default=None,
+ description="Model id for the chosen family; empty = that family's default",
+ )
+ polish_timeout_ms: int | None = Field(
+ default=None,
+ description=(
+ "How long the polish pass may take before the plain transcript is "
+ "delivered instead (200-5000 ms)"
+ ),
+ )
+ polish_max_input_chars: int | None = None
+ polish_min_words: int | None = None
+ polish_max_output_tokens: int | None = None
+ polish_temperature: float | None = None
+ polish_drift_max_shrink: float | None = None
+ polish_drift_max_growth: float | None = None
+ polish_style: str | None = Field(
+ default=None,
+ description="Register the polished text is written in",
+ )
persist: bool = Field(
default=True, description="Also write the change to jarvis.toml"
)
@@ -587,16 +780,26 @@ async def restore_history_entry(entry_id: str, request: Request) -> dict[str, An
detail: str | None = None
retranscribed = False
if not has_text:
- text, detected, detail = await _retranscribe_from_audio(
- entry, language=_pinned_language(request)
+ raw, text, detected, detail = await _retranscribe_from_audio(
+ entry, language=_chosen_language(request), request=request
)
if text:
retranscribed = True
changes.update(
- raw_text=text,
+ # The provider's words and the formatted words are stored
+ # separately, exactly as a live dictation stores them: the raw
+ # column is what makes "give me the text I actually said"
+ # answerable after a polish pass has run.
+ raw_text=raw,
text=text,
word_count=count_words(text),
- language=detected or entry.language,
+ # Normalized rather than stored verbatim: the same recording
+ # transcribed twice can come back tagged "German" once and "de"
+ # the next time, and a consumer doing ``{"de": ...}.get(lang)``
+ # misses on the first. The store normalizes on write as well —
+ # this is the belt to that brace, and it also keeps the value
+ # the RESPONSE carries consistent with what was resolved.
+ language=_normalized_language(detected or entry.language),
# The recorded failure is over — but the OUTCOME stays what it
# was. The dictation really did fail to reach the window the
# user was typing in; rewriting it to "inserted" would invent
@@ -673,13 +876,14 @@ async def get_settings(request: Request) -> dict[str, Any]:
the cost of getting it wrong here is a recorder that happily captures a key
the actuator cannot send, which then fails silently at paste time.
"""
- from jarvis.core.config import DICTATION_LANGUAGES
+ from jarvis.core.config import DICTATION_LANGUAGES, POLISH_STYLES
from jarvis.core.config_writer import DICTATION_SETTING_KEYS
from jarvis.dictation.insert import (
CUSTOM_CHORD_KEYS,
CUSTOM_CHORD_MODIFIERS,
PASTE_CHORDS,
)
+ from jarvis.dictation.polish_client import POLISH_FAMILIES
dictation = _dictation_cfg(request)
values = {key: getattr(dictation, key, None) for key in DICTATION_SETTING_KEYS}
@@ -691,6 +895,12 @@ async def get_settings(request: Request) -> dict[str, Any]:
"insert_method": ["clipboard", "type"],
"paste_chord": ["auto", *PASTE_CHORDS],
"language": list(DICTATION_LANGUAGES),
+ # Both derived from their single source of truth rather than typed
+ # out here: a hand-mirrored list is the AP-4 drift trap, and the
+ # cost of getting it wrong is a dropdown offering a value the
+ # backend rejects (or hiding one it accepts).
+ "polish_style": list(POLISH_STYLES),
+ "polish_provider": ["auto", *(family.id for family in POLISH_FAMILIES)],
},
"custom": {
"paste_chord": {
@@ -791,6 +1001,14 @@ async def put_settings(body: SettingsBody, request: Request) -> dict[str, Any]:
try:
pipeline._dictation_cfg = dictation
pipeline._dictation_max_s = float(validated.max_seconds)
+ # The dictation lane caches its own STT instance, built from this
+ # config (its bias prompt, its fallback chain). Dropping it here is
+ # what makes a change take effect on the next press instead of on
+ # the next restart — the difference between a setting and a setting
+ # that appears to work.
+ reset = getattr(pipeline, "_reset_dictation_stt", None)
+ if callable(reset):
+ reset()
if "mode" in updates:
pipeline._dictate_mode = validated.mode
# The mode decides whether the binding wants both key edges,
@@ -810,3 +1028,79 @@ async def put_settings(body: SettingsBody, request: Request) -> dict[str, Any]:
"persisted": persisted,
"applied_live": applied_live,
}
+
+
+#: The transcript the polish dry-run sends. Deliberately shaped like the real
+#: defect and not like a demo sentence: two segments joined mid-thought, the
+#: recognizer's own trailing ellipsis, a lower-case restart, a filler, a false
+#: start the speaker corrected, and a spoken number. English, because it is a
+#: fixed artifact in the repo rather than user content — the pass itself works
+#: in whatever language it is handed.
+_POLISH_SAMPLE = (
+ "so um i think we should ship the report on tuesday ... actually "
+ "wednesday and send it to three people on the team then we can talk "
+ "about the rest tomorrow"
+)
+
+
[email protected]("/polish/test")
+async def test_polish(request: Request) -> dict[str, Any]:
+ """Run one fixed sample through the resolved polish chain and report it.
+
+ The honest answer to "is this switched on, who answers, and how long does it
+ cost me" — which nothing else can give, because the pass is invisible by
+ design when it works and silently falls back to the raw text when it does
+ not. It uses the live ``[dictation]`` config, so what it measures is what a
+ real dictation would get, and it deliberately does NOT persist anything or
+ touch the history: it is a probe, not an action, so it carries no
+ destructive-route marker.
+
+ Never 500s. A host with no key in any family gets ``status: unavailable``
+ and the sample back unchanged — the same answer a dictation would get, and
+ the honest one on an install that never configured a text model.
+ """
+ from jarvis.dictation.polish import polish_enabled, polish_transcript
+
+ cfg = _dictation_cfg(request)
+ if not polish_enabled(cfg):
+ # Reported rather than refused: "you switched it off" is a complete
+ # answer to "why is my dictation not being polished", and a 409 here
+ # would make the settings screen render an error for a working config.
+ return {
+ "status": "off",
+ "provider": "",
+ "model": "",
+ "latency_ms": 0,
+ "reason": "",
+ "sample_in": _POLISH_SAMPLE,
+ "sample_out": _POLISH_SAMPLE,
+ }
+
+ pipeline = _pipeline()
+ terms: tuple[str, ...] = ()
+ getter = getattr(pipeline, "_dictation_protected_terms", None)
+ if callable(getter):
+ try:
+ terms = tuple(getter())
+ except Exception as exc: # noqa: BLE001 — a guard input, never a gate
+ log.debug("polish test protected terms unavailable: %s", exc)
+
+ result = await polish_transcript(
+ _POLISH_SAMPLE,
+ language="en",
+ cfg=cfg,
+ protected_terms=terms,
+ style=str(getattr(cfg, "polish_style", "neutral") or "neutral"),
+ )
+ return {
+ "status": result.status,
+ "provider": result.provider,
+ "model": result.model,
+ "latency_ms": result.latency_ms,
+ # Machine-readable cause when a guard or the transport refused. Shown
+ # next to the status because "rejected_drift" without "lost_term" tells
+ # a user nothing they can act on.
+ "reason": result.reason,
+ "sample_in": _POLISH_SAMPLE,
+ "sample_out": result.text,
+ }
diff --git a/tests/unit/dictation/test_delivery_gates.py b/tests/unit/dictation/test_delivery_gates.py
new file mode 100644
index 0000000000..2a38d34445
--- /dev/null
+++ b/tests/unit/dictation/test_delivery_gates.py
@@ -0,0 +1,445 @@
+"""What a dictation is allowed to put into a document, and how long it lasted.
+
+Four gates guard the last step of a dictation, and every one of them exists
+because the live history of 2026-07-28 shows what happens without it:
+
+* **Silence boilerplate.** 12 of the first 26 rows are "Thank you." or "Thank
+ you for watching!" — a Whisper-family model answering a near-silent
+ microphone. The repo has owned the marker list for months and the voice lane
+ filters on it in four places; the dictation lane did not.
+* **A transcript with no words.** A bare "." was pasted into a live document
+ and the clipboard was restored over it, costing the user both the stray
+ character and whatever they had copied.
+* **The language a transcript is cleaned in.** A provider tag of "English" on
+ German speech used to win over the text itself, and the cleanup then ran the
+ English rules over German words.
+* **How long the user spoke.** The wall clock ran from before the microphone
+ opened until after the last provider retry, so every stored duration — and
+ every words-per-minute figure derived from it — was inflated by whatever the
+ network did that day.
+
+The delivery half is tested directly through ``_finish_dictation``, which needs
+no microphone; the duration is tested through a whole ``_dictation_session``
+with a fake microphone and a deliberately slow provider, because the point of
+that fix is precisely that provider latency no longer reaches the number.
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.core.config import DictationConfig
+from jarvis.core.events import DictationCompleted, DictationTranscript
+from jarvis.dictation.insert import InsertResult, insert_text
+from jarvis.speech.pipeline import SpeechPipeline, _is_silence_hallucination
+
+# 16 kHz mono int16 — the capture contract every dictation records under.
+BYTES_PER_SECOND = 16_000 * 2
+
+# German fixtures. A transcript reproduces the speaker's own words, so the
+# dictated German IS the thing under test here (CLAUDE.md §1, list #4).
+DE_SENTENCE = "Er hat gesagt, dass er das Dokument gleich schickt." # i18n-allow: fixture
+DE_THANKS = "Vielen Dank für das Update" # i18n-allow: fixture
+
+
+def _pipeline(cfg: DictationConfig | None = None):
+ """A pipeline with only the delivery half wired, and no disk anywhere."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_cfg = cfg or DictationConfig(history_enabled=False)
+ events: list[object] = []
+ inserted: list[str] = []
+
+ async def _publish(event: object) -> None:
+ events.append(event)
+
+ pipe._publish_event = _publish # type: ignore[assignment]
+ pipe._insert_dictation = lambda text: ( # type: ignore[assignment]
+ inserted.append(text)
+ or InsertResult(
+ status="inserted", detail="", clipboard_holds_text=False,
+ method="clipboard+ctrl_v",
+ )
+ )
+ return pipe, events, inserted
+
+
+def _completed(events: list[object]) -> DictationCompleted:
+ return next(e for e in events if isinstance(e, DictationCompleted))
+
+
+def _final_transcript(events: list[object]) -> DictationTranscript:
+ return next(
+ e for e in events if isinstance(e, DictationTranscript) and e.is_final
+ )
+
+
+# --------------------------------------------------------------------------
+# The silence hallucination — the whole utterance, and only on short audio
+# --------------------------------------------------------------------------
+
+
+async def test_a_short_thank_you_for_watching_is_empty_not_inserted() -> None:
+ """The exact shape that filled the live history: a second and a half of
+ near-silence, and a video outro nobody said."""
+ pipe, events, inserted = _pipeline()
+ text = await pipe._finish_dictation(
+ raw_text="Thank you for watching!",
+ language="en",
+ duration_s=1.4,
+ target="insert",
+ hung_up=False,
+ )
+ assert text == ""
+ assert inserted == []
+ completed = _completed(events)
+ assert completed.outcome == "empty"
+ # The raw transcript is kept: the history row must still show what the
+ # provider actually returned, or the rejection is unauditable.
+ assert completed.raw_text == "Thank you for watching!"
+ assert completed.detail.strip(), "an unexplained empty result is the old bug"
+
+
+async def test_the_rejected_text_never_reaches_the_composer_either() -> None:
+ """Skipping only the INSERTION would leave the same words sitting in the
+ chat composer and on the bar — the identical defect in another window."""
+ pipe, events, _inserted = _pipeline()
+ await pipe._finish_dictation(
+ raw_text="Thank you.", language="en", duration_s=0.9,
+ target="chat", hung_up=False,
+ )
+ assert _final_transcript(events).text == ""
+ assert _completed(events).outcome == "empty"
+
+
+async def test_a_genuinely_spoken_thank_you_is_delivered() -> None:
+ """Five seconds of audio is a person speaking. The filter must stand down,
+ or it becomes a new way of losing text."""
+ pipe, events, inserted = _pipeline()
+ text = await pipe._finish_dictation(
+ raw_text="thank you very much for the update",
+ language="en",
+ duration_s=5.0,
+ target="insert",
+ hung_up=False,
+ )
+ assert text == "thank you very much for the update"
+ assert inserted == ["thank you very much for the update"]
+ assert _completed(events).outcome == "inserted"
+
+
+async def test_a_short_sentence_that_merely_contains_a_marker_survives() -> None:
+ """``DE_THANKS`` opens with a marker phrase and is still a real sentence.
+
+ Two seconds is inside the duration gate, so the ONLY thing keeping this text
+ is the whole-utterance rule — which is why it is pinned separately.
+ """
+ pipe, events, inserted = _pipeline()
+ await pipe._finish_dictation(
+ raw_text=DE_THANKS,
+ language="de",
+ duration_s=2.0,
+ target="insert",
+ hung_up=False,
+ )
+ assert inserted == [DE_THANKS]
+ assert _completed(events).outcome == "inserted"
+
+
+ "text",
+ [
+ "Thank you.",
+ "Thank you for watching!",
+ "thanks for watching",
+ "please subscribe",
+ "Untertitelung des ZDF, 2020", # i18n-allow: Whisper-noise vocabulary
+ ],
+)
+def test_known_boilerplate_is_recognised_on_short_audio(text: str) -> None:
+ assert _is_silence_hallucination(text, 1.2) is True
+
+
+ ("text", "duration_s"),
+ [
+ # Long enough to be speech, whatever it says.
+ ("Thank you for watching!", 4.0),
+ # Short, but the boilerplate is not the whole utterance.
+ ("thank you very much for the update", 1.0),
+ (DE_THANKS, 1.0),
+ ("check www.example.com for the numbers", 1.0),
+ ("", 1.0),
+ ],
+)
+def test_everything_else_is_left_alone(text: str, duration_s: float) -> None:
+ assert _is_silence_hallucination(text, duration_s) is False
+
+
+# --------------------------------------------------------------------------
+# Nothing without words gets delivered
+# --------------------------------------------------------------------------
+
+
+async def test_a_bare_full_stop_is_empty_not_inserted() -> None:
+ """History row 2026-07-28T18:10:30: ``raw_text "."``, ``word_count 0``,
+ ``outcome "inserted"`` — pasted into a document, then buried under the
+ restored clipboard."""
+ pipe, events, inserted = _pipeline()
+ text = await pipe._finish_dictation(
+ raw_text=".", language="en", duration_s=3.0, target="insert",
+ hung_up=False,
+ )
+ assert text == ""
+ assert inserted == []
+ completed = _completed(events)
+ assert completed.outcome == "empty"
+ assert completed.detail.strip()
+
+
+async def test_punctuation_only_output_is_refused_at_any_duration() -> None:
+ """Unlike the hallucination filter this gate has no duration condition:
+ a transcript with no words is worthless however long the recording was."""
+ pipe, events, inserted = _pipeline()
+ await pipe._finish_dictation(
+ raw_text="... ,", language="en", duration_s=42.0, target="insert",
+ hung_up=False,
+ )
+ assert inserted == []
+ assert _completed(events).outcome == "empty"
+
+
+async def test_one_real_word_is_still_delivered() -> None:
+ """The floor is "no words at all", not "not enough words"."""
+ pipe, _events, inserted = _pipeline()
+ await pipe._finish_dictation(
+ raw_text="Yes.", language="en", duration_s=0.8, target="insert",
+ hung_up=False,
+ )
+ assert inserted == ["Yes."]
+
+
+def test_insert_text_refuses_a_wordless_string_on_its_own() -> None:
+ """Defence in depth: the pipeline gates first, but every other caller of
+ ``insert_text`` — including the ones that do not exist yet — gets the same
+ floor, and it must refuse BEFORE touching the clipboard."""
+ result = insert_text(".")
+ assert result.status == "unavailable"
+ assert result.clipboard_holds_text is False
+
+
+# --------------------------------------------------------------------------
+# Which language the transcript is cleaned in
+# --------------------------------------------------------------------------
+
+
+async def test_german_text_tagged_english_resolves_as_german() -> None:
+ """The worst text defect this feature had.
+
+ Groq and OpenAI report a language NAME on every request and report it
+ confidently when it is wrong. ``normalize_language_tag("English")`` is "en",
+ never "unknown", so the old text-based rescue — gated on an UNPARSEABLE tag
+ — never ran, and the English cleanup rules were applied to German speech.
+ """
+ pipe, events, _inserted = _pipeline()
+ await pipe._finish_dictation(
+ raw_text=DE_SENTENCE,
+ language="English",
+ duration_s=4.0,
+ target="chat",
+ hung_up=False,
+ )
+ completed = _completed(events)
+ assert completed.language == "de"
+ # And the German words survive intact — the wrong language is only a defect
+ # because of what the cleanup then does with it.
+ assert completed.text == DE_SENTENCE
+
+
+async def test_a_user_pin_outranks_the_text() -> None:
+ """The pin is the one signal a person can set. Overruling it with a
+ detector would leave them no way to be right."""
+ pipe, events, _inserted = _pipeline(
+ DictationConfig(language="en", history_enabled=False)
+ )
+ await pipe._finish_dictation(
+ raw_text=DE_SENTENCE,
+ language="English",
+ duration_s=4.0,
+ target="chat",
+ hung_up=False,
+ )
+ assert _completed(events).language == "en"
+
+
+async def test_a_tag_outside_de_en_es_is_kept_rather_than_coerced() -> None:
+ """``detect_text_language`` only knows de/en/es, so letting it overrule a
+ French 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, which is the honest answer for
+ ~95 of the 100 recognition languages.
+
+ The fixture is chosen to make that concrete: this French sentence shares
+ enough tokens with the Spanish vocabulary that the detector calls it "es",
+ so a resolver that trusted the text here would clean French with Spanish
+ rules.
+ """
+ french = "Il faut que je vous envoie le document avec les chiffres tout de suite."
+ from jarvis.core.turn_language import detect_text_language
+
+ assert detect_text_language(french) == "es", "fixture no longer bites"
+
+ pipe, events, _inserted = _pipeline()
+ await pipe._finish_dictation(
+ raw_text=french,
+ language="French",
+ duration_s=4.0,
+ target="chat",
+ hung_up=False,
+ )
+ assert _completed(events).language == "French"
+
+
+async def test_a_silent_provider_still_gets_its_language_from_the_text() -> None:
+ """The rescue that already shipped stays: with no tag at all the text is
+ the only signal there is, and without it the cleanup answers every
+ dictation with "no rules for this language"."""
+ pipe, events, _inserted = _pipeline()
+ await pipe._finish_dictation(
+ raw_text=DE_SENTENCE,
+ language="",
+ duration_s=4.0,
+ target="chat",
+ hung_up=False,
+ )
+ assert _completed(events).language == "de"
+
+
+async def test_an_agreeing_provider_tag_is_left_untouched() -> None:
+ pipe, events, _inserted = _pipeline()
+ await pipe._finish_dictation(
+ raw_text="hello there, this is the summary", language="en",
+ duration_s=4.0, target="chat", hung_up=False,
+ )
+ assert _completed(events).language == "en"
+
+
+# --------------------------------------------------------------------------
+# duration_s comes from the audio, not from the clock
+# --------------------------------------------------------------------------
+
+
+class _FakeChunk:
+ def __init__(self, pcm: bytes) -> None:
+ self.pcm = pcm
+
+
+class _FakeMic:
+ """Yields one chunk and ends, which is what closes the session."""
+
+ def __init__(self, pcm: bytes) -> None:
+ self._pcm = pcm
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_exc) -> bool:
+ return False
+
+ async def stream(self):
+ yield _FakeChunk(self._pcm)
+
+
+class _SlowSTT:
+ """A provider that answers correctly, but takes its time doing it."""
+
+ def __init__(self, delay_s: float) -> None:
+ self._delay_s = delay_s
+
+ async def transcribe_pcm(self, pcm: bytes, **_kw):
+ await asyncio.sleep(self._delay_s)
+ return SimpleNamespace(text="the recorded sentence", language="en")
+
+
+def _session_pipeline(stt, cfg: DictationConfig):
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._utterance_stt = stt
+ pipe._dictation_cfg = cfg
+ pipe._dictation_target = "chat"
+ pipe._ptt_partial_interval_s = 0.0
+ pipe._dictation_max_s = 5.0
+ pipe._input_device = None
+ pipe._input_priority = None
+ pipe._dictation_stop_event = asyncio.Event()
+ pipe._hangup_event = asyncio.Event()
+ events: list[object] = []
+
+ async def _publish(event: object) -> None:
+ events.append(event)
+
+ pipe._publish_event = _publish # type: ignore[assignment]
+ return pipe, events
+
+
+async def test_duration_is_the_length_of_the_audio_not_of_the_wait(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Two seconds of speech stay two seconds however long the provider took.
+
+ The clock used to start before the microphone opened and stop after the
+ final transcription — retry sleeps included — so a slow or rate-limited
+ provider inflated the stored duration by seconds. That number is what the
+ statistics sidecar divides the word count by, so it silently under-reported
+ the user's words per minute and stretched every streak built on it.
+ """
+ import jarvis.speech.pipeline as pipeline_mod
+
+ pcm = b"\x00\x01" * 32_000 # 64 000 bytes = exactly 2.0 s
+ monkeypatch.setattr(
+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(pcm)
+ )
+ pipe, events = _session_pipeline(
+ _SlowSTT(0.35),
+ DictationConfig(partial_interval_s=0.0, history_enabled=False),
+ )
+ await pipe._dictation_session()
+
+ completed = _completed(events)
+ # The transcript really did travel the slow path — without this the
+ # duration assertion could pass on a session that transcribed nothing.
+ assert completed.text == "the recorded sentence"
+ assert completed.duration_s == pytest.approx(len(pcm) / BYTES_PER_SECOND)
+ assert completed.duration_s == pytest.approx(2.0)
+
+
+async def test_a_recording_that_captured_nothing_reports_no_duration(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No audio means no dictation. Reporting the seconds the machinery spent
+ failing would put a duration on a row that holds no speech."""
+ import jarvis.speech.pipeline as pipeline_mod
+
+ monkeypatch.setattr(
+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"")
+ )
+ pipe, events = _session_pipeline(
+ _SlowSTT(0.05),
+ DictationConfig(partial_interval_s=0.0, history_enabled=False),
+ )
+ await pipe._dictation_session()
+ assert _completed(events).duration_s == pytest.approx(0.0)
diff --git a/tests/unit/dictation/test_polish_hook.py b/tests/unit/dictation/test_polish_hook.py
new file mode 100644
index 0000000000..e4e27ff68a
--- /dev/null
+++ b/tests/unit/dictation/test_polish_hook.py
@@ -0,0 +1,397 @@
+"""Where the polish pass plugs into the delivery path, and what it may cost.
+
+``polish.py`` is tested on its own; this file tests the WIRING, which is the
+half that decides whether the feature is safe to ship on by default:
+
+* the deterministic punctuation repair runs on EVERY dictation, not only on one
+ a filler was removed from — the damage it fixes is manufactured by our own
+ segmented transcription, so gating it on the cleanup's outcome (where it used
+ to sit) left every untouched stretch broken;
+* the polished string reaches the composer, the bar and the insertion ALIKE,
+ because they all read the one final transcript published here;
+* ``raw_text`` never changes, so the history keeps what the user actually said;
+* every failure mode of the pass — off, unreachable, timed out, rejected,
+ crashed — delivers the unpolished text rather than nothing;
+* the pass never sees text the delivery gates already rejected, so a
+ hallucinated video outro does not cost a model call;
+* and the three facts about the pass travel outward on the completion event, so
+ a surface showing polished text can say that is what it is showing.
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.core.config import DictationConfig
+from jarvis.core.events import DictationCompleted, DictationTranscript
+from jarvis.dictation.polish import POLISH_STATUSES, PolishOutcome
+from jarvis.speech.pipeline import SpeechPipeline
+
+# A transcript with the two defects our own segmenting produces: an ellipsis
+# glued to a sentence that had already ended, and a segment restarting in lower
+# case. Long enough to clear the pass's minimum-word floor.
+SEGMENTED = "We talked about it. ... and then the report went out on Tuesday."
+
+POLISHED = "We talked about it. And then the report went out on Tuesday."
+
+
+def _pipeline(cfg: DictationConfig | None = None):
+ """A pipeline with only the delivery half wired, and no disk anywhere."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_cfg = cfg or DictationConfig(history_enabled=False, polish=False)
+ events: list[object] = []
+ inserted: list[str] = []
+
+ async def _publish(event: object) -> None:
+ events.append(event)
+
+ pipe._publish_event = _publish # type: ignore[assignment]
+ pipe._insert_dictation = lambda text: ( # type: ignore[assignment]
+ inserted.append(text)
+ or SimpleNamespace(status="inserted", detail="", method="clipboard+ctrl_v")
+ )
+ pipe._dictation_protected_terms = lambda: () # type: ignore[assignment]
+ return pipe, events, inserted
+
+
+def _completed(events: list[object]) -> DictationCompleted:
+ return next(e for e in events if isinstance(e, DictationCompleted))
+
+
+def _final_transcript(events: list[object]) -> DictationTranscript:
+ return next(e for e in events if isinstance(e, DictationTranscript) and e.is_final)
+
+
+def _install_polish(
+ monkeypatch: pytest.MonkeyPatch, outcome: PolishOutcome | Exception
+) -> list[dict[str, Any]]:
+ """Replace the pass with a recorder. Returns the list of calls it saw."""
+ import jarvis.dictation.polish as polish
+
+ calls: list[dict[str, Any]] = []
+
+ async def _fake(raw: str, **kwargs: Any) -> PolishOutcome:
+ calls.append({"raw": raw, **kwargs})
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+
+ monkeypatch.setattr(polish, "polish_transcript", _fake)
+ return calls
+
+
+# --------------------------------------------------------------------------
+# The deterministic repair, which is not gated on anything
+# --------------------------------------------------------------------------
+
+
+async def test_punctuation_is_repaired_even_with_the_filler_cleanup_off() -> None:
+ """The two are not variants of one step. Filler removal is a preference
+ covering three languages; this damage is ours and exists in all of them."""
+ pipe, events, _inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=False, remove_fillers=False)
+ )
+
+ text = await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="chat", hung_up=False,
+ )
+
+ assert "...." not in text
+ assert " ... and" not in text
+ assert _final_transcript(events).text == text
+
+
+async def test_punctuation_is_repaired_in_a_language_with_no_filler_rules() -> None:
+ """~95 of the 100 recognition languages have no filler table, and every one
+ of them still gets its segments joined by us."""
+ pipe, _events, _inserted = _pipeline()
+
+ text = await pipe._finish_dictation(
+ raw_text="Chiedo scusa. ... e poi il documento.", # i18n-allow: fixture
+ language="it",
+ duration_s=6.0,
+ target="chat",
+ hung_up=False,
+ )
+
+ assert "...." not in text
+ assert "..." not in text
+
+
+# --------------------------------------------------------------------------
+# The polish pass — the happy path and everything the composer sees
+# --------------------------------------------------------------------------
+
+
+async def test_the_polished_text_is_what_gets_delivered(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls = _install_polish(
+ monkeypatch,
+ PolishOutcome(
+ text=POLISHED, status="applied", provider="groq",
+ model="llama-3.1-8b-instant", latency_ms=412,
+ ),
+ )
+ pipe, events, inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True)
+ )
+
+ text = await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="insert", hung_up=False,
+ )
+
+ assert text == POLISHED
+ # The composer, the bar and the insertion all read the SAME string. A
+ # polished paste next to an unpolished composer is a divergence nobody can
+ # explain afterwards.
+ assert inserted == [POLISHED]
+ assert _final_transcript(events).text == POLISHED
+ assert len(calls) == 1
+ # It polished the CLEANED text, not the raw one: the deterministic repairs
+ # are cheaper and more reliable than asking a model to redo them.
+ assert "...." not in calls[0]["raw"]
+
+
+async def test_the_raw_transcript_is_never_replaced(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The user must always be able to recover the words they actually said."""
+ _install_polish(
+ monkeypatch,
+ PolishOutcome(text=POLISHED, status="applied", provider="groq"),
+ )
+ pipe, events, _inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True)
+ )
+
+ await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="chat", hung_up=False,
+ )
+
+ assert _completed(events).raw_text == SEGMENTED
+
+
+async def test_the_completion_carries_status_provider_and_latency(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _install_polish(
+ monkeypatch,
+ PolishOutcome(
+ text=POLISHED, status="applied", provider="gemini",
+ model="gemini-3.1-flash-lite", latency_ms=737,
+ ),
+ )
+ pipe, events, _inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True)
+ )
+
+ await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="chat", hung_up=False,
+ )
+
+ completed = _completed(events)
+ assert completed.polish_status == "applied"
+ assert completed.polish_status in POLISH_STATUSES
+ assert completed.polish_provider == "gemini"
+ assert completed.polish_latency_ms == 737
+
+
+async def test_the_resolved_language_and_the_protected_terms_are_handed_over(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The pass must not re-derive either: the language is already resolved, and
+ the protected terms are what stop a technical word being "corrected"."""
+ calls = _install_polish(
+ monkeypatch, PolishOutcome(text=POLISHED, status="applied", provider="groq")
+ )
+ pipe, _events, _inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True, language="de")
+ )
+ pipe._dictation_protected_terms = lambda: ("Vokando", "Adex") # type: ignore[assignment]
+
+ await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="chat", hung_up=False,
+ )
+
+ assert calls[0]["language"] == "de"
+ assert calls[0]["protected_terms"] == ("Vokando", "Adex")
+
+
+# --------------------------------------------------------------------------
+# Every way it can fail delivers the user's own words
+# --------------------------------------------------------------------------
+
+
+async def test_the_switch_off_is_byte_identical_and_costs_no_call(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls = _install_polish(
+ monkeypatch, PolishOutcome(text="NEVER", status="applied", provider="groq")
+ )
+ pipe, events, _inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=False)
+ )
+
+ text = await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="chat", hung_up=False,
+ )
+
+ assert calls == []
+ assert "NEVER" not in text
+ assert _completed(events).polish_status == "off"
+
+
+ "status",
+ ["unavailable", "timeout", "provider_error", "rejected_drift", "skipped_short"],
+)
+async def test_every_non_applied_status_delivers_the_unpolished_text(
+ monkeypatch: pytest.MonkeyPatch, status: str
+) -> None:
+ """``PolishOutcome.text`` is the raw string on all of them; the hook must
+ take it as given rather than second-guessing which ones are safe."""
+ unpolished: list[str] = []
+
+ import jarvis.dictation.polish as polish
+
+ async def _fake(raw: str, **_kwargs: Any) -> PolishOutcome:
+ unpolished.append(raw)
+ return PolishOutcome(text=raw, status=status, provider="")
+
+ monkeypatch.setattr(polish, "polish_transcript", _fake)
+ pipe, events, inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True)
+ )
+
+ text = await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="insert", hung_up=False,
+ )
+
+ assert text == unpolished[0]
+ assert inserted == [text]
+ assert _completed(events).polish_status == status
+
+
+async def test_a_crashing_polish_pass_still_delivers_the_dictation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The pass promises never to raise. This is the belt to that brace: a
+ formatting feature may never be the reason a dictation is lost."""
+ _install_polish(monkeypatch, RuntimeError("the module blew up"))
+ pipe, events, inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True)
+ )
+
+ text = await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="insert", hung_up=False,
+ )
+
+ assert text.strip()
+ assert inserted == [text]
+ assert _completed(events).polish_status == "provider_error"
+
+
+async def test_a_pass_that_hangs_is_bounded_by_its_own_ceiling(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The real ``polish_transcript`` owns the ceiling, so the hook must not add
+ a second one — but it must also not be able to hang the delivery. Verified
+ against the real function with a deliberately tiny budget and a transport
+ that never answers."""
+ import jarvis.dictation.polish as polish
+ from jarvis.dictation.polish_client import POLISH_FAMILIES
+
+ class _Slow:
+ async def complete(self, *_a: Any, **_k: Any) -> str:
+ await asyncio.sleep(30)
+ return "never" # pragma: no cover
+
+ polish.reset_polish_state()
+ monkeypatch.setattr(polish, "resolve_polish_chain", lambda cfg: (POLISH_FAMILIES[0],))
+ monkeypatch.setattr(polish, "build_polish_client", lambda family, *, model: _Slow())
+ pipe, events, _inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True, polish_timeout_ms=200)
+ )
+
+ try:
+ text = await asyncio.wait_for(
+ pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="chat", hung_up=False,
+ ),
+ timeout=10,
+ )
+ finally:
+ polish.reset_polish_state()
+
+ assert text.strip()
+ assert _completed(events).polish_status == "timeout"
+
+
+# --------------------------------------------------------------------------
+# Order — the gates run first, so rejected text costs nothing
+# --------------------------------------------------------------------------
+
+
+async def test_rejected_boilerplate_never_reaches_the_polish_pass(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A 1.4 s "Thank you for watching!" is thrown away by the delivery gates.
+ Paying a model call to format it would be spending on nothing."""
+ calls = _install_polish(
+ monkeypatch, PolishOutcome(text="x", status="applied", provider="groq")
+ )
+ pipe, events, _inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True)
+ )
+
+ text = await pipe._finish_dictation(
+ raw_text="Thank you for watching!", language="en", duration_s=1.4,
+ target="insert", hung_up=False,
+ )
+
+ assert text == ""
+ assert calls == []
+ assert _completed(events).outcome == "empty"
+
+
+async def test_a_hangup_polishes_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A hangup means "stop"; there is no delivery to format."""
+ calls = _install_polish(
+ monkeypatch, PolishOutcome(text="x", status="applied", provider="groq")
+ )
+ pipe, events, _inserted = _pipeline(
+ DictationConfig(history_enabled=False, polish=True)
+ )
+
+ await pipe._finish_dictation(
+ raw_text=SEGMENTED, language="en", duration_s=6.0,
+ target="chat", hung_up=True,
+ )
+
+ assert calls == []
+ assert _completed(events).polish_status == ""