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(stt): close the four gaps the filter rollout left open

Ruben Lütke9ec36a1c6923
diff --git a/jarvis/plugins/stt/nemotron_local.py b/jarvis/plugins/stt/nemotron_local.py
index 5838a9547a..d46fd1cc25 100644
--- a/jarvis/plugins/stt/nemotron_local.py
+++ b/jarvis/plugins/stt/nemotron_local.py
@@ -255,9 +255,17 @@ class NemotronLocalSTT:
while recognizer.is_ready(stream):
recognizer.decode_stream(stream)
result = recognizer.get_result(stream)
- text = (result or "").strip()
+ raw = (result or "").strip()
+ # Same cleanup pass every other provider runs, so the transcript a user
+ # gets does not depend on which engine they picked. ``raw_text`` keeps
+ # the decode for the callers that must not read an edited string (the
+ # dictation lane, wake verification).
+ from jarvis.plugins.stt.transcript_filter import clean_stt_text
+
+ text = clean_stt_text(raw, language=language)
return Transcript(
text=text,
+ raw_text=raw,
language=language or "auto",
# The transducer exposes no calibrated per-utterance probability;
# inventing one would put a fabricated number in front of every
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index c8bdf621ff..2b325e27a1 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -3243,7 +3243,17 @@ class SpeechPipeline:
self, "_probe_generation", generation
):
return
- raw_text = (getattr(transcript, "text", "") or "").strip()
+ # The RAW decode, deliberately. This probe asks "did anything get
+ # said in the tail?" and answers with text LENGTH plus the
+ # hallucination markers. A provider-cleaned string breaks both:
+ # a tail of pure hesitation ("ähm ...") cleans down to nothing and # i18n-allow: quoted input
+ # would read as silence, so Jarvis would cut off the one person
+ # who is visibly still thinking.
+ raw_text = (
+ getattr(transcript, "raw_text", "")
+ or getattr(transcript, "text", "")
+ or ""
+ ).strip()
text = raw_text.lower()
confidence = float(getattr(transcript, "confidence", 0.0) or 0.0)
diff --git a/jarvis/speech/wake_verifier.py b/jarvis/speech/wake_verifier.py
index 88bd6c7a1d..dc0d867232 100644
--- a/jarvis/speech/wake_verifier.py
+++ b/jarvis/speech/wake_verifier.py
@@ -170,7 +170,14 @@ async def verify_wake_with_stt(
# None (not "") = STT OUTAGE: lets the caller degrade open on a dead
# provider (AP-22) while a genuine empty transcription stays "".
return False, None
- text = (getattr(transcript, "text", "") or "").strip()
+ # ``raw_text`` first, like the rolling-whisper verifier: wake has to judge
+ # what the recognizer EMITTED. A provider-cleaned string would be a
+ # different sentence than the one the audio checks were measured against,
+ # and the prefix match would then be answering about text nobody spoke
+ # (AP-27).
+ text = (
+ getattr(transcript, "raw_text", "") or getattr(transcript, "text", "") or ""
+ ).strip()
matched = transcript_has_hey_prefix(text, matcher)
log.info(
"wake-verify transcript=%r matched=%s",
diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.py
index f2157449f6..01c5469b80 100644
--- a/jarvis/ui/web/dictation_routes.py
+++ b/jarvis/ui/web/dictation_routes.py
@@ -310,7 +310,15 @@ async def _retranscribe_from_audio(
log.warning("dictation restore transcription failed: %s", exc, exc_info=True)
return "", "", "", f"Transcribing the saved audio failed: {exc}"
- raw = str(getattr(transcript, "text", "") or "").strip()
+ # ``raw_text`` first: Restore re-runs the SAME delivery chain as the live
+ # lane (filler removal under the user's switch, punctuation repair, polish),
+ # so it has to start from the same string the lane starts from. Starting
+ # from a provider-cleaned one would quietly restore different words than the
+ # dictation produced - and ``raw`` is also what the history shows as the
+ # original.
+ raw = str(
+ getattr(transcript, "raw_text", "") or getattr(transcript, "text", "") or ""
+ ).strip()
reported = str(getattr(transcript, "language", "") or "")
if not raw:
return (
diff --git a/tests/unit/plugins/stt/test_transcript_filter_parity.py b/tests/unit/plugins/stt/test_transcript_filter_parity.py
index 151b74590c..4f176dcd5d 100644
--- a/tests/unit/plugins/stt/test_transcript_filter_parity.py
+++ b/tests/unit/plugins/stt/test_transcript_filter_parity.py
@@ -17,27 +17,67 @@ The German fixtures are the speech under test (CLAUDE.md §1, category 4).
from __future__ import annotations
import dataclasses
+import importlib
+import pkgutil
from types import SimpleNamespace
import pytest
-from jarvis.plugins.stt import (
- gemini_api,
- groq_api,
- openai_api,
- openrouter_stt,
-)
+import jarvis.plugins.stt as stt_package
+from jarvis.plugins.stt import gemini_api, groq_api, openai_api, openrouter_stt
#: One payload carrying three artifact classes at once: an outer quote pair the
#: model added, a hesitation sound, and a decoder repetition loop.
DIRTY_TEXT = '"Um, turn on the light. Thank you. Thank you. Thank you."'
CLEAN_TEXT = "Turn on the light. Thank you."
-#: Every provider module that turns a vendor payload into a Transcript.
+#: Modules in the package that are not providers.
+_NON_PROVIDER_MODULES = frozenset({"errors", "transcript_filter"})
+
+
+def _discover_provider_modules() -> tuple[object, ...]:
+ """Every provider module in the package, found rather than listed.
+
+ Listing them by hand is what let the Nemotron engine ship past the first
+ rollout of this filter: it was added in a parallel session, the list did not
+ know about it, and the parity test went green while one provider quietly
+ behaved differently from the other five. Discovery makes the NEXT provider
+ fail loudly instead.
+
+ A module counts as a provider when it defines a ``Transcript`` — that is the
+ thing this file has an opinion about. A module that cannot be imported (an
+ optional SDK missing on this host) is skipped, not failed: the point of the
+ plugin layout is that a provider you have no dependencies for stays absent.
+ """
+ found: list[object] = []
+ for info in pkgutil.iter_modules(stt_package.__path__):
+ if info.name.startswith("_") or info.name in _NON_PROVIDER_MODULES:
+ continue
+ try:
+ module = importlib.import_module(f"{stt_package.__name__}.{info.name}")
+ except Exception: # noqa: BLE001, S112 — see below
+ # Deliberately silent: on a base install the absent SDKs are the
+ # EXPECTED case, and logging one line per skipped provider would
+ # bury the run in noise about modules that are working as designed.
+ continue
+ if hasattr(module, "Transcript"):
+ found.append(module)
+ return tuple(found)
+
+
+#: Providers that turn a vendor JSON payload into a Transcript.
PAYLOAD_PROVIDERS = (openrouter_stt, groq_api, openai_api)
-#: Every provider module at all, including the local engine.
-ALL_PROVIDER_MODULES = (openrouter_stt, groq_api, openai_api, gemini_api)
+#: Every provider module in the package, discovered at collection time.
+ALL_PROVIDER_MODULES = _discover_provider_modules()
+
+
+def test_discovery_actually_found_the_known_providers() -> None:
+ """A guard on the guard: a broken discovery would make everything below
+ vacuously pass by finding nothing at all."""
+ names = {m.__name__.rsplit(".", 1)[-1] for m in ALL_PROVIDER_MODULES}
+ assert {"openrouter_stt", "groq_api", "openai_api", "gemini_api"} <= names
+ assert len(ALL_PROVIDER_MODULES) >= 4
@pytest.mark.parametrize(
@@ -110,6 +150,30 @@ def test_every_provider_transcript_carries_an_optional_raw_text(module) -> None:
assert fields["raw_text"].default == ""
+ "module", ALL_PROVIDER_MODULES, ids=lambda m: m.__name__.rsplit(".", 1)[-1]
+)
+def test_every_provider_module_runs_the_filter(module) -> None:
+ """Source-level, on purpose.
+
+ A behavioural test is better and this file has one wherever it is possible
+ — but it is not possible for every provider: some need a vendor SDK that a
+ base install does not carry, and one needs an on-device model measured in
+ gigabytes. Those providers are exactly the ones nobody notices drifting, so
+ the check that covers ALL of them is the one that reads the source. It
+ proves the call is wired, not that it works; the behavioural tests above
+ prove the rest for the providers that can be driven here.
+ """
+ import inspect
+
+ source = inspect.getsource(module)
+ assert "clean_stt_text" in source, (
+ f"{module.__name__} builds a Transcript without running the cleanup "
+ "filter — its users would get hesitation sounds and decoder loops that "
+ "every other provider removes."
+ )
+
+
def test_the_shared_protocol_transcript_carries_it_too() -> None:
"""The local engine returns the protocol type, not a plugin-local copy."""
from jarvis.core.protocols import Transcript as ProtocolTranscript
diff --git a/tests/unit/speech/test_wake_verifier.py b/tests/unit/speech/test_wake_verifier.py
index 21aa0256bc..a9af4c5b5d 100644
--- a/tests/unit/speech/test_wake_verifier.py
+++ b/tests/unit/speech/test_wake_verifier.py
@@ -104,12 +104,22 @@ class _FakeTranscript:
text: str
language: str = "de"
confidence: float = 1.0
+ #: What the provider decoded before its own cleanup filter ran. Empty means
+ #: the provider does not filter, and the verifier falls back to ``text``.
+ raw_text: str = ""
class _FakeSTT:
- def __init__(self, transcript_text: str, *, raises: Exception | None = None) -> None:
+ def __init__(
+ self,
+ transcript_text: str,
+ *,
+ raises: Exception | None = None,
+ raw_text: str = "",
+ ) -> None:
self._text = transcript_text
self._raises = raises
+ self._raw_text = raw_text
self.calls: list[tuple[int, int, str | None]] = []
async def transcribe_pcm(
@@ -121,7 +131,7 @@ class _FakeSTT:
self.calls.append((len(pcm_bytes), sample_rate, language))
if self._raises is not None:
raise self._raises
- return _FakeTranscript(text=self._text)
+ return _FakeTranscript(text=self._text, raw_text=self._raw_text)
PCM_2S_16K = b"\x00\x00" * 16_000 * 2 # 2 s int16 silence
@@ -144,6 +154,24 @@ async def test_verify_returns_true_when_transcript_has_hey_prefix() -> None:
assert stt.calls == [(len(PCM_2S_16K), 16_000, None)]
+async def test_verify_judges_the_recognizers_own_output_not_a_cleaned_one() -> None:
+ """Providers now filter their transcript; wake must not read that.
+
+ Verification decides whether the phrase was SPOKEN, and it is paired with
+ audio measurements taken on the raw decode — energy at the match site, the
+ shape of the candidate span (AP-27). Judging an edited sentence would break
+ that pairing and answer about text nobody said. So ``raw_text`` wins
+ whenever a provider offers it, and the string handed back is that one too:
+ the caller logs it as the evidence for the decision.
+ """
+ stt = _FakeSTT("Jarvis", raw_text="Hey Jarvis, was läuft") # i18n-allow
+
+ matched, transcript = await verify_wake_with_stt(stt, PCM_2S_16K, matcher=_JARVIS)
+
+ assert matched is True
+ assert transcript == "Hey Jarvis, was läuft" # i18n-allow
+
+
async def test_verify_returns_false_when_transcript_is_bare_jarvis() -> None:
stt = _FakeSTT("Jarvis")
diff --git a/tests/unit/ui/web/test_dictation_polish_routes.py b/tests/unit/ui/web/test_dictation_polish_routes.py
index 2bf8c262c0..0d9004cb9c 100644
--- a/tests/unit/ui/web/test_dictation_polish_routes.py
+++ b/tests/unit/ui/web/test_dictation_polish_routes.py
@@ -57,17 +57,25 @@ def client(app: FastAPI) -> TestClient:
class _Transcript:
text: str
language: str = "en"
+ #: What the provider decoded before its own cleanup filter ran. Empty for a
+ #: provider that does not filter, which is what the fallback below covers.
+ raw_text: str = ""
class _FakeSTT:
- def __init__(self, text: str, language: str = "en") -> None:
+ def __init__(
+ self, text: str, language: str = "en", *, raw_text: str = ""
+ ) -> None:
self._text = text
self._language = language
+ self._raw_text = raw_text
self.calls: list[str | None] = []
async def transcribe_pcm(self, pcm: bytes, language: str | None = None) -> Any:
self.calls.append(language)
- return _Transcript(text=self._text, language=self._language)
+ return _Transcript(
+ text=self._text, language=self._language, raw_text=self._raw_text
+ )
def _install_pipeline(monkeypatch: pytest.MonkeyPatch, **attrs: Any) -> Any:
@@ -126,6 +134,51 @@ def test_restore_repairs_the_punctuation_the_segmenting_broke(
assert "..." in body["entry"]["raw_text"]
+def test_restore_starts_from_the_providers_raw_decode(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A provider that cleans its own transcript must not shortcut the chain.
+
+ Every provider now filters its text before returning it, and dictation is
+ the one caller that must not read that: Restore re-runs the SAME chain the
+ live lane runs — filler removal under the user's switch, punctuation
+ repair, polish — so starting from an already-cleaned string would apply the
+ cleanup twice and give the user back different words than the dictation
+ produced. The raw column would stop being raw with it, which is what makes
+ the repair auditable in the first place.
+ """
+ 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.",
+ )
+ _install_pipeline(monkeypatch, _utterance_stt=stt)
+ entry = _failed_with_audio()
+
+ body = client.post(f"/api/dictation/history/{entry.id}/restore").json()
+
+ 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.")
+ # 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,")
+
+
+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.")
+ _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"]["text"] == "We talked about it."
+
+
def test_restore_polishes_when_the_pass_is_on(
app: FastAPI, monkeypatch: pytest.MonkeyPatch
) -> None: