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): cross a stuck provider instead of losing the words, and ship a default vocabulary (#815)

Ruben Lütke1561657f5a25
diff --git a/dodaios/speech/pipeline.py b/dodaios/speech/pipeline.py
index 1e124bea3d..a043514453 100644
--- a/dodaios/speech/pipeline.py
+++ b/dodaios/speech/pipeline.py
@@ -1031,6 +1031,28 @@ def _dictation_retry_worthwhile(exc: BaseException | None) -> bool:
return status in _STT_TRANSIENT_STATUS
+def _stt_crossing_reserve_s(stt: Any, audio_s: float) -> float:
+ """Time the provider chain behind ``stt`` may spend crossing, else ``0.0``.
+
+ A :class:`dodaios.speech.stt_fallback.FallbackSTT` with per-provider
+ deadlines bounds each provider that has another one behind it; the lane's
+ own ceiling must cover those deadlines PLUS a full call on the provider it
+ crosses to. One provider's worth of time around the whole chain is exactly
+ what lost the 2026-10-20 17:35 dictation: the local pass hung for the full
+ 8 s, the ceiling ran out, and the keyed cloud provider never got the audio.
+ Read through the transparent wrappers (meter, dictionary), each of which
+ forwards unknown attributes. Never raises.
+ """
+ reserve = getattr(stt, "crossing_reserve_s", None)
+ if not callable(reserve):
+ return 0.0
+ try:
+ value = float(reserve(audio_s))
+ except Exception: # noqa: BLE001 — a missing reserve only shortens the ceiling
+ return 0.0
+ return value if value > 0.0 else 0.0
+
+
def _align_pcm(offset: int) -> int:
"""``offset`` rounded down to a whole int16 sample boundary."""
return max(0, offset - (offset % 2))
@@ -11981,6 +12003,15 @@ class SpeechPipeline:
configured = str(getattr(stt_cfg, "provider", "") or "").strip()
alternates = list(_resolve_stt_fallback_chain(stt_cfg, configured))
configured_instance = instance
+ # Every provider in front of another one gets the lane's own
+ # per-call ceiling and then the chain crosses (2026-10-20: a wedged
+ # local pass ate the whole ceiling and the keyed cloud provider
+ # behind it never heard the audio). ``_transcribe`` widens its own
+ # ceiling by the same amount, so the crossing never eats the next
+ # provider's time.
+ deadline_floor_s = float(
+ getattr(self, "_stt_final_timeout_s", 8.0) or 8.0
+ )
def _build(name: str) -> Any:
if name == configured:
@@ -12011,6 +12042,7 @@ class SpeechPipeline:
chain,
_build,
primary_name=local_final.provider_label,
+ provider_deadline_floor_s=deadline_floor_s,
)
log.info(
"Dictation STT chain armed: %s/%s (out of process) -> %s "
@@ -12023,7 +12055,11 @@ class SpeechPipeline:
from dodaios.speech.stt_fallback import FallbackSTT
instance = FallbackSTT(
- instance, alternates, _build, primary_name=configured
+ instance,
+ alternates,
+ _build,
+ primary_name=configured,
+ provider_deadline_floor_s=deadline_floor_s,
)
log.info(
"Dictation STT chain armed: %s -> %s (no voice bias prompt).",
@@ -12333,8 +12369,8 @@ class SpeechPipeline:
user has already told us they care about travel with the request and are
checked afterwards by the drift guard.
- Three sources, all of them things the user chose: the STT dictionary
- (words they added by hand for exactly this reason), the configured wake
+ Three sources: the STT dictionary (words the user added by hand for
+ exactly this reason, plus the shipped defaults they kept), the configured wake
word (a name, and names are what get "corrected"), and the assistant
name derived from it. Nothing here is a secret and nothing is free text
from a voice turn — AP-2 territory stays out of the prompt.
@@ -12344,9 +12380,11 @@ class SpeechPipeline:
"""
terms: list[str] = []
try:
- from dodaios.speech.stt_dictionary import dictionary_bias_words
+ # Shipped defaults included (the product name, PyPI, GitHub …):
+ # a rewrite model "correcting" them is the same failure.
+ from dodaios.speech.stt_dictionary import dictionary_protected_words
- terms.extend(dictionary_bias_words())
+ terms.extend(dictionary_protected_words())
except Exception as exc: # noqa: BLE001 — an unreadable store is not fatal
log.debug("dictation protected terms: dictionary unavailable (%s)", exc)
phrase = getattr(self, "_wake_phrase_label", "") or ""
@@ -12750,7 +12788,7 @@ class SpeechPipeline:
float(getattr(self, "_stt_final_timeout_s", 8.0) or 8.0),
(len(pcm) / bytes_per_second)
* _DICTATION_TRANSCRIBE_TIMEOUT_PER_AUDIO_S,
- )
+ ) + _stt_crossing_reserve_s(stt, len(pcm) / bytes_per_second)
if ask_for is None:
ask_for = resolve_recognition_language(
pinned=dictation_language, session_language=session_language
@@ -14760,6 +14798,22 @@ class SpeechPipeline:
# about why the words never arrived. The localized half is the
# reason CODE on ``error``, which the UI translates.
detail = stt_failure_message(stt_error)
+ # Every provider failed and the words exist only as audio now.
+ # That audio is kept for exactly this case (``failed`` is a
+ # recoverable outcome), so the notice says where to get the
+ # words back — the 2026-10-20 lost dictation told the user only
+ # that the service "could not be reached". Promised only when
+ # the sidecar will really be written: history on, the user's
+ # keep switch on, and audio captured.
+ if (
+ audio
+ and bool(getattr(cfg, "history_enabled", True))
+ and bool(getattr(cfg, "keep_failed_audio", True))
+ ):
+ detail += (
+ " The audio was kept — use Restore in the dictation "
+ "history to try again."
+ )
elif rejected_detail:
# Nothing arrived because what arrived was not speech. Saying so
# is the difference between "your microphone heard nothing" and
diff --git a/dodaios/speech/stt_dictionary.py b/dodaios/speech/stt_dictionary.py
index cb21dc503d..312d5e7024 100644
--- a/dodaios/speech/stt_dictionary.py
+++ b/dodaios/speech/stt_dictionary.py
@@ -150,6 +150,18 @@ class DictionaryEntry:
misheard: tuple[str, ...] = ()
created_at: str = ""
updated_at: str = ""
+ #: ``True`` for a shipped default (:data:`DEFAULT_TERMS`) the user has not
+ #: edited. Reported to the UI; never written to the sidecar.
+ default: bool = False
+ #: ``False`` makes the entry replacement-only: its misheard variants are
+ #: rewritten, but the word gets no casing rule and no fuzzy repair. Only
+ #: shipped defaults that are COMMON words use it — a casing rule for
+ #: "Bugs" would capitalise every English "bugs" mid-sentence.
+ casing: bool = True
+ #: ``False`` keeps the word out of the sound-alike repair while its casing
+ #: rule stays. Shipped defaults whose phonetic key real words share use it:
+ #: "PyPI" folds like "Pipi" and "Pippi".
+ fuzzy: bool = True
def to_dict(self) -> dict[str, Any]:
return {
@@ -158,8 +170,114 @@ class DictionaryEntry:
"misheard": list(self.misheard),
"created_at": self.created_at,
"updated_at": self.updated_at,
+ "default": self.default,
}
+ def to_storage(self) -> dict[str, Any]:
+ """The sidecar row — the user's data only, no derived flags."""
+ return {
+ "id": self.id,
+ "word": self.word,
+ "misheard": list(self.misheard),
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ }
+
+
+# ----------------------------------------------------------------------
+# Shipped default vocabulary
+# ----------------------------------------------------------------------
+
+#: Id prefix of a shipped default entry. User ids are 12 hex characters, so the
+#: two can never collide.
+DEFAULT_ID_PREFIX = "default-"
+
+
+@dataclass(frozen=True, slots=True)
+class DefaultTerm:
+ """One shipped vocabulary entry: ``word`` plus the spellings it arrives as."""
+
+ slug: str
+ word: str
+ misheard: tuple[str, ...] = ()
+ casing: bool = True
+ fuzzy: bool = True
+
+ @property
+ def entry_id(self) -> str:
+ return f"{DEFAULT_ID_PREFIX}{self.slug}"
+
+
+#: Vocabulary every install starts with, because mixed German/English dictation
+#: about this product and about software work keeps coming back with the same
+#: misspellings (reported 2026-10-20: "the Dios" for the product name, "Pipey"
+#: for PyPI, "Baggen" for Bugs).
+#:
+#: These are ordinary dictionary entries the user can edit or delete in the
+#: Dictionary view, and they never override the user's own: a user entry for
+#: the same word (or one that lists the word as a mishearing) hides the default,
+#: a user spelling hides the default variant that collides with it, and a
+#: deleted default stays deleted (``removed_defaults`` in the sidecar).
+#:
+#: Rules for adding one, since every variant rewrites EVERYONE's transcripts:
+#: a variant must not be a word a person would say on purpose ("Pipi", "PyPy",
+#: "Dios" on its own, "merken" are all out), and a common word is only ever a
+#: replacement target with ``casing=False``; a word whose sound-alike key real
+#: words share gets ``fuzzy=False``. No personal names, no contact data.
+#: The defaults are post-recognition corrections only — they are NOT added to
+#: any decoder prompt (BUG-185/BUG-211: a primed Whisper recites its prompt
+#: over silence), and the prompt-echo guard ignores them for the same reason.
+DEFAULT_TERMS: tuple[DefaultTerm, ...] = (
+ DefaultTerm(
+ "dodaios",
+ "Dodaios",
+ ("the Dios", "Doda iOS", "Doda ios", "Dodai OS", "Dodaius", "Dodayos"),
+ ),
+ DefaultTerm("pypi", "PyPI", ("Pipey", "Pipe-I", "Pai-Pi"), fuzzy=False),
+ DefaultTerm("github", "GitHub", ("Git Hub", "Git-Hub")),
+ DefaultTerm("prs", "PRs", ("PR's", "P.R.s")),
+ DefaultTerm("bugs", "Bugs", ("Baggen",), casing=False),
+)
+
+_DEFAULTS_BY_ID: dict[str, DefaultTerm] = {t.entry_id: t for t in DEFAULT_TERMS}
+
+
+def active_default_entries(
+ user_entries: list[DictionaryEntry],
+ removed: frozenset[str] | set[str] = frozenset(),
+ defaults: tuple[DefaultTerm, ...] = DEFAULT_TERMS,
+) -> list[DictionaryEntry]:
+ """The shipped defaults still in force next to ``user_entries``.
+
+ A default steps aside for the user in every way they can express it: they
+ deleted it (``removed``), edited it (their copy carries its id), added the
+ same word themselves, or listed the word as a mishearing of something else.
+ A default VARIANT that is one of the user's own words or spellings is
+ dropped, so the user's rule is the only one for that spelling.
+ """
+ user_ids = {e.id for e in user_entries}
+ taken = {e.word.casefold() for e in user_entries} | {
+ v.casefold() for e in user_entries for v in e.misheard
+ }
+ out: list[DictionaryEntry] = []
+ for term in defaults:
+ entry_id = term.entry_id
+ if entry_id in removed or entry_id in user_ids:
+ continue
+ if term.word.casefold() in taken:
+ continue
+ out.append(
+ DictionaryEntry(
+ id=entry_id,
+ word=term.word,
+ misheard=tuple(v for v in term.misheard if v.casefold() not in taken),
+ default=True,
+ casing=term.casing,
+ fuzzy=term.fuzzy,
+ )
+ )
+ return out
+
def _now_iso() -> str:
return datetime.now(UTC).isoformat(timespec="seconds")
@@ -220,16 +338,48 @@ class DictionaryStore:
# -- read ----------------------------------------------------------
- def list_all(self) -> list[DictionaryEntry]:
+ def _load(self) -> tuple[list[DictionaryEntry], frozenset[str]]:
+ """``(user entries, ids of the shipped defaults the user deleted)``."""
try:
raw = json.loads(self._path.read_text(encoding="utf-8"))
except FileNotFoundError:
- return []
+ return [], frozenset()
except Exception as exc: # noqa: BLE001 — a corrupt sidecar must never crash voice
log.warning("STT dictionary unreadable (%s); treating as empty.", exc)
- return []
+ return [], frozenset()
+ if not isinstance(raw, dict):
+ return [], frozenset()
+ removed_raw = raw.get("removed_defaults", [])
+ removed = frozenset(
+ item
+ for item in (removed_raw if isinstance(removed_raw, list) else [])
+ if isinstance(item, str) and item.startswith(DEFAULT_ID_PREFIX)
+ )
+ return self._parse_entries(raw), removed
+
+ def list_all(self) -> list[DictionaryEntry]:
+ """The USER's entries, as stored. Shipped defaults are not included."""
+ return self._load()[0]
+
+ def removed_defaults(self) -> frozenset[str]:
+ """Ids of the shipped defaults the user deleted."""
+ return self._load()[1]
+
+ def effective_entries(self) -> list[DictionaryEntry]:
+ """User entries followed by the shipped defaults still in force.
+
+ This is what corrects transcripts and what the Dictionary view lists.
+ """
+ user, removed = self._load()
+ return user + active_default_entries(user, removed)
+
+ @staticmethod
+ def _parse_entries(raw: dict[str, Any]) -> list[DictionaryEntry]:
entries: list[DictionaryEntry] = []
- for item in raw.get("entries", []) if isinstance(raw, dict) else []:
+ items = raw.get("entries", [])
+ for item in items if isinstance(items, list) else []:
+ if not isinstance(item, dict):
+ continue
try:
word = _clean_word(str(item.get("word", "")))
entries.append(
@@ -246,7 +396,7 @@ class DictionaryStore:
return entries
def get(self, entry_id: str) -> DictionaryEntry | None:
- for entry in self.list_all():
+ for entry in self.effective_entries():
if entry.id == entry_id:
return entry
return None
@@ -279,7 +429,31 @@ class DictionaryStore:
misheard: Any = None,
misheard_set: bool = False,
) -> DictionaryEntry | None:
- entries = self.list_all()
+ entries, removed = self._load()
+ if not any(e.id == entry_id for e in entries):
+ # Editing a shipped default turns it into the user's own entry,
+ # under the same id, so a second edit in flight still finds it and
+ # the default stays hidden behind it from then on.
+ default = next(
+ (
+ d
+ for d in active_default_entries(entries, removed)
+ if d.id == entry_id
+ ),
+ None,
+ )
+ if default is None:
+ return None
+ now = _now_iso()
+ entries = entries + [
+ DictionaryEntry(
+ id=default.id,
+ word=default.word,
+ misheard=default.misheard,
+ created_at=now,
+ updated_at=now,
+ )
+ ]
for i, entry in enumerate(entries):
if entry.id != entry_id:
continue
@@ -307,15 +481,29 @@ class DictionaryStore:
return None
def delete(self, entry_id: str) -> bool:
- entries = self.list_all()
+ entries, removed = self._load()
kept = [e for e in entries if e.id != entry_id]
- if len(kept) == len(entries):
+ newly_removed = entry_id in _DEFAULTS_BY_ID and entry_id not in removed
+ if len(kept) == len(entries) and not newly_removed:
return False
- self._write(kept)
+ # A deleted default must stay deleted — also when the user had edited
+ # it first, which made it their entry under the default's id.
+ self._write(kept, removed | {entry_id} if newly_removed else removed)
return True
- def _write(self, entries: list[DictionaryEntry]) -> None:
- payload = {"version": 1, "entries": [e.to_dict() for e in entries]}
+ def _write(
+ self,
+ entries: list[DictionaryEntry],
+ removed_defaults: frozenset[str] | set[str] | None = None,
+ ) -> None:
+ if removed_defaults is None:
+ removed_defaults = self.removed_defaults()
+ payload: dict[str, Any] = {
+ "version": 1,
+ "entries": [e.to_storage() for e in entries],
+ }
+ if removed_defaults:
+ payload["removed_defaults"] = sorted(removed_defaults)
self._path.parent.mkdir(parents=True, exist_ok=True)
# Atomic tempfile + os.replace so a crash mid-write never leaves a
# torn sidecar (same discipline as the config writer, AP-7).
@@ -457,7 +645,15 @@ def _splice_out_run(before: str, after: str) -> str:
class TranscriptCorrector:
"""Compiled correction rules over a fixed snapshot of entries."""
- def __init__(self, entries: list[DictionaryEntry]) -> None:
+ def __init__(
+ self,
+ entries: list[DictionaryEntry],
+ *,
+ echo_entries: list[DictionaryEntry] | None = None,
+ ) -> None:
+ """``echo_entries`` are the words a decoder was actually primed with —
+ the only ones whose run can be a recited prompt. ``None`` means all of
+ ``entries`` (the historical behaviour)."""
# Explicit misheard → word replacements, longest source first so an
# overlapping shorter rule never shadows a longer phrase.
self._replacements: list[tuple[re.Pattern[str], str]] = []
@@ -473,6 +669,7 @@ class TranscriptCorrector:
self._casing: list[tuple[re.Pattern[str], str]] = [
(_boundary_pattern(e.word), e.word)
for e in sorted(entries, key=lambda e: len(e.word), reverse=True)
+ if e.casing
]
# Fuzzy-repair index for SINGLE-token canonical words, keyed by the
@@ -483,6 +680,8 @@ class TranscriptCorrector:
for entry in entries:
word = entry.word
self._canonical_tokens.add(word.casefold())
+ if not entry.casing or not entry.fuzzy:
+ continue
if " " in word or len(word) < _FUZZY_MIN_TOKEN_LEN:
continue
if not word[0].isalpha():
@@ -491,7 +690,9 @@ class TranscriptCorrector:
self._fuzzy_index.setdefault(fold[:1], []).append((word, fold))
self._token_re = re.compile(r"[^\W\d_][\w''\-]*", re.UNICODE)
- self._echo_run_re, self._echo_item_re = _compile_echo_patterns(entries)
+ self._echo_run_re, self._echo_item_re = _compile_echo_patterns(
+ entries if echo_entries is None else echo_entries
+ )
self.rule_count = len(self._replacements) + len(self._casing)
def strip_prompt_echo(self, text: str) -> str:
@@ -624,14 +825,18 @@ def get_corrector(store: DictionaryStore | None = None) -> TranscriptCorrector:
or fresh_path
or signature != _cached_signature
):
- entries = (store or DictionaryStore(path)).list_all()
- _cached_corrector = TranscriptCorrector(entries)
+ user, removed = (store or DictionaryStore(path))._load()
+ entries = user + active_default_entries(user, removed)
+ # Only the user's words are ever primed into a decoder
+ # (``dictionary_bias_words``), so only they can be "recited".
+ _cached_corrector = TranscriptCorrector(entries, echo_entries=user)
_cached_signature = signature
_cached_path = path
- if entries:
+ if user:
log.info(
- "STT dictionary loaded: %d entries, %d rules.",
- len(entries),
+ "STT dictionary loaded: %d entries (+%d defaults), %d rules.",
+ len(user),
+ len(entries) - len(user),
_cached_corrector.rule_count,
)
return _cached_corrector
@@ -654,6 +859,16 @@ def dictionary_bias_words(store: DictionaryStore | None = None) -> list[str]:
return words
+def dictionary_protected_words(store: DictionaryStore | None = None) -> list[str]:
+ """Every word the dictionary stands for, shipped defaults included.
+
+ For the dictation polish pass, which must not "correct" these spellings
+ into something familiar. Unlike :func:`dictionary_bias_words` this is not
+ a decoder prompt, so the defaults belong here.
+ """
+ return [entry.word for entry in (store or DictionaryStore()).effective_entries()]
+
+
# ----------------------------------------------------------------------
# Provider wrapper
# ----------------------------------------------------------------------
@@ -777,8 +992,13 @@ def wrap_stt_with_dictionary(provider: Any) -> Any:
__all__ = [
+ "DEFAULT_ID_PREFIX",
+ "DEFAULT_TERMS",
+ "DefaultTerm",
"DictionaryEntry",
"DictionaryStore",
+ "active_default_entries",
+ "dictionary_protected_words",
"TranscriptCorrector",
"DictionaryCorrectingSTT",
"dictionary_bias_words",
diff --git a/dodaios/speech/stt_fallback.py b/dodaios/speech/stt_fallback.py
index 6886746524..cce4aaf7b1 100644
--- a/dodaios/speech/stt_fallback.py
+++ b/dodaios/speech/stt_fallback.py
@@ -30,6 +30,7 @@ What it does NOT do, on purpose:
from __future__ import annotations
import asyncio
+import contextlib
import logging
import time
from collections.abc import AsyncIterator, Sequence
@@ -51,6 +52,48 @@ TRANSIENT_COOLDOWN_S = 15.0
#: both need real time to change; a 5xx or a dropped connection does not.
_LONG_COOLDOWN_REASONS = frozenset({"rate_limited", "no_credit", "bad_key"})
+#: Per-provider deadline, as a multiple of the audio sent. Matches the dictation
+#: lane's own per-call ceiling, so a call that used to succeed on the provider in
+#: front still does; only one that used to run out the WHOLE ceiling now crosses.
+PROVIDER_DEADLINE_PER_AUDIO_S = 2.0
+
+
+class ProviderDeadlineExceeded(RuntimeError):
+ """A provider with another one behind it did not answer within its deadline.
+
+ Live bug 2026-10-20 17:35: the on-device final pass hung on 1.9 s of audio,
+ the dictation lane's single 8 s ceiling around the WHOLE chain ran out while
+ the chain was still waiting on it, and the cloud provider behind it never
+ got the audio — 0 characters, although a working fallback was keyed. The
+ chain now bounds every provider that is not the last one, so a wedge costs
+ its own deadline and then crosses.
+
+ Carries ``status = 503`` so :func:`dodaios.speech.stt_failure.classify_stt_failure`
+ reads it as ``unavailable`` — crossable, and transient to the dictation
+ retry ladder. It is deliberately NOT a ``TimeoutError``: that type means the
+ lane's own outer ceiling ran out (a wedge of the LAST provider), which the
+ ladder refuses to retry; this one means "the next provider has not been
+ asked yet".
+ """
+
+ status = 503
+
+
+def audio_seconds(pcm: object, sample_rate: object = 16_000) -> float:
+ """Duration of int16 mono PCM ``pcm``; ``0.0`` for anything that is not bytes."""
+ if not isinstance(pcm, (bytes, bytearray, memoryview)):
+ return 0.0
+ try:
+ rate = int(sample_rate or 16_000)
+ except (TypeError, ValueError): # an unusable rate means the 16 kHz default
+ rate = 16_000
+ return len(pcm) / float(max(1, rate) * 2)
+
+
+def provider_deadline_s(audio_s: float, floor_s: float) -> float:
+ """How long ONE provider in front of another gets for ``audio_s`` of audio."""
+ return max(float(floor_s), max(0.0, float(audio_s)) * PROVIDER_DEADLINE_PER_AUDIO_S)
+
def _classify(exc: BaseException) -> str:
"""The failure reason when another provider deserves a shot, else ``""``.
@@ -94,9 +137,18 @@ class FallbackSTT:
build: Any,
*,
primary_name: str = "",
+ provider_deadline_floor_s: float | None = None,
) -> None:
self._primary = primary
self._primary_name = primary_name or type(primary).__name__
+ # ``None`` keeps the historical behaviour (the caller's own ceiling is
+ # the only bound). A number arms per-provider deadlines on
+ # ``transcribe_pcm`` for every provider that has another one behind it.
+ self._deadline_floor_s = (
+ None
+ if provider_deadline_floor_s is None
+ else max(0.1, float(provider_deadline_floor_s))
+ )
self._alternate_names = list(alternates)
self._build = build
# name -> instance, built on first use and kept for the process.
@@ -138,6 +190,22 @@ class FallbackSTT:
"""
return bool(getattr(self._primary, "supports_concurrent_requests", False))
+ def crossing_reserve_s(self, audio_s: float) -> float:
+ """Extra wall-clock time a caller's ceiling must allow for crossing.
+
+ Each provider in front of another may use up to its own deadline before
+ the chain moves on, so a caller that bounds the whole call with ONE
+ provider's worth of time cuts the chain off exactly where it was about
+ to cross — the 2026-10-20 lost dictation. The caller adds this to its
+ own per-call ceiling; the last provider keeps that ceiling for itself.
+ ``0.0`` when the chain does not arm deadlines or has nowhere to cross.
+ """
+ if self._deadline_floor_s is None or not self._alternate_names:
+ return 0.0
+ return provider_deadline_s(audio_s, self._deadline_floor_s) * len(
+ self._alternate_names
+ )
+
@property
def last_used_provider(self) -> str:
"""Which provider produced the most recent transcript."""
@@ -222,10 +290,72 @@ class FallbackSTT:
# ------------------------------------------------------------------
# Transcription
# ------------------------------------------------------------------
- async def _call(self, method: str, *args: Any, **kwargs: Any) -> Any:
+ async def _invoke(self, name: str, provider: Any, fn: Any, args: Any, kwargs: Any) -> Any:
+ if getattr(provider, "supports_concurrent_requests", False):
+ return await fn(*args, **kwargs)
+ lock = self._serial_locks.setdefault(name, asyncio.Lock())
+ async with lock:
+ return await fn(*args, **kwargs)
+
+ async def _invoke_bounded(
+ self,
+ name: str,
+ provider: Any,
+ fn: Any,
+ args: Any,
+ kwargs: Any,
+ deadline_s: float,
+ audio_s: float,
+ ) -> Any:
+ """``_invoke`` with a deadline that ends in a CROSSABLE failure.
+
+ The wait for a serial provider's lock is inside the deadline on
+ purpose: queueing behind a wedged call is the same wedge. A provider's
+ OWN timeout exception (aiohttp raises ``TimeoutError``) still reaches
+ the classifier unchanged — only this chain's deadline becomes
+ :class:`ProviderDeadlineExceeded`.
+ """
+ task = asyncio.ensure_future(self._invoke(name, provider, fn, args, kwargs))
+ try:
+ done, _pending = await asyncio.wait({task}, timeout=deadline_s)
+ except asyncio.CancelledError:
+ task.cancel()
+ with contextlib.suppress(BaseException):
+ await task
+ raise
+ if task in done:
+ return task.result()
+ # Cancelling is what lets an on-device worker replace itself (AP-24:
+ # a wedged native engine is recovered by killing it, never by waiting).
+ task.cancel()
+ try:
+ late = await task
+ except asyncio.CancelledError:
+ current = asyncio.current_task()
+ if current is not None and current.cancelling():
+ raise
+ except Exception as exc: # noqa: BLE001 — the late failure is moot now
+ log.debug("STT fallback: %s ended after its deadline (%s)", name, exc)
+ else:
+ # It finished in the instant between the deadline and the cancel:
+ # a real transcript is never thrown away to make a point.
+ return late
+ raise ProviderDeadlineExceeded(
+ f"{name} did not answer within {deadline_s:.0f}s for "
+ f"{audio_s:.1f}s of audio; the next provider takes it"
+ )
+
+ async def _call(
+ self,
+ method: str,
+ *args: Any,
+ _deadline_audio_s: float | None = None,
+ **kwargs: Any,
+ ) -> Any:
first_error: BaseException | None = None
self._last_failure = None
- for name, preloaded in self._order():
+ order = self._order()
+ for index, (name, preloaded) in enumerate(order):
try:
provider = preloaded if preloaded is not None else self._instance(name)
except Exception as exc: # noqa: BLE001 — an unbuildable alternate is skipped
@@ -235,13 +365,27 @@ class FallbackSTT:
fn = getattr(provider, method, None)
if fn is None:
continue
+ # Only a provider with another one BEHIND it is bounded here. The
+ # last one keeps the caller's ceiling for itself: there is nowhere
+ # left to cross, and cutting it short would only lose the words.
+ floor_s = self._deadline_floor_s
try:
- if getattr(provider, "supports_concurrent_requests", False):
- result = await fn(*args, **kwargs)
+ if (
+ floor_s is not None
+ and _deadline_audio_s is not None
+ and index < len(order) - 1
+ ):
+ result = await self._invoke_bounded(
+ name,
+ provider,
+ fn,
+ args,
+ kwargs,
+ provider_deadline_s(_deadline_audio_s, floor_s),
+ _deadline_audio_s,
+ )
else:
- lock = self._serial_locks.setdefault(name, asyncio.Lock())
- async with lock:
- result = await fn(*args, **kwargs)
+ result = await self._invoke(name, provider, fn, args, kwargs)
except Exception as exc: # noqa: BLE001 — classified below
kind = _classify(exc)
if not kind:
@@ -271,7 +415,13 @@ class FallbackSTT:
raise RuntimeError("No speech-to-text provider was able to transcribe.")
async def transcribe_pcm(self, *args: Any, **kwargs: Any) -> Any:
- return await self._call("transcribe_pcm", *args, **kwargs)
+ audio_s: float | None = None
+ if self._deadline_floor_s is not None and args:
+ rate = args[1] if len(args) > 1 else kwargs.get("sample_rate", 16_000)
+ audio_s = audio_seconds(args[0], rate)
+ return await self._call(
+ "transcribe_pcm", *args, _deadline_audio_s=audio_s, **kwargs
+ )
async def transcribe(self, *args: Any, **kwargs: Any) -> Any:
return await self._call("transcribe", *args, **kwargs)
@@ -363,9 +513,13 @@ def wrap_stt_with_fallback(provider: Any, stt_cfg: Any) -> Any:
__all__ = [
"FallbackSTT",
+ "PROVIDER_DEADLINE_PER_AUDIO_S",
+ "ProviderDeadlineExceeded",
"RATE_LIMIT_COOLDOWN_S",
"TRANSIENT_COOLDOWN_S",
"alternate_provider_names",
+ "audio_seconds",
+ "provider_deadline_s",
"configured_fallback_names",
"wrap_stt_with_fallback",
]
diff --git a/dodaios/ui/web/dictionary_routes.py b/dodaios/ui/web/dictionary_routes.py
index 7c62e4e58b..62612fbbaf 100644
--- a/dodaios/ui/web/dictionary_routes.py
+++ b/dodaios/ui/web/dictionary_routes.py
@@ -2,10 +2,14 @@
Endpoints (mounted by the WebServer in ``_build_app()``):
- GET /api/dictionary → {"entries": [entry, ...]} in insertion order.
+ GET /api/dictionary → {"entries": [entry, ...]}: the user's
+ entries in insertion order, then the shipped
+ defaults still in force (``"default": true``).
POST /api/dictionary → create one entry; 201 (400 on duplicate).
- PATCH /api/dictionary/{id} → partial edit; returns the entry; 404.
- DELETE /api/dictionary/{id} → remove (idempotent → 200, {"removed": bool}).
+ PATCH /api/dictionary/{id} → partial edit; returns the entry; 404. Editing
+ a default makes it the user's own entry.
+ DELETE /api/dictionary/{id} → remove (idempotent → 200, {"removed": bool});
+ a deleted default stays deleted.
An entry is one canonical ``word`` plus optional ``misheard`` variants — see
``dodaios/speech/stt_dictionary.py``. Storage is the atomic JSON sidecar under
@@ -65,7 +69,7 @@ class EntryUpdate(BaseModel):
@router.get("")
def list_entries() -> dict[str, Any]:
with _LOCK:
- entries = _store().list_all()
+ entries = _store().effective_entries()
return {"entries": [e.to_dict() for e in entries]}
diff --git a/tests/fakes/fake_stt_providers.py b/tests/fakes/fake_stt_providers.py
new file mode 100644
index 0000000000..8add8c473e
--- /dev/null
+++ b/tests/fakes/fake_stt_providers.py
@@ -0,0 +1,113 @@
+"""Speech-to-text provider doubles for the dictation lane and the fallback chain.
+
+Each one honours the ``transcribe_pcm(pcm, language=...)`` contract the chain
+and the lane call, and records what happened to it so a test can assert on the
+provider's side of the story (asked? cancelled? how often?).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from dodaios.core.protocols import Transcript
+
+
+class AnsweringSTT:
+ """Answers every call with ``text``."""
+
+ supports_concurrent_requests = True
+
+ def __init__(self, text: str, *, language: str = "en") -> None:
+ self.text = text
+ self.language = language
+ self.calls = 0
+ self.audio_bytes: list[int] = []
+
+ async def transcribe_pcm(
+ self, pcm: bytes, sample_rate: int = 16_000, language: str | None = None
+ ) -> Transcript:
+ self.calls += 1
+ self.audio_bytes.append(len(pcm))
+ return Transcript(text=self.text, language=self.language, confidence=0.9)
+
+
+class FailingSTT:
+ """Raises ``error`` on every call."""
+
+ supports_concurrent_requests = True
+
+ def __init__(self, error: BaseException) -> None:
+ self.error = error
+ self.calls = 0
+
+ async def transcribe_pcm(
+ self, pcm: bytes, sample_rate: int = 16_000, language: str | None = None
+ ) -> Transcript:
+ self.calls += 1
+ raise self.error
+
+
+class WedgedSTT:
+ """The 2026-10-20 local worker: takes the call and never answers.
+
+ Serial like the on-device engine (``supports_concurrent_requests`` False),
+ so the chain routes it through its per-provider lock.
+ """
+
+ supports_concurrent_requests = False
+ runs_on_device = True
+
+ def __init__(self) -> None:
+ self.calls = 0
+ self.cancelled = 0
+
+ async def transcribe_pcm(
+ self, pcm: bytes, sample_rate: int = 16_000, language: str | None = None
+ ) -> Transcript:
+ self.calls += 1
+ try:
+ await asyncio.sleep(3600)
+ except asyncio.CancelledError:
+ self.cancelled += 1
+ raise
+ raise AssertionError("unreachable") # pragma: no cover
+
+
+class SlowSTT:
+ """Answers ``text`` after ``delay_s`` — slow, but not wedged."""
+
+ supports_concurrent_requests = True
+
+ def __init__(self, text: str, delay_s: float) -> None:
+ self.text = text
+ self.delay_s = delay_s
+ self.calls = 0
+
+ async def transcribe_pcm(
+ self, pcm: bytes, sample_rate: int = 16_000, language: str | None = None
+ ) -> Transcript:
+ self.calls += 1
+ await asyncio.sleep(self.delay_s)
+ return Transcript(text=self.text, language="en", confidence=0.9)
+
+
+class RecordingBuilder:
+ """``FallbackSTT``'s ``build`` callable over a fixed name → provider map."""
+
+ def __init__(self, providers: dict[str, Any]) -> None:
+ self._providers = dict(providers)
+ self.built: list[str] = []
+
+ def __call__(self, name: str) -> Any:
+ self.built.append(name)
+ return self._providers[name]
+
+
+__all__ = [
+ "AnsweringSTT",
+ "FailingSTT",
+ "RecordingBuilder",
+ "SlowSTT",
+ "WedgedSTT",
+]
diff --git a/tests/unit/dictation/test_dictation_crossing_deadline.py b/tests/unit/dictation/test_dictation_crossing_deadline.py
new file mode 100644
index 0000000000..4751b063d1
--- /dev/null
+++ b/tests/unit/dictation/test_dictation_crossing_deadline.py
@@ -0,0 +1,329 @@
+"""A finished dictation must reach the next provider when the one in front hangs.
+
+Live bug 2026-10-20 17:35 (``data/jarvis_desktop.log``): the on-device final
+pass hung on 1.9 s of audio. The dictation lane bounded the WHOLE provider chain
+with one provider's worth of time (8 s), so the ceiling ran out while the chain
+was still waiting on the local worker; the keyed cloud provider behind it never
+got the audio, the ladder called our own timeout "not a failure a second attempt
+survives", and the dictation ended with 0 characters. Three seconds later the
+next press crossed to the cloud and was transcribed in 0.5 s.
+
+These tests lock the three halves of the fix:
+
+* the chain bounds every provider that has another one behind it and crosses
+ when that deadline passes (``ProviderDeadlineExceeded``, crossable and
+ retryable — never the lane's own ``TimeoutError``);
+* the lane widens its own ceiling by the chain's crossing reserve, so the
+ crossing does not eat the next provider's time;
+* when every provider fails, the notice says the audio was kept for Restore.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+import dodaios.speech.pipeline as pipeline_module
+import dodaios.speech.stt_fallback as fallback_module
+from dodaios.core.config import DictationConfig
+from dodaios.core.events import DictationCompleted
+from dodaios.speech.pipeline import (
+ SpeechPipeline,
+ _dictation_retry_worthwhile,
+ _stt_crossing_reserve_s,
+)
+from dodaios.speech.stt_failure import classify_stt_failure, is_crossable_failure
+from dodaios.speech.stt_fallback import (
+ FallbackSTT,
+ ProviderDeadlineExceeded,
+ audio_seconds,
+ provider_deadline_s,
+)
+from tests.fakes.fake_stt_providers import (
+ AnsweringSTT,
+ FailingSTT,
+ RecordingBuilder,
+ SlowSTT,
+ WedgedSTT,
+)
+
+BYTES_PER_SECOND = 16_000 * 2
+
+
+def _chain(primary: Any, floor_s: float | None, **alternates: Any) -> FallbackSTT:
+ return FallbackSTT(
+ primary,
+ list(alternates),
+ RecordingBuilder(alternates),
+ primary_name="faster-whisper",
+ provider_deadline_floor_s=floor_s,
+ )
+
+
+# --------------------------------------------------------------------------
+# The chain's own deadline
+# --------------------------------------------------------------------------
+
+
+async def test_a_wedged_provider_in_front_crosses_to_the_next_one() -> None:
+ local = WedgedSTT()
+ cloud = AnsweringSTT("the words")
+ chain = _chain(local, 0.05, **{"groq-api": cloud})
+
+ result = await asyncio.wait_for(
+ chain.transcribe_pcm(b"\x00" * BYTES_PER_SECOND, language="auto"), timeout=5
+ )
+
+ assert result.text == "the words"
+ assert chain.last_used_provider == "groq-api"
+ assert local.cancelled == 1, "the wedged call must be cancelled, not left running"
+ assert cloud.calls == 1
+
+
+async def test_the_wedged_provider_is_skipped_on_the_next_call() -> None:
+ """After a wedge the chain must not make the next press wait it out again."""
+ local = WedgedSTT()
+ cloud = AnsweringSTT("again")
+ chain = _chain(local, 0.05, **{"groq-api": cloud})
+
+ await chain.transcribe_pcm(b"\x00" * 3200)
+ await asyncio.wait_for(chain.transcribe_pcm(b"\x00" * 3200), timeout=0.04)
+
+ assert local.calls == 1
+ assert cloud.calls == 2
+
+
+async def test_the_last_provider_is_never_cut_short_by_the_chain() -> None:
+ """With nowhere to cross, a deadline would only lose the words."""
+ only = SlowSTT("slow but right", delay_s=0.1)
+ chain = _chain(only, 0.01)
+
+ result = await chain.transcribe_pcm(b"\x00" * 3200)
+
+ assert result.text == "slow but right"
+
+
+async def test_a_chain_without_deadlines_keeps_the_old_behaviour() -> None:
+ slow = SlowSTT("primary", delay_s=0.1)
+ cloud = AnsweringSTT("fallback")
+ chain = _chain(slow, None, **{"groq-api": cloud})
+
+ result = await chain.transcribe_pcm(b"\x00" * 3200)
+
+ assert result.text == "primary"
+ assert cloud.calls == 0
+ assert chain.crossing_reserve_s(10.0) == 0.0
+
+
+async def test_a_slow_provider_inside_its_deadline_still_answers() -> None:
+ """The deadline matches the lane's old ceiling: a call that used to succeed
+ on the provider in front must not now be sent to a paid fallback."""
+ slow = SlowSTT("local", delay_s=0.05)
+ cloud = AnsweringSTT("cloud")
+ chain = _chain(slow, 1.0, **{"groq-api": cloud})
+
+ result = await chain.transcribe_pcm(b"\x00" * 3200)
+
+ assert result.text == "local"
+ assert cloud.calls == 0
+
+
+async def test_the_deadline_scales_with_the_audio(monkeypatch: pytest.MonkeyPatch) -> None:
+ assert provider_deadline_s(1.9, 8.0) == 8.0
+ assert provider_deadline_s(25.0, 8.0) == pytest.approx(50.0)
+ assert audio_seconds(b"\x00" * BYTES_PER_SECOND) == pytest.approx(1.0)
+ assert audio_seconds(b"\x00" * 16_000, 8_000) == pytest.approx(1.0)
+ assert audio_seconds("not audio") == 0.0
+
+ chain = _chain(AnsweringSTT("x"), 8.0, **{"groq-api": AnsweringSTT("y")})
+ assert chain.crossing_reserve_s(1.9) == pytest.approx(8.0)
+ assert chain.crossing_reserve_s(25.0) == pytest.approx(50.0)
+ two = _chain(
+ AnsweringSTT("x"),
+ 8.0,
+ **{"groq-api": AnsweringSTT("y"), "openai-api": AnsweringSTT("z")},
+ )
+ assert two.crossing_reserve_s(1.9) == pytest.approx(16.0)
+
+
+async def test_every_provider_failing_surfaces_the_first_failure() -> None:
+ local = WedgedSTT()
+ cloud = FailingSTT(RuntimeError("HTTP 503 Service Unavailable"))
+ chain = _chain(local, 0.05, **{"groq-api": cloud})
+
+ with pytest.raises(ProviderDeadlineExceeded):
+ await chain.transcribe_pcm(b"\x00" * 3200)
+ assert cloud.calls == 1
+
+
+def test_the_chain_deadline_is_crossable_and_worth_a_retry() -> None:
+ """The crossing must never read as "not a failure a second attempt survives"."""
+ exc = ProviderDeadlineExceeded("faster-whisper did not answer within 8s")
+
+ assert classify_stt_failure(exc) == "unavailable"
+ assert is_crossable_failure(classify_stt_failure(exc))
+ assert _dictation_retry_worthwhile(exc) is True
+ # The lane's OWN ceiling stays a wedge of the last provider: not retried.
+ assert _dictation_retry_worthwhile(TimeoutError()) is False
+
+
+def test_the_reserve_is_read_through_transparent_wrappers() -> None:
+ chain = _chain(AnsweringSTT("x"), 8.0, **{"groq-api": AnsweringSTT("y")})
+
+ class _Wrapper:
+ def __init__(self, inner: Any) -> None:
+ self._inner = inner
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._inner, name)
+
+ assert _stt_crossing_reserve_s(_Wrapper(chain), 1.9) == pytest.approx(8.0)
+ assert _stt_crossing_reserve_s(AnsweringSTT("plain"), 1.9) == 0.0
+
+
+# --------------------------------------------------------------------------
+# The whole lane — the 2026-10-20 17:35 dictation, replayed
+# --------------------------------------------------------------------------
+
+
+class _Chunk:
+ def __init__(self, pcm: bytes) -> None:
+ self.pcm = pcm
+ self.timestamp_ns = 0
+
+
+class _FakeMic:
+ def __init__(self, seconds: float) -> None:
+ self._pcm = b"\x11\x22" * int(16_000 * seconds)
+
+ async def stream(self): # noqa: ANN201 — an async generator of chunks
+ yield _Chunk(self._pcm)
+ await asyncio.sleep(3600)
+
+
+class _NullCapture:
+ def __init__(self, source: Any) -> None:
+ self._source = source
+
+ async def __aenter__(self) -> Any:
+ return self._source
+
+ async def __aexit__(self, *exc: object) -> bool:
+ return False
+
+
+def _session_pipeline(stt: Any, *, seconds: float, history_enabled: bool = False):
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_cfg = DictationConfig(
+ history_enabled=history_enabled,
+ segment_seconds=0.0,
+ partial_interval_s=0.0,
+ polish=False,
+ )
+ pipe._dictation_target = "chat"
+ pipe._dictation_completion_published = False
+ pipe._dictation_max_s = 30.0
+ pipe._dictation_stt_instance = stt
+ pipe._stt_final_timeout_s = 0.3
+ pipe._hangup_event = asyncio.Event()
+ pipe._dictation_stop_event = asyncio.Event()
+ events: list[object] = []
+ recorded: list[dict[str, Any]] = []
+
+ async def _publish(event: object) -> None:
+ events.append(event)
+
+ def _publish_soon(event: object) -> None:
+ events.append(event)
+
+ async def _record(**kwargs: Any) -> None:
+ # Stands in for the history store: the test must never write a real
+ # history row or audio sidecar.
+ recorded.append(kwargs)
+
+ pipe._publish_event = _publish # type: ignore[assignment]
+ pipe._publish_event_soon = _publish_soon # type: ignore[assignment]
+ pipe._record_dictation = _record # type: ignore[assignment]
+ pipe._capture_dictation_input = lambda: _NullCapture(_FakeMic(seconds)) # type: ignore[assignment]
+ pipe._insert_dictation = lambda text: SimpleNamespace( # type: ignore[assignment]
+ status="inserted", detail="", method="clipboard+ctrl_v"
+ )
+
+ async def _stop_live(task, **_kwargs): # noqa: ANN001, ANN202
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
+
+ pipe._stop_ptt_live_transcription = _stop_live # type: ignore[assignment]
+ return pipe, events, recorded
+
+
+async def _run_session(pipe: Any) -> None:
+ task = asyncio.create_task(pipe._dictation_session())
+ await asyncio.sleep(0)
+ pipe._dictation_stop_event.set()
+ await asyncio.wait_for(task, timeout=30)
+
+
+def _completed(events: list[object]) -> DictationCompleted:
+ return next(e for e in events if isinstance(e, DictationCompleted))
+
+
+def short_ceilings(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Production's formulas with small multipliers, so a wedge costs ~0.3 s."""
+ monkeypatch.setattr(pipeline_module, "_DICTATION_TRANSCRIBE_TIMEOUT_PER_AUDIO_S", 0.1)
+ monkeypatch.setattr(fallback_module, "PROVIDER_DEADLINE_PER_AUDIO_S", 0.1)
+
+
[email protected]("short_ceilings")
+async def test_a_hung_local_pass_no_longer_loses_the_dictation() -> None:
+ """REGRESSION 2026-10-20 17:35: 0 characters although the cloud was keyed."""
+ local = WedgedSTT()
+ cloud = AnsweringSTT("Bitte die Bugs auf PyPI fixen") # i18n-allow: German fixture
+ # Same floor the lane arms its own chain with (``_stt_final_timeout_s``).
+ chain = _chain(local, 0.3, **{"groq-api": cloud})
+ pipe, events, _recorded = _session_pipeline(chain, seconds=1.0)
+
+ await _run_session(pipe)
+
+ completed = _completed(events)
+ assert completed.text == "Bitte die Bugs auf PyPI fixen" # i18n-allow: German fixture
+ assert completed.outcome != "failed"
+ assert local.cancelled == 1
+ assert cloud.calls >= 1
+
+
[email protected]("short_ceilings")
+async def test_every_provider_failing_says_the_audio_was_kept() -> None:
+ local = WedgedSTT()
+ cloud = FailingSTT(RuntimeError("HTTP 503 Service Unavailable"))
+ chain = _chain(local, 0.3, **{"groq-api": cloud})
+ pipe, events, recorded = _session_pipeline(chain, seconds=1.0, history_enabled=True)
+
+ await _run_session(pipe)
+
+ completed = _completed(events)
+ assert completed.outcome == "failed"
+ assert completed.error == "unavailable"
+ assert "Restore" in completed.detail
+ assert recorded, "a failed dictation must reach the history (Restore starts there)"
+ assert recorded[-1]["outcome_name"] == "failed"
+ assert recorded[-1]["audio"], "the captured audio must be handed over to be kept"
+
+
[email protected]("short_ceilings")
+async def test_no_restore_promise_when_nothing_is_kept() -> None:
+ cloud = FailingSTT(RuntimeError("HTTP 503 Service Unavailable"))
+ chain = _chain(WedgedSTT(), 0.3, **{"groq-api": cloud})
+ pipe, events, _recorded = _session_pipeline(chain, seconds=1.0, history_enabled=False)
+
+ await _run_session(pipe)
+
+ completed = _completed(events)
+ assert completed.outcome == "failed"
+ assert "Restore" not in completed.detail
diff --git a/tests/unit/dictation/test_stt_retry_and_isolation.py b/tests/unit/dictation/test_stt_retry_and_isolation.py
index 3ff253545f..2dd2fb2725 100644
--- a/tests/unit/dictation/test_stt_retry_and_isolation.py
+++ b/tests/unit/dictation/test_stt_retry_and_isolation.py
@@ -491,7 +491,9 @@ def test_protected_terms_carry_the_words_the_user_chose(
duplicates — a repeated term is a wasted slot in a bounded prompt."""
import dodaios.speech.stt_dictionary as dictionary
- monkeypatch.setattr(dictionary, "dictionary_bias_words", lambda: ["Vokando", "Adex"])
+ monkeypatch.setattr(
+ dictionary, "dictionary_protected_words", lambda: ["Vokando", "Adex"]
+ )
pipe = SpeechPipeline.__new__(SpeechPipeline)
pipe._wake_phrase_label = "Hey Adex"
@@ -511,7 +513,7 @@ def test_protected_terms_survive_an_unreadable_dictionary(
def _boom() -> list[str]:
raise RuntimeError("store is locked")
- monkeypatch.setattr(dictionary, "dictionary_bias_words", _boom)
+ monkeypatch.setattr(dictionary, "dictionary_protected_words", _boom)
pipe = SpeechPipeline.__new__(SpeechPipeline)
pipe._wake_phrase_label = "Nova"
diff --git a/tests/unit/speech/test_stt_dictionary_defaults.py b/tests/unit/speech/test_stt_dictionary_defaults.py
new file mode 100644
index 0000000000..2c76a6df20
--- /dev/null
+++ b/tests/unit/speech/test_stt_dictionary_defaults.py
@@ -0,0 +1,168 @@
+"""The shipped default vocabulary: every install fixes the product name and the
+developer terms mixed German/English dictation keeps mishearing — and the
+user's own dictionary always wins over it.
+
+Reported 2026-10-20: "Pipey" / "Pipe-I" for PyPI, "Baggen" for Bugs, "the Dios"
+for Dodaios.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from dodaios.speech.stt_dictionary import (
+ DEFAULT_ID_PREFIX,
+ DEFAULT_TERMS,
+ DictionaryStore,
+ dictionary_bias_words,
+ dictionary_protected_words,
+ get_corrector,
+)
+
+
+def store(tmp_path: Path) -> DictionaryStore:
+ return DictionaryStore(tmp_path / "stt_dictionary.json")
+
+
+ ("heard", "meant"),
+ [
+ (
+ "Ich habe das auf Pipey veröffentlicht.", # i18n-allow: German dictation fixture
+ "Ich habe das auf PyPI veröffentlicht.", # i18n-allow: German dictation fixture
+ ),
+ ("Das Paket liegt auf Pipe-I.", "Das Paket liegt auf PyPI."), # i18n-allow: fixture
+ ("Die Baggen sind gefixt.", "Die Bugs sind gefixt."), # i18n-allow: fixture
+ ("I opened the Dios again.", "I opened Dodaios again."),
+ ("Starte Doda iOS neu.", "Starte Dodaios neu."),
+ ("Push it to Git Hub.", "Push it to GitHub."),
+ ("push it to github", "push it to GitHub"),
+ ("Schau dir die PR's an.", "Schau dir die PRs an."),
+ ("dodaios startet", "Dodaios startet"),
+ ],
+)
+def test_a_fresh_install_corrects_the_reported_mishearings(
+ store: DictionaryStore, heard: str, meant: str
+) -> None:
+ assert get_corrector(store).correct(heard) == meant
+
+
+ "said",
+ [
+ # Real words next to the defaults stay exactly as said.
+ "Ich speichere das in der Cloud.", # i18n-allow: German dictation fixture
+ "Dios mío, otra vez.",
+ "PyPy is a different interpreter.",
+ "fix the bugs before the release", # common word: no casing rule
+ "We merge the release branch.",
+ "the pipe I built",
+ # "PyPI" folds like these; the sound-alike repair must not reach them.
+ "Pippi Langstrumpf",
+ "Das Kind muss Pipi.", # i18n-allow: German dictation fixture
+ ],
+)
+def test_the_defaults_leave_ordinary_words_alone(store: DictionaryStore, said: str) -> None:
+ assert get_corrector(store).correct(said) == said
+
+
+def test_reading_never_writes_the_users_sidecar(store: DictionaryStore) -> None:
+ get_corrector(store).correct("Pipey")
+ store.effective_entries()
+ assert not store.path.exists()
+
+
+def test_a_user_entry_for_the_same_word_replaces_the_default(
+ store: DictionaryStore,
+) -> None:
+ store.add("PyPI", ["Pie Pie"])
+
+ words = [e.word for e in store.effective_entries()]
+ assert words.count("PyPI") == 1
+ corrector = get_corrector(store)
+ assert corrector.correct("Pie Pie") == "PyPI"
+ # The default's variants went with it: the user's entry is the rule now.
+ assert corrector.correct("Pipey") == "Pipey"
+
+
+def test_a_user_spelling_beats_a_default_variant(store: DictionaryStore) -> None:
+ store.add("Pipeline", ["Pipey"])
+
+ assert get_corrector(store).correct("Pipey") == "Pipeline"
+ # The rest of the default survives.
+ assert get_corrector(store).correct("Pipe-I") == "PyPI"
+
+
+def test_a_user_who_calls_the_word_a_mishearing_hides_the_default(
+ store: DictionaryStore,
+) -> None:
+ store.add("Bugsy", ["Bugs"])
+
+ assert "Bugs" not in [e.word for e in store.effective_entries()]
+
+
+def test_a_deleted_default_stays_deleted(store: DictionaryStore) -> None:
+ assert store.delete(f"{DEFAULT_ID_PREFIX}bugs") is True
+
+ assert get_corrector(store).correct("Die Baggen") == "Die Baggen"
+ raw = json.loads(store.path.read_text(encoding="utf-8"))
+ assert raw["removed_defaults"] == [f"{DEFAULT_ID_PREFIX}bugs"]
+ # Later writes keep the record.
+ store.add("Vokando")
+ assert store.removed_defaults() == frozenset({f"{DEFAULT_ID_PREFIX}bugs"})
+ assert store.delete(f"{DEFAULT_ID_PREFIX}bugs") is False
+
+
+def test_an_edited_default_is_stored_as_the_users_own(store: DictionaryStore) -> None:
+ edited = store.update(
+ f"{DEFAULT_ID_PREFIX}dodaios", misheard=["the Dios", "Duda OS"], misheard_set=True
+ )
+
+ assert edited is not None
+ assert edited.default is False
+ stored = store.list_all()
+ assert [e.id for e in stored] == [f"{DEFAULT_ID_PREFIX}dodaios"]
+ assert get_corrector(store).correct("Duda OS") == "Dodaios"
+ # The sidecar holds the user's data only, never the derived flags.
+ row = json.loads(store.path.read_text(encoding="utf-8"))["entries"][0]
+ assert set(row) == {"id", "word", "misheard", "created_at", "updated_at"}
+
+
+def test_an_unknown_default_id_is_not_found(store: DictionaryStore) -> None:
+ assert store.update(f"{DEFAULT_ID_PREFIX}nope", word="X") is None
+ assert store.delete(f"{DEFAULT_ID_PREFIX}nope") is False
+
+
+def test_the_defaults_stay_out_of_every_decoder_prompt(store: DictionaryStore) -> None:
+ """BUG-185/BUG-211: a primed Whisper recites its prompt over silence."""
+ assert dictionary_bias_words(store) == []
+ store.add("Vokando")
+ assert dictionary_bias_words(store) == ["Vokando"]
+
+
+def test_the_polish_pass_protects_the_defaults(store: DictionaryStore) -> None:
+ words = dictionary_protected_words(store)
+
+ assert {"Dodaios", "PyPI", "GitHub"} <= set(words)
+
+
+def test_a_sentence_listing_default_terms_is_not_taken_for_a_recited_prompt(
+ store: DictionaryStore,
+) -> None:
+ """The echo guard drops runs of PRIMED words; the defaults never are."""
+ said = "Wir nutzen GitHub, PyPI, PRs und Dodaios." # i18n-allow: German fixture
+
+ assert get_corrector(store).strip_prompt_echo(said) == said
+
+
+def test_the_defaults_carry_no_personal_data() -> None:
+ for term in DEFAULT_TERMS:
+ for value in (term.word, *term.misheard):
+ assert "@" not in value
+ assert not any(ch.isdigit() for ch in value)
+ slugs = [t.slug for t in DEFAULT_TERMS]
+ assert len(slugs) == len(set(slugs))
diff --git a/tests/unit/ui/web/test_dictionary_routes.py b/tests/unit/ui/web/test_dictionary_routes.py
index 1d18ae6752..f6fcbd4516 100644
--- a/tests/unit/ui/web/test_dictionary_routes.py
+++ b/tests/unit/ui/web/test_dictionary_routes.py
@@ -20,10 +20,21 @@ def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
return TestClient(app)
-def test_list_empty(client: TestClient) -> None:
+def _user_entries(client: TestClient) -> list[dict]:
+ """The user's own rows — the shipped defaults are listed after them."""
+ return [e for e in client.get("/api/dictionary").json()["entries"] if not e["default"]]
+
+
+def test_list_holds_only_the_shipped_defaults_on_a_fresh_install(
+ client: TestClient,
+) -> None:
r = client.get("/api/dictionary")
assert r.status_code == 200
- assert r.json() == {"entries": []}
+ entries = r.json()["entries"]
+ assert entries, "a fresh install starts with the default vocabulary"
+ assert all(e["default"] for e in entries)
+ assert all(e["id"].startswith("default-") for e in entries)
+ assert "Dodaios" in [e["word"] for e in entries]
def test_create_and_list(client: TestClient) -> None:
@@ -39,8 +50,11 @@ def test_create_and_list(client: TestClient) -> None:
r2 = client.get("/api/dictionary")
assert r2.status_code == 200
entries = r2.json()["entries"]
- assert len(entries) == 1
assert entries[0]["word"] == "GitHub"
+ assert entries[0]["default"] is False
+ # The user's GitHub replaces the shipped one rather than sitting beside it.
+ assert [e["word"] for e in entries].count("GitHub") == 1
+ assert len(_user_entries(client)) == 1
def test_create_plain_word_without_misheard(client: TestClient) -> None:
@@ -95,3 +109,32 @@ def test_delete_idempotent(client: TestClient) -> None:
r2 = client.delete(f"/api/dictionary/{created['id']}")
assert r2.status_code == 200
assert r2.json() == {"ok": True, "removed": False}
+
+
+def test_deleting_a_default_keeps_it_deleted(client: TestClient) -> None:
+ r = client.delete("/api/dictionary/default-pypi")
+ assert r.json() == {"ok": True, "removed": True}
+ words = [e["word"] for e in client.get("/api/dictionary").json()["entries"]]
+ assert "PyPI" not in words
+ assert client.delete("/api/dictionary/default-pypi").json()["removed"] is False
+
+
+def test_editing_a_default_makes_it_the_users_entry(client: TestClient) -> None:
+ r = client.patch(
+ "/api/dictionary/default-pypi", json={"misheard": ["Pipey", "Pie Pie"]}
+ )
+ assert r.status_code == 200
+ body = r.json()
+ assert body["id"] == "default-pypi"
+ assert body["default"] is False
+ assert body["misheard"] == ["Pipey", "Pie Pie"]
+ # A second edit in flight with the same id still lands.
+ r2 = client.patch("/api/dictionary/default-pypi", json={"word": "PyPI.org"})
+ assert r2.status_code == 200
+ entries = client.get("/api/dictionary").json()["entries"]
+ assert [e["word"] for e in entries].count("PyPI") == 0
+ assert any(e["word"] == "PyPI.org" and not e["default"] for e in entries)
+ # Deleting the edited copy does not bring the default back.
+ client.delete("/api/dictionary/default-pypi")
+ words = [e["word"] for e in client.get("/api/dictionary").json()["entries"]]
+ assert "PyPI" not in words and "PyPI.org" not in words