Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(dictation): add multilingual final quality pass
Ruben Lütkea2d0b9f58536
diff --git a/docs/adr/0032-final-multilingual-dictation.md b/docs/adr/0032-final-multilingual-dictation.mdnew file mode 100644index 0000000000..4e7dfaf9f4--- /dev/null+++ b/docs/adr/0032-final-multilingual-dictation.md@@ -0,0 +1,113 @@+---+title: "ADR-0032: Final Multilingual Dictation Transcription"+slug: adr-0032-final-multilingual-dictation+diataxis: adr+status: active+owner: project-maintainers+last_reviewed: 2026-07-30+phase: speech+audience: developer+---++# ADR-0032 — Final Multilingual Dictation Transcription++**Status:** Accepted (2026-07-30)+**Reference:** AP-21, AP-22, AP-23, AP-24, AP-26, AP-30, AP-31++## Context++The dictation lane previously delivered text assembled from short STT segments.+Each segment carried one recognition language, so a language change inside a+sentence could be misrecognized or translated. A selected cloud model was not+reliably forwarded, OpenRouter transcription did not receive deterministic+temperature, and provider adapters assumed request/response fields that some+models reject. The desktop capture path also exposed an echo-cancellation+setting although raw PortAudio has no portable AEC, noise-suppression, or AGC+control.++## Decision++1. `[stt].models.<provider-id>` is the only cloud model pin. `[stt].model`+ remains the local faster-whisper checkpoint. `[stt].temperature` defaults to+ `0.0` and is forwarded only where the request shape accepts it.+2. Transcription request shape is model-capability driven. Unknown non-Whisper+ models start with the universal JSON response; a field-specific HTTP 400+ narrows the process-local capability and retries without that field.+3. Short segments serve the live preview and are never the preferred delivered+ transcript. After capture closes, the whole recording is transcribed in+ 25-second windows with 1.5-second overlap by default. Text overlap is merged+ without assuming whitespace, so CJK and other space-free scripts are not+ joined incorrectly. Preview text remains a fail-soft recovery path if the+ final pass cannot produce text.+4. With `[dictation].code_switching = true` (default), every final window asks+ for automatic language detection. A preferred language is not sent as a+ recognition lock. Provider output is returned in its spoken language; no+ translation request is made. Disabling the switch sends the explicit+ dictation-language pin for deliberately monolingual use.+5. `DictationCompleted` and the safe history API carry provider, effective+ model, reported languages, logical STT calls, aggregate latency, stable+ errors, sample rate, RMS, clipping ratio, capture dropouts, and path audit+ facts. Arbitrary history metadata remains private.+6. Raw PortAudio PCM stays byte-identical. The audit reports NS/AGC/AEC as+ unavailable (or AEC as off) until a platform backend advertises and passes a+ quality regression corpus. An unverified DSP filter is not a fallback.+7. `python -m jarvis.speech.stt_eval` compares exact provider/model pairs on a+ user-supplied, consented 16 kHz mono WAV corpus. It measures WER, annotated+ switch-anchor loss, median latency, billed gateway cost (when returned),+ explicit price-based estimates, and repeat variance. Reports omit reference+ text and hypotheses.++## Model evaluation status++GPT-4o Transcribe is a valid candidate, not a hardcoded dependency. OpenAI+reports improved word-error rate and language recognition relative to original+Whisper. GPT-4o Transcribe is currently token-priced; Whisper Large v3 Turbo is+currently minute-priced. These are vendor claims and inputs, not a Jarvis+quality verdict:++- [OpenAI GPT-4o Transcribe model](https://developers.openai.com/api/docs/models/gpt-4o-transcribe)+- [OpenAI API pricing](https://developers.openai.com/api/docs/pricing)+- [Groq speech-to-text documentation](https://console.groq.com/docs/speech-to-text)++The 2026-07-30 smoke comparison used four newly synthesized utterances, three+runs each, temperature 0, and the same OpenRouter endpoint. It covered Latin,+Arabic, Cyrillic, CJK, Devanagari, and Hangul scripts, multilingual voices,+proper names, and technical terms. Lower is better except cost:++| Model | WER | Switch error | Repeat error | Median latency | Billed cost |+|---|---:|---:|---:|---:|---:|+| Whisper Large v3 Turbo | 0.296 | 0.458 | 0.000 | 478 ms | $0.0013 |+| GPT-4o Transcribe | 0.470 | 0.583 | 0.092 | 992 ms | $0.0032 |++This small synthetic proxy does **not** justify changing the default: Whisper+won every aggregate metric here. A representative, consented human-speech+corpus with real accents and background conditions remains the release gate.+Run it with the same harness (quote each contender because `|` is a shell+operator):++```powershell+python -m jarvis.speech.stt_eval `+ --corpus data/stt-eval/corpus.jsonl `+ --contender "current|openrouter-stt|openai/whisper-large-v3-turbo|0" `+ --contender "candidate|openrouter-stt|openai/gpt-4o-transcribe|0" `+ --repeats 3+```++Each JSONL row contains `id`, relative `audio`, human `reference`, optional+`switch_anchors` spanning language boundaries, and optional `tags`. Credentials+are entered in-app and resolved through the normal secret store; they never+enter the corpus or command.++## Consequences++- Final delivery adds one post-recording STT pass and therefore latency and+ possible cloud cost. Long windows reduce language ambiguity; overlap avoids+ word loss at boundaries.+- A cloud-only/headless install may still spend short-preview requests before+ the final pass because no local preview engine is available. Runtime+ cross-family fallback and failed-audio Restore remain intact.+- Providers that return only plain JSON may not report language tags. The+ transcript remains usable and telemetry honestly leaves languages empty.+- NS/AGC/AEC remain an explicit open capability, not a silently enabled claim.+ A future processor must beat the raw-PCM control on a representative corpus;+ any WER or switch-error regression keeps the raw arm enabled.diff --git a/jarvis.toml.example b/jarvis.toml.exampleindex 57c2fdb893..3e7825ea7b 100644--- a/jarvis.toml.example+++ b/jarvis.toml.example@@ -46,8 +46,26 @@ sensitivity = 0.5 # 0.5..1 (values below 0.5 are lifted — the wake[stt]provider = "groq-api" # groq-api | openai-api | openrouter-stt | gemini-api | faster-whisper (local)device = "cpu" # cpu | cuda — keep "cpu" unless you have a local GPU-language = "auto" # "de" | "en" | "auto"+language = "auto" # auto, or a weak ISO-639 preference such as "fr"bias_prompt = "" # optional comma-separated vocab to stabilize proper nouns+temperature = 0.0 # deterministic when the selected model supports it++# Cloud model pins are provider-specific; an omitted pin uses that plugin's+# default. Configure these in the app's model picker in normal use.+[stt.models]+# openai-api = "gpt-4o-transcribe"+# openrouter-stt = "openai/gpt-4o-transcribe"++# ── Dictation quality ──+[dictation]+# Short segments update the live preview. Delivery comes from a second pass+# over the complete recording in long overlapping windows.+final_quality_pass = true+final_window_seconds = 25.0+final_overlap_seconds = 1.5+# Auto-detect each final window so language changes remain in the spoken+# language. Turn this off only to apply the preference as a hard monolingual pin.+code_switching = true# ── Text-to-Speech ──# Cloud default = Gemini Flash TTS (reuses your GEMINI_API_KEY). Alternatives:@@ -121,7 +139,7 @@ commands = ["format *", "rm -rf /", "del /f /s /q C:\\", "shutdown /p", "reg del[audio]input_device = "auto" # "auto" | shortest-unique device-name token (e.g. "PRO X")output_device = "auto"-echo_cancellation = true+echo_cancellation = true # requested; raw PortAudio reports unavailable honestlysample_rate = 16000 # mandatory 16 kHz (AP-L-16)# ── UI / tray ──diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 71841da4bb..6faccd31b1 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2745,13 +2745,62 @@ class DictationConfig(BaseModel):#: preview entirely (the final transcription still happens).partial_interval_s: float = Field(default=1.2, ge=0.0, le=10.0)- #: Segment length for streaming-style transcription. The old dictation lane+ #: Segment length for the LIVE line while you speak. The old dictation lane#: re-transcribed the whole growing buffer on every tick, which costs#: O(n²) audio-seconds and, on a paid API, real money. Closed segments are#: transcribed once and never again; only the open tail is re-sent.#: ``0`` restores the legacy full-buffer behaviour.+ #:+ #: With ``final_quality_pass`` on (the default), what these short segments+ #: produce is a PREVIEW and never the delivered text — see below for why+ #: that distinction is the whole of the multilingual repair.segment_seconds: float = Field(default=8.0, ge=0.0, le=60.0)+ #: Re-transcribe the WHOLE recording once, in long windows, after the key+ #: is released — and deliver that instead of the stitched-together short+ #: segments.+ #:+ #: A recognizer detects the spoken language from the audio it is handed.+ #: On an eight-second segment it is not sure, and an unsure model does not+ #: merely mislabel the language — it TRANSLATES. That is why one continuous+ #: recording used to arrive with one paragraph in the language spoken and+ #: the next in English, and why a sentence that switches language halfway+ #: through could not survive at all: each segment was decided separately.+ #: Long windows remove the cause rather than patching the symptom.+ #:+ #: The cost is one extra pass over the audio. It is paid back by the live+ #: line moving to the on-device preview engine where there is one, so a+ #: desktop install sends FEWER requests than before; a host without a local+ #: engine sends the short segments as before and this pass on top.+ final_quality_pass: bool = True++ #: Length of one final-pass window, in seconds. Long enough for reliable+ #: language detection, short enough to stay inside every provider's upload+ #: limit and to keep one failed window cheap.+ final_window_seconds: float = Field(default=25.0, ge=5.0, le=60.0)++ #: How much audio consecutive windows share. The overlap is what stops a+ #: word that straddles a boundary from being cut in half; the duplicate it+ #: creates is removed from the TEXT afterwards, which is possible, while+ #: recovering half a word is not. ``0`` disables the overlap.+ final_overlap_seconds: float = Field(default=1.5, ge=0.0, le=5.0)++ #: Allow the language to change WITHIN one dictation.+ #:+ #: While this is on (the default), the final pass asks the recognizer to+ #: detect the language from each long window instead of being told one, so+ #: a sentence that starts in one language and finishes in another is+ #: transcribed as it was spoken. ``language`` above then still governs how+ #: the finished text is treated — which filler rules run, which language+ #: the polish pass writes in — but it no longer LOCKS the recognizer, which+ #: is what used to turn a pin into a translation of everything else said.+ #:+ #: Turn it off to hand the pinned language to the recognizer outright. That+ #: is the right choice when you only ever dictate in one language and the+ #: provider keeps guessing wrong; it is the wrong choice for anyone who+ #: mixes languages, which is why it is not the default.+ code_switching: bool = True+#: Keep a local history of dictations (raw + cleaned, for auditing what the#: cleanup changed). Dictated text is among the most sensitive data this app#: holds, so it is local-only, capped, and purgeable from the UI.diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 142fdcd1ee..93724630e8 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -836,6 +836,10 @@ DICTATION_SETTING_KEYS = ("max_seconds","partial_interval_s","segment_seconds",+ "final_quality_pass",+ "final_window_seconds",+ "final_overlap_seconds",+ "code_switching","history_enabled","history_max_entries","history_retention_days",diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 15a987f761..8dc0be861d 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -196,6 +196,36 @@ class DictationCompleted(Event):#: place in the delivery path, so it is reported on every status, not only#: on ``applied``.polish_latency_ms: int = 0+ #: STT provider ids that produced text during this dictation, in first-use+ #: order. More than one means the runtime fallback crossed families.+ stt_providers: tuple[str, ...] = ()+ #: Effective/requested model ids corresponding to the successful STT calls.+ #: Kept as a set-like ordered tuple because a fallback may use more than one.+ stt_models: tuple[str, ...] = ()+ #: Language tags reported by the recognizer's final windows. The transcript+ #: remains the source of truth; these are diagnostics, never a language lock.+ detected_languages: tuple[str, ...] = ()+ #: Aggregate wall-clock time spent awaiting STT for this dictation.+ stt_latency_ms: int = 0+ #: Number of logical STT uploads, including previews and final attempts.+ #: A provider's internal request-shape downgrade is deliberately not+ #: observable at this layer.+ stt_calls: int = 0+ #: Stable reason codes observed during STT, with duplicates removed.+ stt_errors: tuple[str, ...] = ()+ #: Compact audit facts such as final-pass status, window count, and audio+ #: preprocessing decisions. English machine data, no transcript content.+ stt_audit: tuple[str, ...] = ()+ #: Stable PCM rate delivered to STT after any capture-side resampling.+ audio_sample_rate_hz: int = 0+ #: Whole-recording normalized RMS in the same 0..1 convention as VAD.+ audio_rms: float = 0.0+ #: Share of PCM16 samples at (or immediately below) full scale.+ audio_clipping_ratio: float = 0.0+ #: Discontinuities inferred from capture timestamps / queue overflow counts.+ audio_dropouts: int = 0+ #: Approximate duration missing across timestamp-detected discontinuities.+ audio_dropout_ms: int = 0#: Every reason a dictation start can be refused. Declared ONCE here, next todiff --git a/jarvis/dictation/audio_preprocessing.py b/jarvis/dictation/audio_preprocessing.pynew file mode 100644index 0000000000..9d514fb1b0--- /dev/null+++ b/jarvis/dictation/audio_preprocessing.py@@ -0,0 +1,178 @@+"""Honest capability verdicts for desktop dictation audio preprocessing.++The capture contract is raw 16 kHz mono PCM from PortAudio. PortAudio and+``sounddevice`` expose stream format and device selection; they do not expose a+portable switch for acoustic echo cancellation, noise suppression, or+automatic gain control. Applying an arbitrary DSP filter merely because a+config switch exists can remove quiet speech and make recognition worse.++Until a backend supplies a processor with measured, platform-specific support,+dictation therefore keeps the PCM byte-identical and records the missing+capabilities in its audit telemetry. This is an explicit degradation on+Windows, macOS, Linux, and headless hosts, not an implied feature.+"""++from __future__ import annotations++import math+import sys+from array import array+from dataclasses import dataclass+++@dataclass(frozen=True, slots=True)+class AudioPreprocessingDecision:+ """What the active desktop capture path can safely do."""++ noise_suppression: str+ automatic_gain_control: str+ acoustic_echo_cancellation: str+ pcm_changed: bool = False++ def audit(self) -> tuple[str, ...]:+ """Stable, transcript-free telemetry fields for one dictation."""+ return (+ "audio_preprocessing:raw_pcm",+ f"noise_suppression:{self.noise_suppression}",+ f"automatic_gain_control:{self.automatic_gain_control}",+ f"acoustic_echo_cancellation:{self.acoustic_echo_cancellation}",+ )+++@dataclass(frozen=True, slots=True)+class AudioQualityMetrics:+ """Signal facts captured before any STT provider sees the recording."""++ sample_rate_hz: int = 0+ rms: float = 0.0+ clipping_ratio: float = 0.0+ dropout_count: int = 0+ dropout_duration_ms: int = 0+++class AudioQualityAccumulator:+ """Streaming PCM16 quality measurement with timestamp-gap detection.++ Keeping the accumulator beside the preprocessing verdict makes the A/B+ contract explicit: both a future processed arm and today's raw control arm+ are measured using the same signal facts. It consumes each captured chunk+ once, so even an unbounded dictation is not copied or rescanned merely for+ telemetry.+ """++ _CLIP_LEVEL = 32_760++ def __init__(self) -> None:+ self._sample_rate_hz = 0+ self._sample_count = 0+ self._sum_squares = 0+ self._clipped_samples = 0+ self._dropout_count = 0+ self._dropout_duration_ns = 0+ self._previous_timestamp_ns = 0+ self._previous_duration_ns = 0++ def add_chunk(+ self,+ pcm: bytes,+ *,+ sample_rate_hz: int,+ timestamp_ns: int = 0,+ ) -> None:+ """Measure one little-endian mono PCM16 chunk. Invalid tails are ignored."""+ rate = max(0, int(sample_rate_hz or 0))+ usable = len(pcm) - (len(pcm) % 2)+ if usable <= 0 or rate <= 0:+ return++ samples = array("h")+ samples.frombytes(pcm[:usable])+ if sys.byteorder != "little": # pragma: no cover - uncommon host+ samples.byteswap()+ count = len(samples)+ if not count:+ return++ self._sample_rate_hz = rate+ self._sample_count += count+ self._sum_squares += sum(int(value) * int(value) for value in samples)+ self._clipped_samples += sum(+ 1 for value in samples if abs(int(value)) >= self._CLIP_LEVEL+ )++ stamp = max(0, int(timestamp_ns or 0))+ duration_ns = round(count * 1_000_000_000 / rate)+ if stamp and self._previous_timestamp_ns and self._previous_duration_ns:+ interval_ns = stamp - self._previous_timestamp_ns+ missing_ns = interval_ns - self._previous_duration_ns+ # PortAudio callback jitter is ordinary. One missing 32 ms frame is+ # not: a 20 ms / 75% grace distinguishes the two without depending+ # on the configured callback block size.+ grace_ns = max(20_000_000, round(self._previous_duration_ns * 0.75))+ if missing_ns > grace_ns:+ self._dropout_count += 1+ self._dropout_duration_ns += missing_ns+ if stamp:+ self._previous_timestamp_ns = stamp+ self._previous_duration_ns = duration_ns++ def snapshot(self, *, reported_dropouts: int = 0) -> AudioQualityMetrics:+ """Return immutable metrics, including capture-queue drops when exposed."""+ rms = (+ math.sqrt(self._sum_squares / self._sample_count) / 32_768.0+ if self._sample_count+ else 0.0+ )+ clipping = (+ self._clipped_samples / self._sample_count if self._sample_count else 0.0+ )+ return AudioQualityMetrics(+ sample_rate_hz=self._sample_rate_hz,+ rms=rms,+ clipping_ratio=clipping,+ dropout_count=max(self._dropout_count, max(0, int(reported_dropouts or 0))),+ dropout_duration_ms=max(0, round(self._dropout_duration_ns / 1_000_000)),+ )+++def assess_desktop_audio_preprocessing(+ *, echo_cancellation_requested: bool+) -> AudioPreprocessingDecision:+ """Return the capability-tested verdict for the current raw capture path.++ No optional native module is imported here: base/headless installs must+ remain importable, and none of the installed capture APIs advertises these+ three processing capabilities. The distinction between ``off`` and+ ``unavailable`` makes the existing echo-cancellation setting observable+ without claiming it changes the samples (AP-31).+ """+ return AudioPreprocessingDecision(+ noise_suppression="unavailable",+ automatic_gain_control="unavailable",+ acoustic_echo_cancellation=(+ "unavailable" if echo_cancellation_requested else "off"+ ),+ )+++def prepare_dictation_pcm(+ pcm: bytes, *, echo_cancellation_requested: bool+) -> tuple[bytes, AudioPreprocessingDecision]:+ """Return safe PCM plus its preprocessing decision.++ The byte-for-byte return is intentional. A future processor must replace+ this only behind an actual capability probe and quality regression corpus.+ """+ decision = assess_desktop_audio_preprocessing(+ echo_cancellation_requested=echo_cancellation_requested+ )+ return pcm, decision+++__all__ = [+ "AudioPreprocessingDecision",+ "AudioQualityAccumulator",+ "AudioQualityMetrics",+ "assess_desktop_audio_preprocessing",+ "prepare_dictation_pcm",+]diff --git a/jarvis/dictation/history.py b/jarvis/dictation/history.pyindex f51363ee2d..52a470ba65 100644--- a/jarvis/dictation/history.py+++ b/jarvis/dictation/history.py@@ -119,6 +119,27 @@ class DictationEntry:"""from jarvis.dictation.audio import audio_exists+ public_metadata = {+ key: self.metadata[key]+ for key in (+ "polish_status",+ "polish_provider",+ "polish_latency_ms",+ "stt_providers",+ "stt_models",+ "detected_languages",+ "stt_latency_ms",+ "stt_calls",+ "stt_errors",+ "stt_audit",+ "audio_sample_rate_hz",+ "audio_rms",+ "audio_clipping_ratio",+ "audio_dropouts",+ "audio_dropout_ms",+ )+ if key in self.metadata+ }return {"id": self.id,"created_at": self.created_at,@@ -134,6 +155,7 @@ class DictationEntry:"discarded": self.discarded,"audio_available": audio_exists(self.audio_path),"error": self.error,+ **public_metadata,}@@ -300,9 +322,9 @@ class DictationHistory:The result was a generative pass that could rewrite a user's words whileleaving no record anywhere of whether it had run, which provideranswered, or which guard fired — the one question a bug report about- wrong words has to be able to answer. ``metadata`` is deliberately kept- out of :meth:`DictationEntry.to_dict`: it is diagnostic detail for the- sidecar, not part of the API shape.+ wrong words has to be able to answer. :meth:`DictationEntry.to_dict`+ exposes only its explicit safe-key allowlist; arbitrary metadata stays+ in the local sidecar and can never drift into an API response."""from jarvis.dictation.outcomes import is_recoverablediff --git a/jarvis/dictation/merge.py b/jarvis/dictation/merge.pynew file mode 100644index 0000000000..d775ec2d0c--- /dev/null+++ b/jarvis/dictation/merge.py@@ -0,0 +1,242 @@+"""Joining window transcripts back into one text, without the seam.++Why the windows overlap at all+------------------------------+A long dictation cannot be uploaded as one file, and cutting it into pieces at+exact clock positions cuts words in half. The final transcription therefore+cuts at the quietest point near the nominal length AND lets consecutive windows+share a second or two of audio, so a word that straddles a boundary is spoken+in full inside at least one window.++That guarantee is bought with a duplicate: the shared audio is transcribed+twice, so a naive join reads "the final version the final version is ready".+Removing the duplicate is this module's whole job.++Why it is not a string comparison+---------------------------------+The two transcriptions of the same audio are rarely byte-identical. The second+window heard the words with different context, so it may capitalise+differently, punctuate differently, or spell a number as a word. Matching+therefore happens on a NORMALISED view — case-folded, punctuation removed,+Unicode-composed — while what gets kept is the original text, untouched.++Why it must not assume spaces+-----------------------------+Chinese, Japanese, Thai, Lao, Khmer and Burmese are written without spaces+between words, so a token-based overlap search finds nothing there and a+token-based join inserts spaces a reader of those scripts would call wrong. The+search falls back to characters, and the join asks the two boundary characters+whether a space belongs between them. No language is the default one+(CLAUDE.md §1).++Pure functions over strings: no model, no I/O, no configuration.+"""++from __future__ import annotations++import re+import unicodedata+from collections.abc import Sequence++#: Longest overlap the search will consider, in words. A window overlap is one+#: or two seconds of speech — roughly two to six words — so this is generous by+#: a wide margin while keeping the search cheap and stopping a coincidental+#: repetition far from the seam from being mistaken for one.+MAX_OVERLAP_WORDS = 40++#: The same bound for the character-level search used on space-free scripts.+#: Two seconds of Mandarin is on the order of ten characters.+MAX_OVERLAP_CHARS = 80++#: Below this, an overlap match is more likely to be a coincidence ("und",+#: "the") than the seam. One matching word is not evidence; two are, because+#: the words on either side of a seam come from the same audio.+MIN_OVERLAP_WORDS = 2++#: Same idea for characters — a single shared character means nothing.+MIN_OVERLAP_CHARS = 2++_PUNCTUATION = re.compile(r"[^\w\s]", flags=re.UNICODE)+_WHITESPACE = re.compile(r"\s+", flags=re.UNICODE)+++def _normalize(text: str) -> str:+ """The comparison view: same words, none of the presentation.++ NFKC first so a composed and a decomposed umlaut compare equal — the same+ normalisation the transcript filter applies — then case folding and+ punctuation removal, because the second reading of a seam routinely+ capitalises or punctuates it differently.+ """+ folded = unicodedata.normalize("NFKC", str(text or "")).casefold()+ return _WHITESPACE.sub(" ", _PUNCTUATION.sub(" ", folded)).strip()+++#: Unicode blocks written WITHOUT spaces between words. Korean is deliberately+#: absent: Hangul is written with spaces, so treating it as space-free would+#: run its words together.+_SPACE_FREE_RANGES: tuple[tuple[int, int], ...] = (+ (0x2E80, 0x2FFF), # CJK radicals, Kangxi+ (0x3040, 0x30FF), # Hiragana, Katakana+ (0x3400, 0x4DBF), # CJK Extension A+ (0x4E00, 0x9FFF), # CJK Unified Ideographs+ (0xF900, 0xFAFF), # CJK Compatibility Ideographs+ (0xFF66, 0xFF9F), # Halfwidth Katakana+ (0x0E00, 0x0E7F), # Thai+ (0x0E80, 0x0EFF), # Lao+ (0x1000, 0x109F), # Myanmar+ (0x1780, 0x17FF), # Khmer+)+++def _is_space_free(char: str) -> bool:+ """Whether ``char`` belongs to a script that writes without word spaces."""+ if not char:+ return False+ code = ord(char)+ return any(low <= code <= high for low, high in _SPACE_FREE_RANGES)+++def _join_boundary(left: str, right: str) -> str:+ """``left`` and ``right`` joined the way their scripts are written."""+ if not left:+ return right+ if not right:+ return left+ if _is_space_free(left[-1]) and _is_space_free(right[0]):+ return left + right+ return f"{left} {right}"+++def _word_overlap(left_words: list[str], right_words: list[str]) -> int:+ """How many trailing words of ``left`` repeat as leading words of ``right``.++ The LARGEST match wins: a one-second overlap can repeat several words, and+ stopping at the first (shortest) match would leave most of the duplicate in+ place.+ """+ limit = min(len(left_words), len(right_words), MAX_OVERLAP_WORDS)+ for size in range(limit, MIN_OVERLAP_WORDS - 1, -1):+ if left_words[-size:] == right_words[:size]:+ return size+ return 0+++def _char_overlap(left: str, right: str) -> int:+ """The same search on characters, for scripts written without spaces."""+ limit = min(len(left), len(right), MAX_OVERLAP_CHARS)+ for size in range(limit, MIN_OVERLAP_CHARS - 1, -1):+ if left[-size:] == right[:size]:+ return size+ return 0+++def _drop_leading_words(text: str, count: int) -> str:+ """``text`` without its first ``count`` NORMALISED words.++ Walks the ORIGINAL string rather than re-joining normalised tokens, so the+ kept remainder keeps its own punctuation and capitalisation — the point of+ normalising only for comparison.+ """+ if count <= 0:+ return text+ seen = 0+ index = 0+ length = len(text)+ while index < length and seen < count:+ while index < length and text[index].isspace():+ index += 1+ start = index+ while index < length and not text[index].isspace():+ index += 1+ if index > start and _normalize(text[start:index]):+ # A run of pure punctuation is not a word; the normalised token+ # list did not count it either, so it must not consume a step.+ seen += 1+ return text[index:].lstrip()+++def merge_transcripts(parts: Sequence[str]) -> str:+ """One text from consecutive, overlapping window transcripts.++ Each part is appended after the words it repeats from the accumulated text+ have been removed. Parts that are empty (a window of silence) are skipped+ without breaking the chain — the NEXT part is still matched against+ everything kept so far, so one silent window between two speaking ones+ cannot smuggle a duplicate through.++ Never raises and never drops a part it cannot match: an unmatched part is+ appended whole, because a duplicated phrase is a blemish while a missing+ one is lost speech.+ """+ merged = ""+ merged_words: list[str] = []+ for raw in parts:+ piece = str(raw or "").strip()+ if not piece:+ continue+ if not merged:+ merged = piece+ merged_words = _normalize(piece).split()+ continue++ piece_words = _normalize(piece).split()+ overlap = _word_overlap(merged_words, piece_words)+ if overlap:+ kept = _drop_leading_words(piece, overlap)+ if kept:+ merged = _join_boundary(merged, kept)+ merged_words = _normalize(merged).split()+ # A window whose transcript was ENTIRELY a repetition adds nothing;+ # dropping it is the correct outcome, not a lost window.+ continue++ # No word-level seam. Either the scripts write without spaces, or the+ # two readings of the seam disagree on every word in it.+ left_norm = _normalize(merged)+ right_norm = _normalize(piece)+ chars = (+ _char_overlap(left_norm, right_norm)+ if _is_space_free(left_norm[-1:]) or _is_space_free(right_norm[:1])+ else 0+ )+ if chars:+ # Character offsets are taken on the normalised view, and the+ # original may differ in length; scanning forward from the start+ # keeps the two in step without rebuilding the string.+ kept = _drop_leading_chars(piece, chars)+ if kept:+ merged = _join_boundary(merged, kept)+ merged_words = _normalize(merged).split()+ continue++ merged = _join_boundary(merged, piece)+ merged_words = _normalize(merged).split()+ return merged.strip()+++def _drop_leading_chars(text: str, count: int) -> str:+ """``text`` without the first ``count`` characters OF ITS NORMALISED view.++ The original and the normalised string do not line up character for+ character (punctuation disappears, NFKC can merge a pair), so this consumes+ the original one character at a time and stops when the normalised budget+ is spent.+ """+ if count <= 0:+ return text+ spent = 0+ index = 0+ while index < len(text) and spent < count:+ spent += len(_normalize(text[index]))+ index += 1+ return text[index:].lstrip()+++__all__ = [+ "MAX_OVERLAP_CHARS",+ "MAX_OVERLAP_WORDS",+ "MIN_OVERLAP_CHARS",+ "MIN_OVERLAP_WORDS",+ "merge_transcripts",+]diff --git a/jarvis/dictation/segment.py b/jarvis/dictation/segment.pyindex 95b88335ae..a573256218 100644--- a/jarvis/dictation/segment.py+++ b/jarvis/dictation/segment.py@@ -103,6 +103,80 @@ def quietest_cut(return _align(min(limit, best_centre * BYTES_PER_SAMPLE))+#: Shortest window the final pass will emit on its own. A sliver of audio is+#: the case a recognizer answers with a hallucinated subtitle credit, and it+#: costs a whole request to be told so.+_MIN_WINDOW_S = 1.0+++def quality_windows(+ pcm: bytes,+ *,+ window_bytes: int,+ overlap_bytes: int = 0,+ bytes_per_second: int = 16_000 * BYTES_PER_SAMPLE,+) -> list[tuple[int, int]]:+ """Byte ranges covering ALL of ``pcm``, overlapping and cut at pauses.++ The shape the FINAL transcription uses, and it differs from the live+ segmentation above in both of its properties:++ * **Long windows.** A recognizer detects the spoken language from the audio+ it is handed. Four seconds is not enough to be sure, and an unsure model+ does not merely mislabel — it TRANSLATES. Twenty to thirty seconds is+ long enough that detection is reliable and short enough to stay inside+ every provider's upload limit.+ * **They overlap.** Consecutive windows share ``overlap_bytes`` of audio,+ so a word straddling a boundary is spoken in full inside at least one of+ them. The duplicate that buys is removed from the TEXT afterwards+ (:func:`jarvis.dictation.merge.merge_transcripts`) — which is possible,+ while recovering a word that was cut in half is not.++ Each window still ends at the quietest point near its nominal length, so+ the seam usually lands in a pause and the overlap has little to repair.++ Always makes progress: a pathological ``overlap_bytes`` (larger than the+ window, negative, absurd) cannot produce a window that starts where the+ previous one did. Returns ``[]`` for empty input.+ """+ total = len(pcm)+ if total <= 0 or window_bytes <= 0:+ return []+ window = _align(window_bytes)+ # More than half a window of overlap can never improve a seam enough to+ # justify re-reading most of the same audio. More importantly, clamping to+ # ``window - one sample`` technically made progress but could turn a bad+ # 5s/5s configuration into millions of two-byte windows. Half a window is+ # still far above the recommended 1--2 seconds and gives a hard O(n) bound.+ overlap = max(0, min(_align(overlap_bytes), window // 2))+ min_window = int(_MIN_WINDOW_S * bytes_per_second)++ ranges: list[tuple[int, int]] = []+ start = 0+ while start < total:+ remaining = total - start+ if remaining <= window:+ ranges.append((start, total))+ break+ cut = quietest_cut(pcm[start:], window, bytes_per_second)+ if cut < min_window:+ # The scan found its quiet spot too early to be a useful window —+ # take the nominal length instead. The overlap is what protects the+ # word this cut may land inside.+ cut = window+ end = _align(min(total, start + cut))+ if end <= start: # pragma: no cover — _align keeps this unreachable+ end = min(total, start + window)+ ranges.append((start, end))+ # Step back by the overlap, but never to (or behind) this window's own+ # start: that would transcribe the same audio forever.+ # A pause search may cut as early as 60% of the nominal window. Keep a+ # half-window minimum stride even then: otherwise a legal 50% overlap+ # plus the earliest cut advances by only 10% and multiplies requests.+ start = max(end - overlap, start + window // 2)+ return ranges++#: Below these an int16 microphone signal cannot be carrying speech on ANY#: gain setting worth calling working — this is room tone, a fan, a desk bump.#: ~1.2 % of full scale peak. Deliberately far under the quietest usable speech@@ -174,6 +248,7 @@ def is_silent_segment(pcm: bytes, *, session_peak: float = 0.0) -> bool:__all__ = ["BYTES_PER_SAMPLE","is_silent_segment",+ "quality_windows","quietest_cut","segment_energy",]diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.pyindex 54c2411793..32dc897458 100644--- a/jarvis/plugins/stt/fwhisper.py+++ b/jarvis/plugins/stt/fwhisper.py@@ -531,6 +531,11 @@ class FasterWhisperProvider:"""True when the model is constructed AND primed (safe to poll)."""return self._warm+ @property+ def last_used_model(self) -> str:+ """Effective local checkpoint used for transcription telemetry."""+ return self._model_name+@propertydef bias_prompt(self) -> str | None:"""The ``initial_prompt`` this instance primes the decoder with.diff --git a/jarvis/plugins/stt/gemini_api.py b/jarvis/plugins/stt/gemini_api.pyindex b8740e3c59..3bed6d6a6a 100644--- a/jarvis/plugins/stt/gemini_api.py+++ b/jarvis/plugins/stt/gemini_api.py@@ -141,6 +141,7 @@ class GeminiSTT:# triggers a config load on the boot critical path (AP-26).self._api_key = (api_key or "").strip() or Noneself._model = model or DEFAULT_MODEL+ self._last_used_model = ""self._language = language if language and language != "auto" else None# A bias/vocabulary hint (proper nouns). Appended to the instruction so# the model favours those spellings; never treated as required content.@@ -156,6 +157,11 @@ class GeminiSTT:# Public API (STTProvider contract + pipeline compat shims)# ------------------------------------------------------------------+ @property+ def last_used_model(self) -> str:+ """Effective model that produced the latest successful transcript."""+ return self._last_used_model+async def transcribe(self, audio: AsyncIterator[Any]) -> Transcript:"""Collect audio chunks, upload once, return a final Transcript."""pcm_pieces: list[bytes] = []@@ -353,9 +359,11 @@ class GeminiSTT:if model != DEFAULT_MODEL and is_model_rejection(str(exc), model):log_model_fallback("Gemini", model, DEFAULT_MODEL, str(exc))try:- return _response_to_transcript(+ transcript = _response_to_transcript(await _generate(DEFAULT_MODEL), language)+ self._last_used_model = DEFAULT_MODEL+ return transcriptexcept Exception as retry_exc: # noqa: BLE001 — classify, never leakfailure = retry_exc@@ -376,7 +384,9 @@ class GeminiSTT:status=status,headers=getattr(getattr(failure, "response", None), "headers", None),) from failure- return _response_to_transcript(response, language)+ transcript = _response_to_transcript(response, language)+ self._last_used_model = model+ return transcript# ----------------------------------------------------------------------diff --git a/jarvis/plugins/stt/groq_api.py b/jarvis/plugins/stt/groq_api.pyindex b37c56f578..635e8c01cb 100644--- a/jarvis/plugins/stt/groq_api.py+++ b/jarvis/plugins/stt/groq_api.py@@ -112,6 +112,7 @@ class GroqWhisperAPI:or _read_keyring_secret("personal-jarvis", "groq_api_key"))self._model = model+ self._last_used_model = ""self._endpoint = endpointself._language = language if language and language != "auto" else None# Whisper ``prompt`` biases the token distribution toward the words in@@ -130,6 +131,11 @@ class GroqWhisperAPI:# Public API (STTProvider contract)# ------------------------------------------------------------------+ @property+ def last_used_model(self) -> str:+ """Effective model that produced the latest successful transcript."""+ return self._last_used_model+async def transcribe(self, audio: AsyncIterator[Any]) -> Transcript:"""Collect audio chunks, upload, return a final Transcript."""pcm_pieces: list[bytes] = []@@ -300,10 +306,14 @@ class GroqWhisperAPI:# classifiable shape, so there is nothing to gain and a purity# contract to lose. Do not "unify" this line.response.raise_for_status()- return _payload_to_transcript(response.json())+ transcript = _payload_to_transcript(response.json())+ self._last_used_model = model+ return transcriptresponse.raise_for_status()- return _payload_to_transcript(response.json())+ transcript = _payload_to_transcript(response.json())+ self._last_used_model = model+ return transcript# ----------------------------------------------------------------------diff --git a/jarvis/plugins/stt/openai_api.py b/jarvis/plugins/stt/openai_api.pyindex 4a285131e5..37e7cdee3e 100644--- a/jarvis/plugins/stt/openai_api.py+++ b/jarvis/plugins/stt/openai_api.py@@ -152,6 +152,7 @@ class OpenAIWhisperAPI:self._api_key = api_key or Noneself._api_key_is_explicit = bool(api_key)self._model = model or DEFAULT_MODEL+ self._last_used_model = ""self._base_url = base_url or Noneself._language = language if language and language != "auto" else None# Whisper ``prompt`` biases the token distribution toward the words in@@ -172,6 +173,11 @@ class OpenAIWhisperAPI:# Public API (STTProvider contract + pipeline compat shims)# ------------------------------------------------------------------+ @property+ def last_used_model(self) -> str:+ """Effective model that produced the latest successful transcript."""+ return self._last_used_model+async def transcribe(self, audio: AsyncIterator[Any]) -> Transcript:"""Collect audio chunks, upload once, return a final Transcript."""pcm_pieces: list[bytes] = []@@ -378,7 +384,9 @@ class OpenAIWhisperAPI:) from excif response.status_code < 400:- return _payload_to_transcript(response.json())+ transcript = _payload_to_transcript(response.json())+ self._last_used_model = model+ return transcriptif response.status_code != 400:raise _http_error_to_runtime(response)diff --git a/jarvis/plugins/stt/openrouter_stt.py b/jarvis/plugins/stt/openrouter_stt.pyindex 55f6962d49..be8d130fbf 100644--- a/jarvis/plugins/stt/openrouter_stt.py+++ b/jarvis/plugins/stt/openrouter_stt.py@@ -69,6 +69,11 @@ DEFAULT_BASE_URL = "https://openrouter.ai/api/v1"# in the model dropdown; the picker only offers transcription-capable models.DEFAULT_MODEL = "openai/whisper-large-v3"+# OpenRouter exposes vocabulary priming through provider-specific passthrough+# options. Keep the same conservative ceiling as the direct Whisper adapters so+# one dictionary cannot turn a transcription into a request-size failure.+_MAX_PROMPT_CHARS = 1000+#: The per-call ``language`` value that REQUESTS detection instead of a pinned#: language. Spelled out per plugin because plugins may not import ``jarvis.*``.AUTO_LANGUAGE = "auto"@@ -162,15 +167,15 @@ class OpenRouterSTT:self._api_key = api_key or Noneself._api_key_is_explicit = bool(api_key)self._model = model or DEFAULT_MODEL+ self._last_used_model = ""+ self._last_usage_cost_usd: float | None = Noneself._base_url = base_url or Noneself._language = language if language and language != "auto" else None- # ``prompt`` (bias vocabulary) is accepted for STT-factory kwarg- # compatibility but NOT forwarded: the OpenRouter transcription endpoint- # exposes no documented bias-prompt parameter, and sending an- # unsupported field risks a hard 400 that silences the whole turn. It is- # stored only so a future API revision could opt in without a signature- # change.- self._prompt = (prompt or "").strip() or None+ # The gateway exposes bias through provider-specific passthrough rather+ # than a top-level field. Only the matched upstream receives it, and the+ # request-shape downgrade below removes it when that model rejects it.+ cleaned = (prompt or "").strip()+ self._prompt = cleaned[:_MAX_PROMPT_CHARS] if cleaned else Noneself._temperature = temperatureself._timeout_s = timeout_sself._client = http_client@@ -182,6 +187,16 @@ class OpenRouterSTT:# Public API (STTProvider contract + pipeline compat shims)# ------------------------------------------------------------------+ @property+ def last_used_model(self) -> str:+ """Effective model that produced the latest successful transcript."""+ return self._last_used_model++ @property+ def last_usage_cost_usd(self) -> float | None:+ """Billed cost reported for the latest successful gateway response."""+ return self._last_usage_cost_usd+async def transcribe(self, audio: AsyncIterator[Any]) -> Transcript:"""Collect audio chunks, upload once, return a final Transcript."""pcm_pieces: list[bytes] = []@@ -311,6 +326,10 @@ class OpenRouterSTT:"""import base64+ # Never let a previous successful request's cost leak into a failed+ # evaluation sample. The harness reads this only after the call returns.+ self._last_usage_cost_usd = None+url = self._ensure_endpoint()encoded = base64.b64encode(wav_bytes).decode("ascii")headers = {@@ -343,6 +362,10 @@ class OpenRouterSTT:body["language"] = languageif self._temperature is not None and shape.temperature:body["temperature"] = float(self._temperature)+ if self._prompt and shape.prompt:+ body["provider"] = {+ "options": {"groq": {"prompt": self._prompt}}+ }try:response = await client.post(url, headers=headers, json=body)@@ -352,7 +375,11 @@ class OpenRouterSTT:) from excif response.status_code < 400:- return _payload_to_transcript(response.json())+ payload = response.json()+ transcript = _payload_to_transcript(payload)+ self._last_used_model = model+ self._last_usage_cost_usd = _payload_cost_usd(payload)+ return transcriptif response.status_code != 400:raise _http_error_to_runtime(response)@@ -517,6 +544,18 @@ def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:)+def _payload_cost_usd(payload: dict[str, Any]) -> float | None:+ """Return OpenRouter's billed USD amount when the response carries one."""+ usage = payload.get("usage")+ if not isinstance(usage, dict):+ return None+ try:+ value = float(usage.get("cost"))+ except (TypeError, ValueError): # optional telemetry: malformed means absent+ return None+ return value if value >= 0.0 else None++__all__ = ["OpenRouterSTT","Transcript",diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 43a1428082..6bca12f90b 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -2669,6 +2669,101 @@ class SpeechPipeline:self._ack_pcm = b""self._task_ack_pcm.clear()+ def set_stt_provider(self, provider: str, *, model: str | None = None) -> bool:+ """Live-apply an utterance STT provider without restarting the app.++ The wake recognizer is intentionally left alone: it is a local,+ latency-sensitive detector with a separate lifecycle. Voice turns and+ dictation use the newly built provider from the next transcription.+ A dictation already in flight keeps its existing local reference and+ finishes normally, which avoids reaching into a native inference+ engine while it is running (AP-24).++ The new provider is fully constructed before any live reference or+ configuration value is changed. A failed build therefore leaves the+ current provider usable and returns ``False`` to the REST route.+ """+ normalized = str(provider or "").strip()+ cfg_stt = getattr(getattr(self, "_config", None), "stt", None)+ if not normalized or cfg_stt is None:+ return False++ updates: dict[str, Any] = {"provider": normalized}+ if model is not None:+ updates["model"] = model+ try:+ candidate = cfg_stt.model_copy(update=updates)+ except AttributeError:+ # Lightweight test doubles may not be Pydantic models. Preserve+ # their remaining attributes through a read-only overlay.+ class _CandidateConfig:+ def __getattr__(_self, name: str) -> Any:+ if name in updates:+ return updates[name]+ return getattr(cfg_stt, name)++ candidate = _CandidateConfig()++ try:+ from jarvis.plugins.stt import (+ build_stt_from_config,+ provider_runs_on_device,+ )++ rebuilt = build_stt_from_config(candidate)+ actual = str(getattr(rebuilt, "name", "") or "").strip()+ if actual and actual != normalized:+ log.error(+ "STT live switch resolved %s instead of requested %s; "+ "keeping the current provider.",+ actual,+ normalized,+ )+ return False++ if not provider_runs_on_device(normalized):+ from jarvis.speech.stt_fallback import wrap_stt_with_fallback++ rebuilt = wrap_stt_with_fallback(rebuilt, candidate)++ from jarvis.speech.stt_dictionary import wrap_stt_with_dictionary++ rebuilt = wrap_stt_with_dictionary(rebuilt)+ except Exception as exc: # noqa: BLE001 — preserve the working provider+ log.error(+ "STT live switch to %s failed; keeping the current provider: %s",+ normalized,+ exc,+ exc_info=True,+ )+ return False++ previous = getattr(self, "_utterance_stt", None)+ self._utterance_stt = rebuilt+ # A lightweight/cloud-first pipeline has no local preview recognizer,+ # so its preview must follow the selected provider. A heavy wake path+ # keeps its dedicated local probe.+ if getattr(self, "_stt", None) is None or getattr(+ self, "_probe_stt", None+ ) is previous:+ self._probe_stt = rebuilt+ try:+ cfg_stt.provider = normalized+ if model is not None:+ cfg_stt.model = model+ except Exception as exc: # noqa: BLE001 — runtime cut-over already succeeded+ log.debug("In-memory STT config update skipped: %s", exc)++ # Dictation owns a prompt-free instance and a separate fallback chain;+ # both must be rebuilt from the new provider on the next key press.+ self._reset_dictation_stt()+ log.info(+ "STT live switch applied: %s -> %s (dictation cache invalidated).",+ type(previous).__name__ if previous is not None else "none",+ normalized,+ )+ return True+def set_stt_language(self, language: str) -> bool:"""Live-apply a new recognition language. Returns True when it took.@@ -9155,6 +9250,43 @@ class SpeechPipeline:# 16 kHz mono int16 -> 32000 bytes per second.bytes_per_second = 16_000 * 2segment_bytes = int(segment_seconds * bytes_per_second)+ # The FINAL pass over the whole recording. Short segments answer "what+ # is on screen while I speak"; this answers "what did I say", and they+ # are not the same question. A recognizer handed eight seconds is not+ # sure which language it is hearing, and an unsure model does not+ # mislabel — it TRANSLATES, which is why one continuous recording used+ # to arrive half in the language spoken and half in English.+ final_quality_pass = bool(getattr(cfg, "final_quality_pass", True))+ final_window_bytes = int(+ float(getattr(cfg, "final_window_seconds", 25.0) or 25.0) * bytes_per_second+ )+ final_overlap_bytes = int(+ float(getattr(cfg, "final_overlap_seconds", 1.5) or 0.0) * bytes_per_second+ )+ # Whether the language may CHANGE inside one dictation. While it may,+ # the final pass asks each long window to detect the language rather+ # than being told one, so a pin steers the cleanup and the polish pass+ # without locking the recognizer (which is what turned a pin into a+ # translation of everything else the speaker said).+ code_switching = bool(getattr(cfg, "code_switching", True))+ # PortAudio gives this lane raw PCM but no portable NS/AGC/AEC controls.+ # Keep the samples byte-identical until a measured backend advertises+ # those capabilities, and make the honest degradation visible in the+ # per-dictation audit. The import is lazy so headless boot stays clean.+ from jarvis.dictation.audio_preprocessing import (+ AudioQualityAccumulator,+ assess_desktop_audio_preprocessing,+ )++ audio_cfg = getattr(getattr(self, "_config", None), "audio", None)+ audio_preprocessing = assess_desktop_audio_preprocessing(+ echo_cancellation_requested=bool(+ getattr(audio_cfg, "echo_cancellation", True)+ ),+ )+ audio_quality = AudioQualityAccumulator()+ capture_reported_dropouts = 0+ capture_restart_count = 0# Sub-0.4s of audio is almost always a near-silence Whisper# hallucination; wait until enough has accumulated before transcribing.min_bytes = int(0.4 * bytes_per_second)@@ -9247,12 +9379,71 @@ class SpeechPipeline:# ``accept_recognition_correction``).contradicting_language = ""contradicting_streak = 0+ # Per-dictation quality telemetry. Ordered-set lists keep the payload+ # compact while preserving a fallback or language-switch sequence.+ stt_providers: list[str] = []+ stt_models: list[str] = []+ detected_languages: list[str] = []+ stt_latency_ms = 0.0+ stt_calls = 0+ final_window_count = 0++ def _append_unique(values: list[str], value: object) -> None:+ text = str(value or "").strip()+ if text and text not in values:+ values.append(text)++ def _language_audit_tag(value: object) -> str:+ raw = str(value or "").strip().lower().replace("_", "-")+ if not raw or raw in ("auto", "unknown", "und"):+ return ""+ normalized = normalize_language_tag(raw)+ if normalized != "unknown":+ return normalized+ # Preserve an ISO-like tag for every language outside the UI's+ # de/en/es phrase set. Telemetry must not collapse the roughly 100+ # recognition languages to "unknown" merely because chat output+ # currently supports three locales.+ return raw.split("-", 1)[0][:32]++ def _record_stt_identity(transcript: Any) -> None:+ provider = (+ getattr(stt, "last_used_provider", "")+ or getattr(stt, "name", "")+ or getattr(stt, "provider_label", "")+ )+ model = (+ getattr(stt, "last_used_model", "")+ or getattr(stt, "_model", "")+ or getattr(stt, "_model_name", "")+ )+ _append_unique(stt_providers, provider)+ _append_unique(stt_models, model)+ _append_unique(+ detected_languages,+ _language_audit_tag(getattr(transcript, "language", "")),+ )+ for segment in getattr(transcript, "segments", ()) or ():+ if isinstance(segment, dict):+ _append_unique(+ detected_languages,+ _language_audit_tag(segment.get("language")),+ )async def _transcribe(pcm: bytes,+ *,+ ask_for: str | None = None,) -> tuple[str, str, bool, BaseException | None]:"""One transcription. ``(text, language, ok, error)``; never raises.+ ``ask_for`` overrides which language the provider is told. Left+ ``None`` it is derived from the pin and the session's own reading,+ which is right for a short segment; the FINAL pass passes ``auto``+ deliberately, because its windows are long enough to detect from+ and a language handed to a recognizer is a language it will+ translate INTO.+Records the failure in ``stt_error`` instead of swallowing it. Alater successful call clears it again — a single flaky segment in anotherwise working dictation is not a failed dictation. The same@@ -9287,15 +9478,18 @@ class SpeechPipeline:# ``stt_failures`` is appended to, never rebound, so it needs no# ``nonlocal`` — the list object itself is the shared state.nonlocal stt_error, stt_error_detail, session_language+ nonlocal stt_calls, stt_latency_msceiling = max(float(getattr(self, "_stt_final_timeout_s", 8.0) or 8.0),(len(pcm) / bytes_per_second)* _DICTATION_TRANSCRIBE_TIMEOUT_PER_AUDIO_S,)- ask_for = resolve_recognition_language(- pinned=dictation_language, session_language=session_language- )+ if ask_for is None:+ ask_for = resolve_recognition_language(+ pinned=dictation_language, session_language=session_language+ )inference_active.set()+ call_started = time.perf_counter()try:try:transcript = await asyncio.wait_for(@@ -9325,6 +9519,8 @@ class SpeechPipeline:log.debug("dictation transcribe failed: %s", stt_error_detail)return "", "", False, excfinally:+ stt_calls += 1+ stt_latency_ms += (time.perf_counter() - call_started) * 1000.0inference_active.clear()stt_error = Nonestt_error_detail = ""@@ -9344,8 +9540,23 @@ class SpeechPipeline:or "").strip()lang = str(getattr(transcript, "language", "") or "")+ _record_stt_identity(transcript)return text, lang, True, None+ def preview_only_engine() -> Any:+ """The on-device engine that may serve the live line, or ``None``.++ ``None`` means a closed segment has to go to the provider — either+ because this host has no local engine (a base or headless install)+ or because the final pass is off, in which case those segments ARE+ the transcript and preview-grade text would not do.+ """+ if not final_quality_pass:+ return None+ from jarvis.dictation.local_preview import local_preview++ return local_preview()+async def _close_finished_segments() -> bool:"""Close every segment the buffer already holds. ``False`` on afailed call, which leaves that segment — and everything after it —@@ -9359,6 +9570,16 @@ class SpeechPipeline:what turned a rate limit into a dictation with most of its wordsmissing: the loop stopped producing text, the upload work stalled theevent loop, and the microphone queue dropped real speech to keep up.++ **What these segments are FOR** depends on the final pass. With it+ on and an on-device engine present, the text produced here only ever+ reaches the live line, so it is transcribed locally and costs no+ quota at all — the delivered words come from the long-window pass+ after the key is released. Without a local engine (a base or+ headless install) the segments go to the provider exactly as before,+ because a growing live line is worth more than the requests it+ spends and because that text is then also the fallback if the final+ pass cannot run."""nonlocal closed_bytes, language, session_peak, skipped_silence_bytesif not segment_bytes:@@ -9369,6 +9590,7 @@ class SpeechPipeline:segment_energy,)+ local_engine = preview_only_engine()while len(buffer) - closed_bytes >= segment_bytes:if stop_event.is_set():return True@@ -9391,7 +9613,19 @@ class SpeechPipeline:closed_bytes += cutskipped_silence_bytes += cutcontinue- text, lang, ok, _exc = await _transcribe(piece)+ if local_engine is not None:+ # Preview-grade and free. A busy engine answers ``None``,+ # which costs this stretch its line on screen and nothing+ # else — the final pass reads the audio regardless.+ local_text = await local_engine.transcribe(+ piece,+ language=(+ None if dictation_language == "auto" else dictation_language+ ),+ )+ text, lang, ok = (local_text or ""), "", True+ else:+ text, lang, ok, _exc = await _transcribe(piece)if stop_event.is_set():return Trueif not ok:@@ -9599,6 +9833,170 @@ class SpeechPipeline:except asyncio.CancelledError:pass+ async def _read_piece(+ piece: bytes, *, ask_for: str | None = None+ ) -> tuple[str, bool]:+ """One piece of audio, retried. ``(text, was_read)``; never raises.++ The retry ladder both final paths share. Unlike a probe tick there+ is no "next time" here — the buffer is gone once the caller+ returns — so a transient failure is worth waiting out, and a+ permanent one is not worth asking about twice.++ ``was_read`` is FALSE only when the piece has had its last chance.+ An empty ``text`` with ``was_read`` true is a genuinely silent+ piece, which is not a loss.+ """+ nonlocal language, session_language+ for attempt in range(_DICTATION_FINAL_ATTEMPTS):+ text, lang, ok, exc = await _transcribe(piece, ask_for=ask_for)+ language = lang or language+ if ok:+ # The first piece to come back also answers "what language+ # is this" for the SHORT-segment path, where the question+ # is otherwise put to four seconds of audio and answered+ # with a translation. It is consulted only when neither a+ # user pin nor the cross-dictation anchor already has, both+ # of which outrank it — and the final long-window pass+ # deliberately does not consult it at all, because a window+ # that long detects better on its own than any carried-over+ # reading can promise.+ if not session_language:+ code = str(lang or "").strip().lower()+ if code and code not in ("auto", "unknown", "und"):+ session_language = code+ return text, True+ # 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",+ )+ return "", False+ if attempt + 1 >= _DICTATION_FINAL_ATTEMPTS:+ break+ # 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,+ max(+ _stt_retry_delay(exc, attempt),+ _DICTATION_FINAL_RETRY_DELAY_S * (2**attempt),+ ),+ )+ log.info(+ "final dictation transcription failed (%s) — retry %d/%d "+ "in %.1fs.",+ stt_error_detail or stt_error or "unknown error",+ attempt + 1,+ _DICTATION_FINAL_ATTEMPTS - 1,+ delay,+ )+ await asyncio.sleep(delay)+ return "", False++ async def _final_quality_text(audio: bytes) -> str:+ """Re-read the WHOLE recording in long, overlapping windows.++ This is the transcript the user is handed, and it is a different+ request from the one the live line makes. Two properties, both of+ them the point:++ * **Long windows.** A recognizer detects the spoken language from+ the audio it is given. Eight seconds is not enough to be sure,+ and an unsure model does not merely mislabel — it TRANSLATES.+ That is why one continuous German recording used to arrive with+ one paragraph verbatim and the next in fluent English.+ * **Auto-detect per window, not a carried-over pin.** With+ ``[dictation].code_switching`` on (the default) nothing tells the+ recognizer which language to expect, so a speaker who switches+ language mid-sentence is transcribed as they spoke rather than+ translated into whichever language the session had decided on.+ A user who turns it off gets their pin handed over outright.++ Overlapping windows mean a word on a boundary is spoken in full+ inside at least one of them; the duplicate that creates is removed+ from the text (``jarvis.dictation.merge``), which is possible,+ while recovering half a word is not.++ Returns ``""`` when nothing could be read — the caller then falls+ back to the incremental text rather than losing the dictation.+ """+ nonlocal session_peak, lost_audio_bytes, final_window_count+ from jarvis.dictation.merge import merge_transcripts+ from jarvis.dictation.segment import (+ is_silent_segment,+ quality_windows,+ segment_energy,+ )++ windows = quality_windows(+ audio,+ window_bytes=final_window_bytes,+ overlap_bytes=final_overlap_bytes,+ bytes_per_second=bytes_per_second,+ )+ if not windows:+ return ""+ final_window_count = len(windows)+ # ``auto`` is passed explicitly rather than omitted: an absent+ # language argument means "no opinion" to a provider, which lands+ # on whatever the recognition language is pinned to — the exact+ # inheritance that used to write German speech in English.+ ask_for = (+ "auto"+ if code_switching or dictation_language == "auto"+ else dictation_language+ )+ parts: list[str] = []+ dead_streak = 0+ for start, end in windows:+ piece = audio[start:end]+ if len(piece) < min_bytes:+ continue+ peak, _rms = segment_energy(piece)+ session_peak = max(session_peak, peak)+ if is_silent_segment(piece, session_peak=session_peak):+ continue+ if dead_streak >= _DICTATION_FINAL_DEAD_PIECES:+ # The provider is not flaky, it is down. Counting the rest+ # as lost is what degrades the outcome, and the degraded+ # outcome is what keeps the audio for a later Restore.+ lost_audio_bytes += len(audio) - start+ log.warning(+ "final dictation transcription abandoned after %d "+ "consecutive failed windows (%s) — %.1fs of audio kept "+ "for a later retry rather than making you wait.",+ dead_streak,+ stt_error_detail or stt_error or "unknown error",+ (len(audio) - start) / bytes_per_second,+ )+ break+ text, was_read = await _read_piece(piece, ask_for=ask_for)+ if was_read:+ dead_streak = 0+ if text:+ parts.append(text)+ else:+ dead_streak += 1+ # Only the audio this window did not SHARE with its+ # neighbour is at risk; the overlap is read by the window+ # after it. Counting the whole window would report a loss+ # the user never experienced.+ lost_audio_bytes += max(0, (end - start) - final_overlap_bytes)+ return merge_transcripts(parts)+async def _finalize_tail(tail: bytes) -> str:"""Transcribe everything still open, in segment-sized pieces.@@ -9614,7 +10012,7 @@ class SpeechPipeline:only postpones a read; here it ends it, and the seconds behind thosebytes are words the user said that nothing will ever transcribe."""- nonlocal language, session_peak, lost_audio_bytes, session_language+ nonlocal session_peak, lost_audio_bytesfrom jarvis.dictation.segment import (is_silent_segment,quietest_cut,@@ -9651,86 +10049,27 @@ class SpeechPipeline:session_peak = max(session_peak, peak)if is_silent_segment(piece, session_peak=session_peak):continue- piece_read = False- for attempt in range(_DICTATION_FINAL_ATTEMPTS):- text, lang, ok, exc = await _transcribe(piece)- language = lang or language- if ok:- if text:- parts.append(text)- # The FIRST piece to come back decides the language for- # the rest of this recording. Without it every piece is- # asked to detect independently, and the answers- # disagree inside one dictation — which is not a- # cosmetic mislabel, because a piece detected wrongly- # comes back TRANSLATED. That is the reported "it keeps- # switching between German and English mid-transcript":- # one paragraph in the language spoken, the next one in- # English, from a single continuous recording.- #- # This piece is a full segment (~8 s) rather than the- # ~4 s the live probe works with, so it is the best- # reading available here — and it is only consulted when- # neither a user pin nor the cross-dictation anchor has- # already answered, both of which outrank it.- if not session_language:- code = str(lang or "").strip().lower()- if code and code not in ("auto", "unknown", "und"):- session_language = code- dead_streak = 0- piece_read = True- 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:- # 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,- max(- _stt_retry_delay(exc, attempt),- _DICTATION_FINAL_RETRY_DELAY_S * (2**attempt),- ),- )- log.info(- "final dictation transcription failed (%s) — "- "retry %d/%d in %.1fs.",- stt_error_detail or stt_error or "unknown error",- attempt + 1,- _DICTATION_FINAL_ATTEMPTS - 1,- delay,- )- await asyncio.sleep(delay)- if not piece_read:- # Both exits from the attempt loop that are not ``ok`` land- # here — the refusal nobody retries and the retry ladder run- # to its end. Either way this piece has had its last chance,- # and the transcript the user is about to be handed is- # missing exactly this much of what they said.+ text, piece_read = await _read_piece(piece)+ if piece_read:+ if text:+ parts.append(text)+ dead_streak = 0+ else:+ # The refusal nobody retries and the retry ladder run to+ # its end both land here. Either way this piece has had its+ # last chance, and the transcript the user is about to be+ # handed is missing exactly this much of what they said.+ dead_streak += 1lost_audio_bytes += len(piece)return " ".join(parts).strip()final_text = ""raw_text = ""+ # Which read produced the delivered words: ``applied`` (the long-window+ # pass), ``failed`` (it produced nothing and the live-segment text was+ # delivered instead), ``off``, or ``empty``. Reported in the telemetry+ # so "the transcript is worse than usual" has an answer.+ final_pass_status = "off" # noqa: S105 - quality status, not a credentialhung_up = False# Set when the RECORDING ended before the user did — a different failure# from a transcription that went wrong, and one that used to be invisible.@@ -9748,6 +10087,15 @@ class SpeechPipeline:async def _drain() -> None:async for chunk in source.stream():+ audio_quality.add_chunk(+ chunk.pcm,+ sample_rate_hz=int(+ getattr(chunk, "sample_rate", 16_000) or 16_000+ ),+ timestamp_ns=int(+ getattr(chunk, "timestamp_ns", 0) or 0+ ),+ )buffer.extend(chunk.pcm)# Feed the live loudness so the bar's equalizer moves# while dictating — same normalized RMS as the VAD and@@ -9811,6 +10159,14 @@ class SpeechPipeline:"dictation input stream ended; finalizing what ""was captured.")+ capture_reported_dropouts = max(+ capture_reported_dropouts,+ int(getattr(source, "dropped_frames", 0) or 0),+ )+ capture_restart_count = max(+ capture_restart_count,+ int(getattr(source, "restart_count", 0) or 0),+ )finally:# Freeze the probe BEFORE tearing anything else down so a# stop edge cannot race one more transcription into flight.@@ -9846,9 +10202,41 @@ class SpeechPipeline:)if not hung_up:- # Finalize ONLY the open tail — every closed segment is done.- tail_text = await _finalize_tail(bytes(buffer[closed_bytes:]))- raw_text = " ".join([*closed_parts, tail_text]).strip()+ if final_quality_pass:+ # Read the WHOLE recording once more, in long overlapping+ # windows. The short segments above answered "what is on+ # screen while I speak"; this answers "what did I say", and+ # a recognizer given twenty-five seconds instead of eight+ # knows which language it is hearing — which is the whole+ # difference between a transcript and a translation.+ quality_text = await _final_quality_text(bytes(buffer))+ if quality_text:+ raw_text = quality_text+ final_pass_status = "applied" # noqa: S105 - status token+ else:+ # Nothing came back. Deliver what the live line already+ # produced rather than nothing — but do NOT run the+ # piecewise pass on top: it would ask the same provider+ # for the same audio a second time and double a wait+ # the user has already paid once. What the failed+ # windows cost is counted as lost audio, which is what+ # degrades the outcome and keeps the recording for a+ # later Restore.+ raw_text = " ".join(closed_parts).strip()+ final_pass_status = "failed" if raw_text else "empty"+ if raw_text:+ log.warning(+ "the final dictation pass produced nothing "+ "(%s); delivering the live-segment text "+ "instead, which is preview quality.",+ stt_error_detail or stt_error or "no detail",+ )+ else:+ # Finalize ONLY the open tail — every closed segment is+ # already transcribed, by the configured provider.+ tail_text = await _finalize_tail(bytes(buffer[closed_bytes:]))+ raw_text = " ".join([*closed_parts, tail_text]).strip()+ final_pass_status = "off" # noqa: S105 - status tokenfinal_text = raw_text# How long the user SPOKE — measured from the audio, not the clock.@@ -9872,6 +10260,9 @@ class SpeechPipeline:# and ``stt_error is None`` — a dictation with a hole in it and# nothing anywhere saying why.lost_reason = stt_failures[-1] if (lost_audio_bytes and stt_failures) else None+ quality_metrics = audio_quality.snapshot(+ reported_dropouts=capture_reported_dropouts+ )finished = Trueresult = await self._finish_dictation(raw_text=raw_text,@@ -9887,6 +10278,24 @@ class SpeechPipeline:stt_error=capture_error or lost_reason or stt_error,lost_audio_s=lost_audio_s,audio=bytes(buffer),+ stt_providers=tuple(stt_providers),+ stt_models=tuple(stt_models),+ detected_languages=tuple(detected_languages),+ stt_latency_ms=round(stt_latency_ms),+ stt_calls=stt_calls,+ stt_errors=tuple(dict.fromkeys(stt_failures)),+ stt_audit=(+ f"final_pass:{final_pass_status}",+ f"final_windows:{final_window_count}",+ f"code_switching:{'on' if code_switching else 'off'}",+ f"capture_restarts:{capture_restart_count}",+ *audio_preprocessing.audit(),+ ),+ audio_sample_rate_hz=quality_metrics.sample_rate_hz,+ audio_rms=quality_metrics.rms,+ audio_clipping_ratio=quality_metrics.clipping_ratio,+ audio_dropouts=quality_metrics.dropout_count,+ audio_dropout_ms=quality_metrics.dropout_duration_ms,)final_text = resultlog.info(@@ -9933,6 +10342,9 @@ class SpeechPipeline:# records a `failed` history row — the worst failure this feature# has used to be its most invisible one.try:+ quality_metrics = audio_quality.snapshot(+ reported_dropouts=capture_reported_dropouts+ )await self._finish_dictation(raw_text="",language=language,@@ -9943,6 +10355,11 @@ class SpeechPipeline:hung_up=False,stt_error=classify_stt_failure(exc),audio=bytes(buffer),+ audio_sample_rate_hz=quality_metrics.sample_rate_hz,+ audio_rms=quality_metrics.rms,+ audio_clipping_ratio=quality_metrics.clipping_ratio,+ audio_dropouts=quality_metrics.dropout_count,+ audio_dropout_ms=quality_metrics.dropout_duration_ms,)except Exception: # noqa: BLE001 — the fallback must not raise eitherlog.debug("dictation failure record failed", exc_info=True)@@ -9967,6 +10384,9 @@ class SpeechPipeline:# reliable.if not getattr(self, "_dictation_completion_published", True):self._dictation_completion_published = True+ quality_metrics = audio_quality.snapshot(+ reported_dropouts=capture_reported_dropouts+ )self._publish_event_soon(DictationCompleted(source_layer="speech.dictation",@@ -9975,6 +10395,11 @@ class SpeechPipeline:# 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,+ audio_sample_rate_hz=quality_metrics.sample_rate_hz,+ audio_rms=quality_metrics.rms,+ audio_clipping_ratio=quality_metrics.clipping_ratio,+ audio_dropouts=quality_metrics.dropout_count,+ audio_dropout_ms=quality_metrics.dropout_duration_ms,))@@ -10079,6 +10504,18 @@ class SpeechPipeline:stt_error: str | None = None,lost_audio_s: float = 0.0,audio: bytes | None = None,+ stt_providers: tuple[str, ...] = (),+ stt_models: tuple[str, ...] = (),+ detected_languages: tuple[str, ...] = (),+ stt_latency_ms: int = 0,+ stt_calls: int = 0,+ stt_errors: tuple[str, ...] = (),+ stt_audit: tuple[str, ...] = (),+ audio_sample_rate_hz: int = 0,+ audio_rms: float = 0.0,+ audio_clipping_ratio: float = 0.0,+ audio_dropouts: int = 0,+ audio_dropout_ms: int = 0,) -> str:"""Clean, deliver and record one finished dictation. Returns the text.@@ -10432,6 +10869,18 @@ class SpeechPipeline:polish_status=polish_status,polish_provider=polish_provider,polish_latency_ms=polish_latency_ms,+ stt_providers=stt_providers,+ stt_models=stt_models,+ detected_languages=detected_languages,+ stt_latency_ms=max(0, int(stt_latency_ms)),+ stt_calls=max(0, int(stt_calls)),+ stt_errors=stt_errors,+ stt_audit=stt_audit,+ audio_sample_rate_hz=max(0, int(audio_sample_rate_hz)),+ audio_rms=max(0.0, float(audio_rms)),+ audio_clipping_ratio=max(0.0, float(audio_clipping_ratio)),+ audio_dropouts=max(0, int(audio_dropouts)),+ audio_dropout_ms=max(0, int(audio_dropout_ms)),))except Exception as exc: # noqa: BLE001@@ -10451,6 +10900,18 @@ class SpeechPipeline:polish_status=polish_status,polish_provider=polish_provider,polish_latency_ms=polish_latency_ms,+ stt_providers=stt_providers,+ stt_models=stt_models,+ detected_languages=detected_languages,+ stt_latency_ms=max(0, int(stt_latency_ms)),+ stt_calls=max(0, int(stt_calls)),+ stt_errors=stt_errors,+ stt_audit=stt_audit,+ audio_sample_rate_hz=max(0, int(audio_sample_rate_hz)),+ audio_rms=max(0.0, float(audio_rms)),+ audio_clipping_ratio=max(0.0, float(audio_clipping_ratio)),+ audio_dropouts=max(0, int(audio_dropouts)),+ audio_dropout_ms=max(0, int(audio_dropout_ms)),)return cleaned@@ -10470,6 +10931,18 @@ class SpeechPipeline:polish_status: str = "",polish_provider: str = "",polish_latency_ms: int = 0,+ stt_providers: tuple[str, ...] = (),+ stt_models: tuple[str, ...] = (),+ detected_languages: tuple[str, ...] = (),+ stt_latency_ms: int = 0,+ stt_calls: int = 0,+ stt_errors: tuple[str, ...] = (),+ stt_audit: tuple[str, ...] = (),+ audio_sample_rate_hz: int = 0,+ audio_rms: float = 0.0,+ audio_clipping_ratio: float = 0.0,+ audio_dropouts: int = 0,+ audio_dropout_ms: int = 0,) -> None:"""Write the history row and, when warranted, the audio sidecar.@@ -10517,6 +10990,18 @@ class SpeechPipeline:"polish_status": polish_status,"polish_provider": polish_provider,"polish_latency_ms": polish_latency_ms,+ "stt_providers": stt_providers,+ "stt_models": stt_models,+ "detected_languages": detected_languages,+ "stt_latency_ms": max(0, int(stt_latency_ms)),+ "stt_calls": max(0, int(stt_calls)),+ "stt_errors": stt_errors,+ "stt_audit": stt_audit,+ "audio_sample_rate_hz": max(0, int(audio_sample_rate_hz)),+ "audio_rms": max(0.0, float(audio_rms)),+ "audio_clipping_ratio": max(0.0, float(audio_clipping_ratio)),+ "audio_dropouts": max(0, int(audio_dropouts)),+ "audio_dropout_ms": max(0, int(audio_dropout_ms)),}try:entry = await asyncio.to_thread(history.add, **fields, **extra)diff --git a/jarvis/speech/stt_eval/__main__.py b/jarvis/speech/stt_eval/__main__.pyindex 4144447d08..6a15e5738c 100644--- a/jarvis/speech/stt_eval/__main__.py+++ b/jarvis/speech/stt_eval/__main__.py@@ -4,7 +4,7 @@ Example (quote contender values in shells where ``|`` is a pipe)::python -m jarvis.speech.stt_eval --corpus data/stt-eval/corpus.jsonl \--contender "current|groq-api|whisper-large-v3-turbo|0.0006667" \- --contender "candidate|openai-api|gpt-4o-transcribe|0.006"+ --contender "candidate|openrouter-stt|openai/gpt-4o-transcribe|0"Prices are explicit inputs, not embedded facts, because providers can changethem independently of a Jarvis release. Reports contain metrics and stable@@ -120,6 +120,7 @@ def _recognizer(provider: Any):text=str(text).strip(),latency_ms=(time.perf_counter() - started) * 1000.0,reported_languages=tuple(languages),+ cost_usd=getattr(provider, "last_usage_cost_usd", None),)return recognize@@ -197,7 +198,7 @@ def main(argv: list[str] | None = None) -> int:out.parent.mkdir(parents=True, exist_ok=True)out.write_text(json.dumps(- {"schema_version": 1, "contenders": [asdict(report) for report in reports]},+ {"schema_version": 2, "contenders": [asdict(report) for report in reports]},ensure_ascii=False,indent=2,),@@ -214,10 +215,15 @@ def main(argv: list[str] | None = None) -> int:if report.repeatability_error_rate is Noneelse f"{report.repeatability_error_rate:.3f}")+ cost = (+ f"measured_cost=${report.measured_cost_usd:.4f}"+ if report.measured_cost_usd is not None+ else f"estimated_cost=${report.estimated_cost_usd:.4f}"+ )print(f"{report.label}: WER={report.wer:.3f}, switch={switch}, "f"repeatability={repeatability}, latency={report.median_latency_ms:.0f} ms, "- f"estimated_cost=${report.estimated_cost_usd:.4f}"+ f"{cost}")print(f"Report written to {out}")return 0diff --git a/jarvis/speech/stt_eval/harness.py b/jarvis/speech/stt_eval/harness.pyindex ac4e144a7c..e6c78ff287 100644--- a/jarvis/speech/stt_eval/harness.py+++ b/jarvis/speech/stt_eval/harness.py@@ -21,6 +21,7 @@ class Recognition:text: strlatency_ms: floatreported_languages: tuple[str, ...] = ()+ cost_usd: float | None = Noneerror: str = ""@@ -44,6 +45,7 @@ class ContenderReport:switch_error_rate: float | Nonerepeatability_error_rate: float | Nonemedian_latency_ms: float+ measured_cost_usd: float | Noneestimated_cost_usd: floatitems: tuple[ItemReport, ...]@@ -75,6 +77,8 @@ async def evaluate_contender(repeats = max(1, int(repeats))item_reports: list[ItemReport] = []all_latencies: list[float] = []+ measured_costs: list[float] = []+ measured_cost_complete = Truetotal_audio_s = 0.0for item in items:pcm, duration_s = read_pcm16(item)@@ -83,6 +87,11 @@ async def evaluate_contender(texts = [answer.text if not answer.error else "" for answer in answers]latencies = [max(0.0, answer.latency_ms) for answer in answers]all_latencies.extend(latencies)+ for answer in answers:+ if answer.error or answer.cost_usd is None:+ measured_cost_complete = False+ else:+ measured_costs.append(max(0.0, float(answer.cost_usd)))wers = [word_error_rate(item.reference, text) for text in texts]switch_rates = [switch_error_rate(item.switch_anchors, text) for text in texts]item_reports.append(@@ -110,6 +119,9 @@ async def evaluate_contender([item.repeatability_error_rate for item in item_reports]),median_latency_ms=statistics.median(all_latencies),+ measured_cost_usd=(+ sum(measured_costs) if measured_cost_complete else None+ ),estimated_cost_usd=(total_audio_s / 60.0) * max(0.0, price_per_minute_usd),items=tuple(item_reports),)diff --git a/jarvis/speech/stt_fallback.py b/jarvis/speech/stt_fallback.pyindex c9fb9657f4..0ba2173d4f 100644--- a/jarvis/speech/stt_fallback.py+++ b/jarvis/speech/stt_fallback.py@@ -124,6 +124,30 @@ class FallbackSTT:"""Which provider produced the most recent transcript."""return self._last_used+ @property+ def last_used_model(self) -> str:+ """Model exposed by the provider that produced the latest transcript.++ Alternates are constructed lazily, so an unused one has no model to+ report. The common attribute spellings cover the cloud plugins and the+ local faster-whisper provider without making a provider id load-bearing.+ """+ name = self._last_used+ if not name:+ return ""+ provider = (+ self._primary+ if name == self._primary_name+ else self._instances.get(name)+ )+ if provider is None:+ return ""+ for attribute in ("last_used_model", "_model", "_model_name"):+ value = getattr(provider, attribute, "")+ if value:+ return str(value)+ return ""+_last_used = ""# ------------------------------------------------------------------diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.pyindex 6ee67c489b..9c5b66d12e 100644--- a/jarvis/ui/web/dictation_routes.py+++ b/jarvis/ui/web/dictation_routes.py@@ -417,6 +417,28 @@ class SettingsBody(BaseModel):max_seconds: float | None = Nonepartial_interval_s: float | None = Nonesegment_seconds: float | None = None+ final_quality_pass: bool | None = Field(+ default=None,+ description=(+ "Re-transcribe the complete recording after release and deliver "+ "that quality pass instead of the short live-preview segments"+ ),+ )+ final_window_seconds: float | None = Field(+ default=None,+ description="Length of each final transcription window (5-60 seconds)",+ )+ final_overlap_seconds: float | None = Field(+ default=None,+ description="Audio shared by adjacent final windows (0-5 seconds)",+ )+ code_switching: bool | None = Field(+ default=None,+ description=(+ "Let the final recognizer detect language from the audio instead "+ "of locking the request to one configured language"+ ),+ )history_enabled: bool | None = Nonehistory_max_entries: int | None = Nonehistory_retention_days: int | None = Nonediff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.tsindex 5bac966eb7..2b01cff02b 100644--- a/jarvis/ui/web/frontend/src/hooks/useDictation.ts+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts@@ -215,6 +215,30 @@ export interface DictationEntry {/** What the pass cost in wall-clock time, for the honest "is this slowing me* down" question. 0 when it never ran. */polish_latency_ms?: number | null;+ /** STT providers that produced text, in first-use order (fallback is visible). */+ stt_providers?: string[];+ /** Requested/effective STT model ids used by successful calls. */+ stt_models?: string[];+ /** Provider-reported language tags across the final windows. */+ detected_languages?: string[];+ /** Aggregate wall-clock time spent in STT for this dictation. */+ stt_latency_ms?: number;+ /** Logical preview/final STT calls; provider-internal shape retries are opaque. */+ stt_calls?: number;+ /** Stable failure reason codes observed during this dictation. */+ stt_errors?: string[];+ /** Machine-readable quality-path decisions; never transcript content. */+ stt_audit?: string[];+ /** Stable PCM rate delivered to STT after capture-side resampling. */+ audio_sample_rate_hz?: number;+ /** Whole-recording normalized RMS (0..1). */+ audio_rms?: number;+ /** Share of PCM16 samples at or immediately below full scale. */+ audio_clipping_ratio?: number;+ /** Capture discontinuities inferred from timestamps / queue overflow. */+ audio_dropouts?: number;+ /** Approximate missing audio across timestamp-detected discontinuities. */+ audio_dropout_ms?: number;}/**@@ -247,6 +271,14 @@ export interface DictationSettings {max_seconds: number;partial_interval_s: number;segment_seconds: number;+ /** Re-read the complete recording after release; live segments stay preview-only. */+ final_quality_pass: boolean;+ /** Length of one final quality window in seconds. */+ final_window_seconds: number;+ /** Overlap between adjacent final windows in seconds. */+ final_overlap_seconds: number;+ /** Auto-detect within the recording instead of sending a hard language lock. */+ code_switching: boolean;history_enabled: boolean;history_max_entries: number;history_retention_days: number;diff --git a/tests/unit/dictation/test_audio_preprocessing.py b/tests/unit/dictation/test_audio_preprocessing.pynew file mode 100644index 0000000000..438298beb3--- /dev/null+++ b/tests/unit/dictation/test_audio_preprocessing.py@@ -0,0 +1,64 @@+"""Capability-first desktop dictation audio preprocessing."""++import struct++import pytest++from jarvis.dictation.audio_preprocessing import (+ AudioQualityAccumulator,+ assess_desktop_audio_preprocessing,+ prepare_dictation_pcm,+)+++def test_unverified_processing_never_changes_the_pcm() -> None:+ pcm = bytes(range(128))+ prepared, decision = prepare_dictation_pcm(+ pcm, echo_cancellation_requested=True+ )++ assert prepared is pcm+ assert decision.pcm_changed is False+ assert decision.audit() == (+ "audio_preprocessing:raw_pcm",+ "noise_suppression:unavailable",+ "automatic_gain_control:unavailable",+ "acoustic_echo_cancellation:unavailable",+ )+++def test_disabled_echo_setting_is_reported_as_off() -> None:+ decision = assess_desktop_audio_preprocessing(+ echo_cancellation_requested=False+ )++ assert decision.acoustic_echo_cancellation == "off"+ assert decision.noise_suppression == "unavailable"+ assert decision.automatic_gain_control == "unavailable"+++def test_quality_accumulator_measures_rate_rms_and_clipping() -> None:+ meter = AudioQualityAccumulator()+ meter.add_chunk(+ struct.pack("<hhhh", 0, 32_767, -32_768, 16_384),+ sample_rate_hz=16_000,+ )++ quality = meter.snapshot()++ assert quality.sample_rate_hz == 16_000+ assert quality.rms == pytest.approx(0.75, abs=0.02)+ assert quality.clipping_ratio == 0.5+ assert quality.dropout_count == 0+++def test_quality_accumulator_detects_timestamp_gaps_and_capture_drops() -> None:+ meter = AudioQualityAccumulator()+ pcm = b"\x00\x01" * 512 # 32 ms at 16 kHz+ meter.add_chunk(pcm, sample_rate_hz=16_000, timestamp_ns=1_000_000_000)+ meter.add_chunk(pcm, sample_rate_hz=16_000, timestamp_ns=1_096_000_000)++ quality = meter.snapshot(reported_dropouts=3)++ assert quality.dropout_count == 3+ assert quality.dropout_duration_ms == 64diff --git a/tests/unit/dictation/test_delivery_and_bar.py b/tests/unit/dictation/test_delivery_and_bar.pyindex e335fc153d..6a06c7b62d 100644--- a/tests/unit/dictation/test_delivery_and_bar.py+++ b/tests/unit/dictation/test_delivery_and_bar.py@@ -46,7 +46,8 @@ def _pipeline(cfg: DictationConfig | None = None, *, insert: InsertResult | Noneasync def test_cleans_then_inserts() -> None:pipe, events = _pipeline()text = await pipe._finish_dictation(- raw_text="Ähm, das ist äh wirklich gut.", # i18n-allow: German fixture under test (§1 list #4)+ # i18n-allow: German fixture under test (§1 list #4)+ raw_text="Ähm, das ist äh wirklich gut.", # i18n-allowlanguage="de",duration_s=3.0,target="insert",@@ -57,9 +58,11 @@ async def test_cleans_then_inserts() -> None:transcript = next(e for e in events if isinstance(e, DictationTranscript))completed = next(e for e in events if isinstance(e, DictationCompleted))assert transcript.is_final is True- assert transcript.text == "Das ist wirklich gut." # i18n-allow: German fixture under test (§1 list #4)+ # i18n-allow: German fixture under test (§1 list #4)+ assert transcript.text == "Das ist wirklich gut." # i18n-allowassert completed.outcome == "inserted"- assert completed.raw_text == "Ähm, das ist äh wirklich gut." # i18n-allow: German fixture under test (§1 list #4)+ # i18n-allow: German fixture under test (§1 list #4)+ assert completed.raw_text == "Ähm, das ist äh wirklich gut." # i18n-allowassert completed.removed_words == 2@@ -513,7 +516,7 @@ def _session_pipeline(stt, cfg: DictationConfig):@pytest.mark.asyncio-async def test_the_pinned_language_reaches_the_provider(+async def test_a_language_pin_does_not_lock_a_code_switching_dictation(monkeypatch: pytest.MonkeyPatch, audio_spy) -> None:import jarvis.speech.pipeline as pipeline_mod@@ -532,6 +535,87 @@ async def test_the_pinned_language_reaches_the_provider(_STT(), DictationConfig(language="es", partial_interval_s=0.0))await pipe._dictation_session()+ assert seen == [{"language": "auto"}]+++async def test_completion_and_history_carry_stt_quality_telemetry(+ monkeypatch: pytest.MonkeyPatch, audio_spy+) -> None:+ import jarvis.speech.pipeline as pipeline_mod++ class _MeasuredSTT:+ name = "openai-api"+ _model = "gpt-4o-transcribe"++ async def transcribe_pcm(self, pcm: bytes, **_kw):+ return SimpleNamespace(+ text="hello 東京 equipo", # i18n-allow: multilingual STT fixture+ language="en-US",+ segments=(+ {"language": "ja-JP"},+ {"language": "es-MX"},+ ),+ )++ monkeypatch.setattr(+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)+ )+ pipe, events = _session_pipeline(+ _MeasuredSTT(), DictationConfig(partial_interval_s=0.0)+ )++ await pipe._dictation_session()++ completed = next(e for e in events if isinstance(e, DictationCompleted))+ assert completed.stt_providers == ("openai-api",)+ assert completed.stt_models == ("gpt-4o-transcribe",)+ assert completed.detected_languages == ("en", "ja", "es")+ assert completed.stt_calls == 1+ assert "final_pass:applied" in completed.stt_audit+ assert "audio_preprocessing:raw_pcm" in completed.stt_audit+ assert "acoustic_echo_cancellation:unavailable" in completed.stt_audit+ assert completed.audio_sample_rate_hz == 16_000+ assert completed.audio_rms == pytest.approx(1 / 128)+ assert completed.audio_clipping_ratio == 0.0+ assert completed.audio_dropouts == 0+ assert completed.audio_dropout_ms == 0+ stored = _FakeHistory.instances[-1].added[0]+ assert stored["stt_providers"] == ("openai-api",)+ assert stored["stt_models"] == ("gpt-4o-transcribe",)+ assert stored["detected_languages"] == ("en", "ja", "es")+ assert stored["audio_sample_rate_hz"] == 16_000+ assert stored["audio_rms"] == pytest.approx(1 / 128)+ assert stored["audio_clipping_ratio"] == 0.0+ assert stored["audio_dropouts"] == 0+ assert stored["audio_dropout_ms"] == 0+++async def test_a_language_pin_reaches_the_provider_when_code_switching_is_off(+ monkeypatch: pytest.MonkeyPatch, audio_spy+) -> None:+ import jarvis.speech.pipeline as pipeline_mod++ seen: list[dict] = []++ class _STT:+ async def transcribe_pcm(self, pcm: bytes, **kw):+ seen.append(kw)+ return SimpleNamespace(text="hola mundo", language="es")++ monkeypatch.setattr(+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)+ )+ pipe, _events = _session_pipeline(+ _STT(),+ DictationConfig(+ language="es",+ code_switching=False,+ partial_interval_s=0.0,+ ),+ )+ await pipe._dictation_session()assert seen == [{"language": "es"}]diff --git a/tests/unit/dictation/test_final_quality_windows.py b/tests/unit/dictation/test_final_quality_windows.pynew file mode 100644index 0000000000..be0da407f6--- /dev/null+++ b/tests/unit/dictation/test_final_quality_windows.py@@ -0,0 +1,83 @@+"""Final dictation windows and their lossless text seam."""++from jarvis.dictation.merge import merge_transcripts+from jarvis.dictation.segment import quality_windows++BYTES_PER_SECOND = 16_000 * 2+++def test_short_recording_is_one_complete_window() -> None:+ pcm = b"x" * (7 * BYTES_PER_SECOND)+ assert quality_windows(+ pcm,+ window_bytes=25 * BYTES_PER_SECOND,+ overlap_bytes=int(1.5 * BYTES_PER_SECOND),+ ) == [(0, len(pcm))]+++def test_long_recording_is_fully_covered_with_overlap() -> None:+ pcm = b"\x00\x01" * (61 * 16_000)+ windows = quality_windows(+ pcm,+ window_bytes=25 * BYTES_PER_SECOND,+ overlap_bytes=int(1.5 * BYTES_PER_SECOND),+ )++ assert windows[0][0] == 0+ assert windows[-1][1] == len(pcm)+ assert all(start < end for start, end in windows)+ pairs = zip(windows, windows[1:], strict=False)+ assert all(next_start < end for (_, end), (next_start, _) in pairs)+ assert all(+ next_start <= end and next_start > start+ for (start, end), (next_start, _) in zip(+ windows, windows[1:], strict=False+ )+ )+++def test_pathological_overlap_still_has_linear_progress() -> None:+ pcm = b"x" * (20 * BYTES_PER_SECOND)+ windows = quality_windows(+ pcm,+ window_bytes=5 * BYTES_PER_SECOND,+ overlap_bytes=60 * BYTES_PER_SECOND,+ )++ assert len(windows) <= 8+ assert all(+ next_start - start >= (5 * BYTES_PER_SECOND) // 2+ for (start, _), (next_start, _) in zip(+ windows, windows[1:], strict=False+ )+ )+++def test_merge_removes_the_largest_normalized_word_overlap() -> None:+ assert merge_transcripts(+ [+ "We deploy the final release tomorrow.",+ "the FINAL release tomorrow, then monitor it.",+ ]+ ) == "We deploy the final release tomorrow. then monitor it."+++def test_merge_preserves_unmatched_code_switching_text() -> None:+ result = merge_transcripts(+ [+ "We deploy the release heute Abend.", # i18n-allow: mixed-language fixture+ "heute Abend. Luego revisamos métricas.", # i18n-allow: mixed-language fixture+ ]+ )+ assert result == (+ "We deploy the release heute Abend. Luego revisamos métricas."+ ) # i18n-allow: mixed-language fixture+++def test_merge_does_not_insert_spaces_into_cjk_text() -> None:+ assert merge_transcripts(+ [+ "今日は東京へ行きます", # i18n-allow: Japanese transcription fixture+ "東京へ行きます明日は大阪です", # i18n-allow: Japanese transcription fixture+ ]+ ) == "今日は東京へ行きます明日は大阪です" # i18n-allow: Japanese fixturediff --git a/tests/unit/dictation/test_segment_and_history.py b/tests/unit/dictation/test_segment_and_history.pyindex 039a1b067b..8f042d0126 100644--- a/tests/unit/dictation/test_segment_and_history.py+++ b/tests/unit/dictation/test_segment_and_history.py@@ -96,7 +96,8 @@ def test_add_stores_raw_and_cleaned(history: DictationHistory) -> None:assert entry is not Nonestored = history.list_all()assert len(stored) == 1- assert stored[0].raw_text == "Ähm das ist gut" # i18n-allow: German fixture under test (§1 list #4)+ # i18n-allow: German fixture under test (§1 list #4)+ assert stored[0].raw_text == "Ähm das ist gut" # i18n-allowassert stored[0].text == "Das ist gut" # i18n-allow: German fixture under test (§1 list #4)assert stored[0].removed_words == 1@@ -300,6 +301,45 @@ def test_public_dict_reports_audio_that_is_actually_on_disk(assert stored.to_dict()["audio_available"] is True+def test_public_dict_exposes_only_safe_quality_telemetry(+ history: DictationHistory,+) -> None:+ entry = history.add(+ raw_text="hello",+ text="hello",+ stt_providers=("openai-api",),+ stt_models=("gpt-4o-transcribe",),+ detected_languages=("en", "ja"),+ stt_latency_ms=123,+ stt_calls=2,+ stt_errors=("rate_limited",),+ stt_audit=("final_pass:applied",),+ audio_sample_rate_hz=16_000,+ audio_rms=0.0125,+ audio_clipping_ratio=0.001,+ audio_dropouts=2,+ audio_dropout_ms=64,+ internal_debug_path="private/path",+ )+ assert entry is not None++ payload = entry.to_dict()++ assert payload["stt_providers"] == ("openai-api",)+ assert payload["stt_models"] == ("gpt-4o-transcribe",)+ assert payload["detected_languages"] == ("en", "ja")+ assert payload["stt_latency_ms"] == 123+ assert payload["stt_calls"] == 2+ assert payload["stt_errors"] == ("rate_limited",)+ assert payload["stt_audit"] == ("final_pass:applied",)+ assert payload["audio_sample_rate_hz"] == 16_000+ assert payload["audio_rms"] == 0.0125+ assert payload["audio_clipping_ratio"] == 0.001+ assert payload["audio_dropouts"] == 2+ assert payload["audio_dropout_ms"] == 64+ assert "internal_debug_path" not in payload++def test_delete_also_removes_the_audio_sidecar(history: DictationHistory, tmp_path: Path) -> None:diff --git a/tests/unit/dictation/test_stt_retry_and_isolation.py b/tests/unit/dictation/test_stt_retry_and_isolation.pyindex 5ee5a2ecec..17966e0351 100644--- a/tests/unit/dictation/test_stt_retry_and_isolation.py+++ b/tests/unit/dictation/test_stt_retry_and_isolation.py@@ -437,6 +437,7 @@ def test_the_dictation_provider_arms_the_cross_family_chain(family sits unused — and the alternates come from the resolver thatguarantees one entry per CREDENTIAL family."""import jarvis.plugins.stt as stt_plugins+ import jarvis.speech.pipeline as pipeline_modimport jarvis.speech.stt_dictionary as dictionaryfrom jarvis.speech.stt_fallback import FallbackSTT@@ -444,8 +445,8 @@ def test_the_dictation_provider_arms_the_cross_family_chain(stt_plugins, "build_stt_from_config", lambda cfg: SimpleNamespace())monkeypatch.setattr(- stt_plugins,- "resolve_keyed_stt_fallback",+ pipeline_mod,+ "_resolve_stt_fallback_chain",lambda *_a, **_k: ("openai-api", "gemini-api"),)# The dictionary wrapper sits ON TOP of the chain and its presence dependsdiff --git a/tests/unit/plugins/stt/test_openrouter_stt.py b/tests/unit/plugins/stt/test_openrouter_stt.pyindex fa92e09c97..c2de162a28 100644--- a/tests/unit/plugins/stt/test_openrouter_stt.py+++ b/tests/unit/plugins/stt/test_openrouter_stt.py@@ -136,6 +136,29 @@ async def test_temperature_is_pinned_to_zero_by_default() -> None:await stt.aclose()assert captured["body"]["temperature"] == 0.0++async def test_bias_prompt_uses_capability_scoped_provider_options() -> None:+ captured: dict[str, dict] = {}++ async def handler(request: httpx.Request) -> httpx.Response:+ captured["body"] = __import__("json").loads(request.content)+ return httpx.Response(200, json=_JSON_OK)++ stt = OpenRouterSTT(+ api_key="k",+ prompt="Nova, PostgreSQL, São Paulo",+ http_client=_mock_client(handler),+ )+ try:+ await stt.transcribe_pcm(_silent_pcm())+ finally:+ await stt.aclose()++ assert captured["body"]["provider"] == {+ "options": {"groq": {"prompt": "Nova, PostgreSQL, São Paulo"}}+ }+# An explicit None is still "say nothing about it" — the escape hatch for a# deployment that wants the backend's own default.stt2 = OpenRouterSTT(@@ -188,6 +211,25 @@ async def test_response_text_is_parsed_into_transcript() -> None:assert result.confidence == 1.0assert result.is_partial is Falseassert result.segments == ()+ assert stt.last_usage_cost_usd == pytest.approx(0.00003)+++async def test_missing_gateway_cost_does_not_reuse_the_previous_request() -> None:+ responses = iter((_JSON_OK, {"text": "second"}))++ async def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=next(responses))++ stt = OpenRouterSTT(api_key="k", http_client=_mock_client(handler))+ try:+ await stt.transcribe_pcm(_silent_pcm())+ assert stt.last_usage_cost_usd == pytest.approx(0.00003)+ await stt.transcribe_pcm(_silent_pcm())+ finally:+ await stt.aclose()++ assert stt.last_usage_cost_usd is None@pytest.mark.asynciodiff --git a/tests/unit/plugins/stt/test_request_capabilities.py b/tests/unit/plugins/stt/test_request_capabilities.pyindex f4c0ffcab2..870d7cdb26 100644--- a/tests/unit/plugins/stt/test_request_capabilities.py+++ b/tests/unit/plugins/stt/test_request_capabilities.py@@ -265,6 +265,7 @@ class TestTheOpenAIShapedPluginsAdapt:assert result.text == "hallo welt"assert models[-1] == "whisper-1"+ assert stt.last_used_model == "whisper-1"@pytest.mark.asyncioasync def test_an_unrelated_400_is_still_an_error(self):@@ -303,6 +304,31 @@ class TestTheOpenAIShapedPluginsAdapt:class TestTheGatewayPluginAdapts:+ @pytest.mark.asyncio+ async def test_a_rejected_bias_prompt_is_dropped_and_the_call_retried(self):+ bodies: list[dict] = []++ async def handler(request: httpx.Request) -> httpx.Response:+ body = json.loads(request.content)+ bodies.append(body)+ if "provider" in body:+ return httpx.Response(+ 400, json={"error": {"message": "prompt is not supported"}}+ )+ return httpx.Response(200, json={"text": "hola mundo"})++ stt = OpenRouterSTT(+ api_key="k", prompt="Nova", http_client=_mock_client(handler)+ )+ try:+ result = await stt.transcribe_pcm(_silent_pcm())+ finally:+ await stt.aclose()++ assert result.text == "hola mundo"+ assert "provider" in bodies[0]+ assert "provider" not in bodies[-1]+@pytest.mark.asyncioasync def test_a_rejected_temperature_is_dropped_and_the_call_retried(self):bodies: list[dict] = []diff --git a/tests/unit/speech/stt_eval/test_harness.py b/tests/unit/speech/stt_eval/test_harness.pyindex a12500ffb1..c3455b2e7d 100644--- a/tests/unit/speech/stt_eval/test_harness.py+++ b/tests/unit/speech/stt_eval/test_harness.py@@ -50,7 +50,7 @@ async def test_harness_measures_quality_latency_cost_and_repeatability(answers = iter(("hello mundo", "hello mundo", "hello world"))async def recognize(_pcm: bytes) -> Recognition:- return Recognition(text=next(answers), latency_ms=120.0)+ return Recognition(text=next(answers), latency_ms=120.0, cost_usd=0.0002)report = await evaluate_contender(recognize,@@ -66,6 +66,7 @@ async def test_harness_measures_quality_latency_cost_and_repeatability(assert report.switch_error_rate == pytest.approx(1 / 3)assert report.repeatability_error_rate == pytest.approx(1 / 4)assert report.median_latency_ms == 120.0+ assert report.measured_cost_usd == pytest.approx(0.0006)assert report.estimated_cost_usd == pytest.approx(0.0006)@@ -87,4 +88,5 @@ async def test_provider_error_counts_as_a_failed_transcript(tmp_path: Path) -> N)assert report.wer == 1.0+ assert report.measured_cost_usd is Noneassert report.items[0].errors == ("rate_limited",)diff --git a/tests/unit/speech/test_dictation_no_audio_dropped.py b/tests/unit/speech/test_dictation_no_audio_dropped.pyindex 8dcd3a592d..ea144ec7a0 100644--- a/tests/unit/speech/test_dictation_no_audio_dropped.py+++ b/tests/unit/speech/test_dictation_no_audio_dropped.py@@ -166,7 +166,11 @@ async def test_a_failed_segment_does_not_delete_its_audio(monkeypatch) -> None:continuing to retry costs the user more than it can possibly return."""stt = _ScriptedSTT(fail_first=2)- cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=0.5)+ cfg = DictationConfig(+ partial_interval_s=0.02,+ segment_seconds=0.5,+ final_quality_pass=False,+ )await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=3)@@ -185,7 +189,11 @@ async def test_a_successful_segment_still_closes(monkeypatch) -> None:"""The gegenprobe: segmenting must keep working, or every dictation paysthe O(n²) cost this design exists to avoid."""stt = _ScriptedSTT(fail_first=0)- cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=0.5)+ cfg = DictationConfig(+ partial_interval_s=0.02,+ segment_seconds=0.5,+ final_quality_pass=False,+ )captured = await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=3)@@ -204,7 +212,11 @@ async def test_the_final_transcription_is_retried(monkeypatch) -> None:precise moment the user has stopped speaking and is waiting for their text."""stt = _ScriptedSTT(fail_first=1, text="the words")- cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=0.5)+ cfg = DictationConfig(+ partial_interval_s=0.0,+ segment_seconds=0.5,+ final_quality_pass=False,+ )captured = await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=0)@@ -227,7 +239,11 @@ async def test_the_retry_gives_up_instead_of_hanging(monkeypatch) -> None:Restore can try again once the provider is back."""stt = _ScriptedSTT(fail_first=99)- cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=0.5)+ cfg = DictationConfig(+ partial_interval_s=0.0,+ segment_seconds=0.5,+ final_quality_pass=False,+ )captured = await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=0)diff --git a/tests/unit/speech/test_dictation_pause_does_not_truncate.py b/tests/unit/speech/test_dictation_pause_does_not_truncate.pyindex 08feda6b49..bcb7c945d9 100644--- a/tests/unit/speech/test_dictation_pause_does_not_truncate.py+++ b/tests/unit/speech/test_dictation_pause_does_not_truncate.py@@ -181,7 +181,11 @@ async def test_words_after_a_long_pause_still_reach_the_transcript(monkeypatch)"""script = [_word(0), _word(1), _silence(12.0), _word(2), _word(3)]stt = _MarkerSTT()- cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=2.0)+ cfg = DictationConfig(+ partial_interval_s=0.02,+ segment_seconds=2.0,+ final_quality_pass=False,+ )captured = await _run(monkeypatch, script=script, stt=stt, cfg=cfg)@@ -218,7 +222,11 @@ async def test_the_open_tail_never_grows_past_one_segment(monkeypatch) -> None:"""script = [_word(i, seconds=1.0) for i in range(12)]stt = _MarkerSTT()- cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=2.0)+ cfg = DictationConfig(+ partial_interval_s=0.02,+ segment_seconds=2.0,+ final_quality_pass=False,+ )await _run(monkeypatch, script=script, stt=stt, cfg=cfg)@@ -268,7 +276,11 @@ async def test_one_dead_piece_does_not_cost_the_others(monkeypatch) -> None:script = [_word(i, seconds=1.0) for i in range(4)]stt = _OneBadPiece()- cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=1.0)+ cfg = DictationConfig(+ partial_interval_s=0.0,+ segment_seconds=1.0,+ final_quality_pass=False,+ )captured = await _run(monkeypatch, script=script, stt=stt, cfg=cfg)@@ -290,7 +302,11 @@ async def test_the_final_pass_goes_out_in_pieces(monkeypatch) -> None:"""script = [_word(i, seconds=1.0) for i in range(6)]stt = _MarkerSTT()- cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=2.0)+ cfg = DictationConfig(+ partial_interval_s=0.0,+ segment_seconds=2.0,+ final_quality_pass=False,+ )captured = await _run(monkeypatch, script=script, stt=stt, cfg=cfg)diff --git a/tests/unit/speech/test_stt_fallback.py b/tests/unit/speech/test_stt_fallback.pyindex 06126534f0..c091e6068b 100644--- a/tests/unit/speech/test_stt_fallback.py+++ b/tests/unit/speech/test_stt_fallback.py@@ -59,6 +59,19 @@ async def test_rate_limit_crosses_to_the_next_provider():assert backup.calls == 1+async def test_fallback_exposes_the_model_that_actually_answered():+ primary = FakeSTT(error=RuntimeError("429 Too Many Requests"))+ primary._model = "whisper-large-v3-turbo"+ backup = FakeSTT(text="recovered")+ backup._model = "gpt-4o-transcribe"+ chain = _chain(primary, **{"openai-api": backup})++ await chain.transcribe_pcm(b"x")++ assert chain.last_used_provider == "openai-api"+ assert chain.last_used_model == "gpt-4o-transcribe"++@pytest.mark.parametrize("message",[diff --git a/tests/unit/ui/web/test_dictation_polish_routes.py b/tests/unit/ui/web/test_dictation_polish_routes.pyindex 454a184fe6..0ebe6d1503 100644--- a/tests/unit/ui/web/test_dictation_polish_routes.py+++ b/tests/unit/ui/web/test_dictation_polish_routes.py@@ -149,7 +149,7 @@ def test_restore_starts_from_the_providers_raw_decode("""stt = _FakeSTT("We talked about it.", # what the provider's own filter produced- raw_text="Um, we talked about it. ... and then the report went out.",+ raw_text="Umm, we talked about it. ... and then the report went out.",)_install_pipeline(monkeypatch, _utterance_stt=stt)entry = _failed_with_audio()@@ -158,24 +158,24 @@ def test_restore_starts_from_the_providers_raw_decode(assert body["retranscribed"] is True# The raw column is the provider's decode, not its cleaned answer.- assert body["entry"]["raw_text"].startswith("Um, we talked about it.")+ assert body["entry"]["raw_text"].startswith("Umm, we talked about it.")# And the chain ran over that decode: the second sentence only exists in# the raw string, so its presence proves Restore did not read ``text``.assert "report went out" in body["entry"]["text"]- assert not body["entry"]["text"].startswith("Um,")+ assert not body["entry"]["text"].startswith("Umm,")def test_restore_falls_back_to_text_for_a_provider_without_a_raw_decode(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:"""Providers that set no ``raw_text`` behave exactly as they did before."""- stt = _FakeSTT("Um, we talked about it.")+ stt = _FakeSTT("Umm, we talked about it.")_install_pipeline(monkeypatch, _utterance_stt=stt)entry = _failed_with_audio()body = client.post(f"/api/dictation/history/{entry.id}/restore").json()- assert body["entry"]["raw_text"] == "Um, we talked about it."+ assert body["entry"]["raw_text"] == "Umm, we talked about it."assert body["entry"]["text"] == "We talked about it."