Skip to content

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

fix(dictation): stop asking a 4-second clip which language is being spoken

Ruben Lütke2d515101a519
diff --git a/jarvis/dictation/local_preview.py b/jarvis/dictation/local_preview.py
index 1d1553d096..87c3d1fb05 100644
--- a/jarvis/dictation/local_preview.py
+++ b/jarvis/dictation/local_preview.py
@@ -82,6 +82,16 @@ class LocalPreviewTranscriber:
self._unavailable = False
self._loading = False
self._load_failed = False
+ #: Language of the MOST RECENT preview, as ``(code, probability)``.
+ #: The engine computes this on every call and it used to be discarded.
+ #: It is the only reading of the spoken language taken from the AUDIO
+ #: rather than from a transcript, which is what makes it worth keeping:
+ #: a cloud provider handed a few seconds of speech may silently
+ #: TRANSLATE it, and a translated sentence looks like the wrong
+ #: language to any text-based detector (BUG: German dictation
+ #: delivered in English, 2026-07-29). Empty until a preview has run.
+ self.last_language = ""
+ self.last_language_probability = 0.0
@property
def available(self) -> bool:
@@ -140,22 +150,37 @@ class LocalPreviewTranscriber:
log.debug("Preview CUDA probe failed (%s); using CPU.", exc)
return "cpu", "int8"
- def _transcribe_sync(self, pcm: bytes, language: str | None) -> str:
+ def _transcribe_sync(self, pcm: bytes, language: str | None) -> tuple[str, str, float]:
+ """``(text, language_code, language_probability)``.
+
+ The language is reported back rather than dropped: it costs nothing
+ (the decoder already produced it) and it is an AUDIO-derived reading,
+ which no downstream text inspection can reconstruct once a provider
+ has translated the words.
+ """
import numpy as np
samples = np.frombuffer(pcm, dtype=np.int16).astype(np.float32) / 32768.0
if samples.size == 0:
- return ""
+ return "", "", 0.0
model = self._model
if model is None: # pragma: no cover — transcribe() gates on ready
- return ""
- segments, _info = model.transcribe(
+ return "", "", 0.0
+ segments, info = model.transcribe(
samples,
language=language,
beam_size=1, # greedy: the preview trades a little accuracy for latency
condition_on_previous_text=False,
)
- return " ".join(seg.text for seg in segments).strip()
+ text = " ".join(seg.text for seg in segments).strip()
+ # A language the CALLER pinned is not a detection — reporting it back as
+ # one would let a pin confirm itself forever.
+ detected = "" if language else str(getattr(info, "language", "") or "")
+ try:
+ probability = float(getattr(info, "language_probability", 0.0) or 0.0)
+ except (TypeError, ValueError):
+ probability = 0.0
+ return text, detected, probability
async def transcribe(self, pcm: bytes, language: str | None = None) -> str | None:
"""Preview text, or ``None`` when this tick has none.
@@ -181,10 +206,14 @@ class LocalPreviewTranscriber:
# call on a native engine is how it wedges (AP-24).
return None
try:
- return await asyncio.wait_for(
+ text, detected, probability = await asyncio.wait_for(
asyncio.to_thread(self._transcribe_sync, pcm, language),
timeout=PREVIEW_TIMEOUT_S,
)
+ if detected:
+ self.last_language = detected
+ self.last_language_probability = probability
+ return text
except TimeoutError:
# Not silent: _note_failure logs the attempt and drops the engine once
# the failures persist. Returning None is the whole handling — a
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index d9bb0b5a4a..baf1d1bb1f 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -995,6 +995,73 @@ def resolve_dictation_language(*, pinned: str, reported: str, text: str) -> str:
log.debug("dictation language detection failed", exc_info=True)
return tag
+
+#: How sure the on-device detector must be before its reading is allowed to pin
+#: the rest of a session. The engine answers ~1.0 on a few seconds of clear
+#: speech and drops sharply on noise or silence, so this rejects the readings
+#: that would pin the WRONG language while costing nothing on real speech.
+_RECOGNITION_PIN_MIN_PROBABILITY = 0.6
+
+
+def resolve_recognition_language(*, pinned: str, session_language: str) -> str:
+ """Which language to ASK the provider for on the next piece of audio.
+
+ Distinct from :func:`resolve_dictation_language`, which labels a finished
+ dictation. This one runs BEFORE a transcription and decides what the
+ recogniser is told, which is a different question with a different failure:
+
+ ``auto`` reaches a provider as "no language field", i.e. "detect it
+ yourself". Whisper detects from the audio it is given, and a dictation is
+ uploaded in ~4 s segments — far too little for a confident reading. On a
+ short segment the model does not merely mislabel the language, it
+ TRANSLATES: the same German recording came back verbatim when posted whole
+ and as fluent English when posted in segments, and re-running one segment
+ flipped between the two (measured against openai/whisper-large-v3 through
+ OpenRouter, 2026-07-29). Nothing downstream can undo that — a translated
+ sentence IS English to every text-based detector — so the repair has to
+ happen before the call.
+
+ The fix is to stop asking twice. Once a session has an AUDIO-derived
+ reading of what is being spoken, every later piece is told that language
+ explicitly instead of gambling on four seconds of context. Auto-detect is
+ preserved where it belongs: the session still starts on ``auto``, and the
+ reading is renewed from the audio as the session runs, so switching
+ language mid-dictation still lands (the bilingual mandate — a static pin
+ was the 2026-06-14 bug and is not what this restores).
+
+ Precedence, and the order is the point:
+
+ 1. **A user's pin wins.** It is the one signal a person can set.
+ 2. **Otherwise this session's own reading**, when there is one.
+ 3. **Otherwise ``auto``** — a provider that detects well on the audio it
+ has is not made worse by being asked to.
+ """
+ pin = str(pinned or "").strip().lower()
+ if pin and pin != "auto":
+ return pin
+ session = str(session_language or "").strip().lower()
+ return session or "auto"
+
+
+def accept_recognition_reading(*, language: str, probability: float) -> str:
+ """The session language an on-device reading justifies; ``""`` for none.
+
+ Gate-keeps :func:`resolve_recognition_language`'s second precedence step.
+ A reading only earns the right to steer later segments when the detector
+ was actually sure, because the cost of accepting a bad one is a whole
+ dictation pinned to a language nobody spoke.
+ """
+ code = str(language or "").strip().lower()
+ if not code or code in ("auto", "unknown", "und", "nn"):
+ return ""
+ try:
+ if float(probability) < _RECOGNITION_PIN_MIN_PROBABILITY:
+ return ""
+ except (TypeError, ValueError):
+ return ""
+ return code
+
+
# After this many consecutive pieces have exhausted every attempt, the provider
# is not flaky, it is down — and continuing to retry each remaining piece would
# make a 300 s dictation spend minutes proving it. Stop and say so: the audio is
@@ -9111,6 +9178,13 @@ class SpeechPipeline:
dictation_language = (
str(getattr(cfg, "language", "auto") or "auto").strip().lower() or "auto"
)
+ # What THIS session has established is being spoken, read from the audio
+ # rather than from a transcript. Empty until a reading earns it; once
+ # set, every later segment is told this language instead of asking a
+ # 4-second clip to detect it — the whole of the German-in, English-out
+ # repair (see ``resolve_recognition_language``). It is re-read as the
+ # session runs, so a user who switches language is followed, not pinned.
+ session_language = ""
async def _transcribe(
pcm: bytes,
@@ -9150,17 +9224,20 @@ 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
+ nonlocal stt_error, stt_error_detail, session_language
ceiling = max(
float(getattr(self, "_stt_final_timeout_s", 8.0) or 8.0),
(len(pcm) / bytes_per_second)
* _DICTATION_TRANSCRIBE_TIMEOUT_PER_AUDIO_S,
)
+ ask_for = resolve_recognition_language(
+ pinned=dictation_language, session_language=session_language
+ )
inference_active.set()
try:
try:
transcript = await asyncio.wait_for(
- stt.transcribe_pcm(pcm, language=dictation_language),
+ stt.transcribe_pcm(pcm, language=ask_for),
timeout=ceiling,
)
except TypeError:
@@ -9283,7 +9360,7 @@ class SpeechPipeline:
async def _probe() -> None:
"""Close finished segments and publish the live transcript."""
- nonlocal last_published, language, error_backoff_s
+ nonlocal last_published, language, error_backoff_s, session_language
from jarvis.dictation.local_preview import local_preview
from jarvis.dictation.preview_budget import preview_budget
from jarvis.dictation.segment import is_silent_segment
@@ -9335,13 +9412,37 @@ class SpeechPipeline:
# itself is never produced here.
engine = local_preview() if want_preview else None
if engine is not None:
+ ask_local = resolve_recognition_language(
+ pinned=dictation_language,
+ session_language=session_language,
+ )
local_text = await engine.transcribe(
tail,
- language=None if dictation_language == "auto"
- else dictation_language,
+ language=None if ask_local == "auto" else ask_local,
)
if stop_event.is_set():
return
+ # The reading this preview took from the AUDIO. Free —
+ # the decoder produced it either way — and the only
+ # reading a cloud provider's translated words cannot
+ # contradict. It steers the segment uploads that
+ # actually produce the transcript.
+ if not session_language:
+ accepted = accept_recognition_reading(
+ language=getattr(engine, "last_language", ""),
+ probability=getattr(
+ engine, "last_language_probability", 0.0
+ ),
+ )
+ if accepted:
+ session_language = accepted
+ log.info(
+ "dictation recognition language established "
+ "from the audio: %s — later segments are "
+ "transcribed as that language instead of "
+ "re-detecting on each one.",
+ accepted,
+ )
if local_text is not None:
tail_text = local_text
want_preview = False # served without touching the quota
diff --git a/tests/unit/dictation/test_local_preview.py b/tests/unit/dictation/test_local_preview.py
index 0e53d5810c..dcb2fdcdf3 100644
--- a/tests/unit/dictation/test_local_preview.py
+++ b/tests/unit/dictation/test_local_preview.py
@@ -32,9 +32,17 @@ class _Engine(LocalPreviewTranscriber):
not finished loading answers "nothing yet" without transcribing anything.
"""
- def __init__(self, text="hallo welt", delay=0.0, error=None): # i18n-allow: German test fixture
+ def __init__(
+ self,
+ text="hallo welt", # i18n-allow: German test fixture
+ delay=0.0,
+ error=None,
+ detected="",
+ probability=0.0,
+ ):
super().__init__()
self.text, self.delay, self.error = text, delay, error
+ self.detected, self.probability = detected, probability
self.calls = 0
self._model = object() # pretend the load already completed
@@ -46,7 +54,7 @@ class _Engine(LocalPreviewTranscriber):
import time
time.sleep(self.delay)
- return self.text
+ return self.text, self.detected, self.probability
async def test_preview_text_comes_back():
@@ -169,3 +177,72 @@ def test_the_device_probe_falls_back_to_cpu_when_cuda_is_not_usable(monkeypatch)
monkeypatch.setattr(builtins, "__import__", _no_torch)
assert LocalPreviewTranscriber._pick_device() == ("cpu", "int8")
+
+
+async def test_the_audio_language_reading_is_kept_not_discarded():
+ """The decoder names the spoken language on every call; the preview keeps it.
+
+ This reading is the only one taken from the AUDIO. A cloud provider handed
+ a few seconds of speech may TRANSLATE it, and translated words look like
+ the target language to any text-based detector — so a reading taken after
+ the fact cannot replace this one.
+ """
+ # i18n-allow: German test fixture — the speech under test
+ engine = _Engine(text="hallo welt", detected="de", probability=0.99)
+
+ assert await engine.transcribe(b"\x00" * 32000) == "hallo welt"
+ assert engine.last_language == "de"
+ assert engine.last_language_probability == 0.99
+
+
+class _Segment:
+ def __init__(self, text):
+ self.text = text
+
+
+class _Info:
+ def __init__(self, language, probability):
+ self.language = language
+ self.language_probability = probability
+
+
+class _NativeModel:
+ """Stands in for the real decoder, which always names a language."""
+
+ def __init__(self, text, language, probability):
+ self._answer = (text, language, probability)
+ self.asked_for: list[str | None] = []
+
+ def transcribe(self, samples, language=None, **kwargs):
+ self.asked_for.append(language)
+ text, detected, probability = self._answer
+ return [_Segment(text)], _Info(detected, probability)
+
+
+def test_a_pinned_language_is_not_reported_back_as_a_detection():
+ """Otherwise a pin would confirm itself forever and never be re-examined.
+
+ Runs the REAL decode path — the point is what the engine does with the
+ decoder's answer, so a stub that skips that step would prove nothing.
+ """
+ engine = LocalPreviewTranscriber()
+ # The decoder is handed "de" and, as it always does, echoes a language back.
+ engine._model = _NativeModel("Hallo Welt", "de", 1.0) # i18n-allow: German test fixture
+
+ text, detected, probability = engine._transcribe_sync(b"\x00" * 32000, "de")
+
+ assert text == "Hallo Welt" # i18n-allow: German test fixture
+ assert detected == "", (
+ "a language the caller supplied is an instruction, not a reading"
+ )
+ assert probability == 1.0
+
+
+def test_an_unpinned_decode_reports_the_language_it_found():
+ engine = LocalPreviewTranscriber()
+ engine._model = _NativeModel("Hallo Welt", "de", 0.98) # i18n-allow: German test fixture
+
+ text, detected, probability = engine._transcribe_sync(b"\x00" * 32000, None)
+
+ assert (detected, probability) == ("de", 0.98)
+ assert text == "Hallo Welt" # i18n-allow: German test fixture
diff --git a/tests/unit/speech/test_dictation_recognition_language.py b/tests/unit/speech/test_dictation_recognition_language.py
new file mode 100644
index 0000000000..41b75cbded
--- /dev/null
+++ b/tests/unit/speech/test_dictation_recognition_language.py
@@ -0,0 +1,110 @@
+"""What language the recogniser is ASKED for, before it transcribes anything.
+
+Root cause these lock (2026-07-29, measured against openai/whisper-large-v3
+through OpenRouter): ``auto`` reaches a provider as "no language field", which
+means "detect it yourself". A dictation is uploaded in ~4 s segments, and on a
+segment that short the model does not merely mislabel the language — it
+TRANSLATES. The same German recording came back verbatim when posted whole and
+as fluent English when posted in segments, and re-running one segment flipped
+between the two. Every user-visible symptom followed from that: German speech
+delivered as English words, and a history whose language column read "en"
+because by then the text really was English.
+
+Nothing downstream can repair it — a translated sentence IS English to any
+text-based detector — so the decision has to be made before the call.
+"""
+
+from __future__ import annotations
+
+from jarvis.speech.pipeline import (
+ accept_recognition_reading,
+ resolve_recognition_language,
+)
+
+
+class TestWhatTheRecogniserIsAskedFor:
+ def test_a_fresh_session_still_asks_the_provider_to_detect(self):
+ """Auto-detect is the shipped default and stays the starting point."""
+ assert (
+ resolve_recognition_language(pinned="auto", session_language="") == "auto"
+ )
+
+ def test_once_the_session_knows_the_language_it_says_so(self):
+ """THE FIX: stop re-asking a 4 s clip a question already answered."""
+ assert resolve_recognition_language(pinned="auto", session_language="de") == "de"
+
+ def test_a_user_pin_outranks_the_session_reading(self):
+ """The pin is the one signal a person can set; overruling it would
+ leave them no way to be right."""
+ assert resolve_recognition_language(pinned="de", session_language="en") == "de"
+
+ def test_an_empty_pin_is_treated_as_auto(self):
+ assert resolve_recognition_language(pinned="", session_language="") == "auto"
+ assert resolve_recognition_language(pinned=" ", session_language="es") == "es"
+
+ def test_the_answer_is_case_insensitive_and_trimmed(self):
+ assert resolve_recognition_language(pinned=" DE ", session_language="") == "de"
+ assert resolve_recognition_language(pinned="auto", session_language=" ES ") == "es"
+
+ def test_every_supported_language_is_carried_the_same_way(self):
+ """No de/en bias — a locale is a locale (CLAUDE.md §1)."""
+ for code in ("de", "en", "es"):
+ assert (
+ resolve_recognition_language(pinned="auto", session_language=code)
+ == code
+ )
+
+
+class TestWhichReadingsMaySteerASession:
+ """A reading that pins the WRONG language costs the whole dictation, so the
+ gate is deliberately strict: only a confident, placeable reading counts."""
+
+ def test_a_confident_reading_is_accepted(self):
+ assert accept_recognition_reading(language="de", probability=0.99) == "de"
+
+ def test_an_unsure_reading_is_refused(self):
+ """The detector drops sharply on noise and silence; that is the case
+ this rejects, and it costs nothing on real speech (~1.0)."""
+ assert accept_recognition_reading(language="de", probability=0.2) == ""
+
+ def test_a_non_answer_is_refused_however_confident(self):
+ for tag in ("", " ", "auto", "unknown", "und"):
+ assert accept_recognition_reading(language=tag, probability=1.0) == ""
+
+ def test_a_missing_or_broken_probability_is_refused_not_assumed(self):
+ assert accept_recognition_reading(language="de", probability=None) == ""
+ assert accept_recognition_reading(language="de", probability="very") == ""
+
+ def test_an_accepted_reading_comes_back_as_a_lowercase_code(self):
+ assert accept_recognition_reading(language=" DE ", probability=0.9) == "de"
+
+
+class TestTheBugItself:
+ def test_a_german_session_never_asks_for_english_again(self):
+ """The reported failure, end to end.
+
+ Segment 1 is transcribed with no language field (the gamble). The
+ preview reads the AUDIO as German and the session accepts it — so every
+ later segment is asked for German instead of gambling again. That is
+ what stops segment 2 coming back translated.
+ """
+ session = ""
+ assert resolve_recognition_language(pinned="auto", session_language=session) == "auto"
+
+ session = accept_recognition_reading(language="de", probability=1.0)
+
+ for _later_segment in range(5):
+ assert (
+ resolve_recognition_language(pinned="auto", session_language=session)
+ == "de"
+ )
+
+ def test_a_bilingual_user_is_followed_not_frozen(self):
+ """A static pin was the 2026-06-14 bug (English audio written as German
+ gibberish) and is not what this restores: the reading is renewed from
+ the audio, so switching language mid-session still lands."""
+ session = accept_recognition_reading(language="de", probability=1.0)
+ assert resolve_recognition_language(pinned="auto", session_language=session) == "de"
+
+ session = accept_recognition_reading(language="en", probability=0.97)
+ assert resolve_recognition_language(pinned="auto", session_language=session) == "en"