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
fix(dictation): arm the paste-again key and stop dropping audio on a failed segment
Ruben Lütke916dbd31650c
diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 47261cbd3c..3270a88018 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -189,6 +189,22 @@ class DictationCompleted(Event):#: render an unknown-reason blank.#: ``pipeline_not_running``#: The speech pipeline has no running event loop to host the session.+#:+#: The last three belong to the "insert the last dictation again" key rather+#: than to a recording. It starts nothing, so it can never be refused for a+#: microphone reason — but it CAN do nothing at all, and a key that does+#: nothing in silence is the exact failure this vocabulary exists to prevent.+#:+#: ``nothing_to_paste``+#: The history holds no dictation to re-insert (nothing recorded yet, or+#: every entry was discarded).+#: ``history_disabled``+#: ``[dictation].history_enabled`` is off, so no transcript was kept and+#: there is nothing this key could paste. Recoverable in the settings.+#: ``paste_unavailable``+#: The text could not be typed into the focused window — Wayland, a+#: headless host, an elevated window in front, macOS secure input. The+#: detail says where the text ended up instead (usually the clipboard).DICTATION_REFUSAL_REASONS: Final[tuple[str, ...]] = ("microphone_unavailable","no_stt",@@ -196,6 +212,9 @@ DICTATION_REFUSAL_REASONS: Final[tuple[str, ...]] = ("handover_failed","voice_session_active","pipeline_not_running",+ "nothing_to_paste",+ "history_disabled",+ "paste_unavailable",)diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 2f8a492372..b90dd97205 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -678,6 +678,15 @@ _DICTATION_HANDOVER_TIMEOUT_S = 5.0# Small enough to be imperceptible, large enough not to spin the loop._DICTATION_HANDOVER_POLL_S = 0.02+# How many times the FINAL dictation transcription is attempted, and how long it+# waits between attempts. Only the final call is retried: every earlier one is a+# probe tick that gets another chance a second later anyway, while this one is+# the last thing that ever sees the audio — the buffer is gone once the session+# returns. Three attempts over ~1.2 s covers a transient 429 / socket reset+# without making a genuinely dead provider feel like a hang.+_DICTATION_FINAL_ATTEMPTS = 3+_DICTATION_FINAL_RETRY_DELAY_S = 0.6+class _SessionInputBuffer:"""Replayable bounded handoff for one continuously captured mic stream.@@ -1341,6 +1350,13 @@ class SpeechPipeline:# key and a toggle key armed at the same time, and the legacy# ``[dictation].mode = "toggle"`` still only governs ``dictate_hotkeys``.dictate_toggle_hotkeys: tuple[str, ...] = (),+ # "Insert the last dictation again" — its own binding, because it needs+ # neither a microphone nor a speech-to-text provider and therefore stays+ # useful on a host where dictation itself cannot run. It was editable in+ # the Voice → Shortcuts tab for a while WITHOUT arriving here: the save+ # persisted, the UI showed the new combo, and the key did nothing —+ # forever, restart included (the AP-4 trap: one layer never told).+ paste_last_hotkeys: tuple[str, ...] = (),# Resolved DictationConfig (jarvis.core.config.DictationConfig) or None.# None keeps every legacy call site and test on the built-in defaults.dictation_config: Any = None,@@ -1350,6 +1366,10 @@ class SpeechPipeline:self._hangup_hotkeys = hangup_hotkeysself._dictate_hotkeys = list(dictate_hotkeys)self._dictate_toggle_hotkeys = list(dictate_toggle_hotkeys)+ self._paste_last_hotkeys = list(paste_last_hotkeys)+ # One paste at a time — two overlapping ones race over the clipboard+ # restore and the loser puts the wrong content back (see _on_paste_last).+ self._paste_last_busy = Falseself._dictate_mode = "toggle" if str(dictate_mode).lower() == "toggle" else "hold"self._dictation_cfg = dictation_config# Push-to-talk runtime state. ``_ptt_mode`` arms the raw-recording path@@ -2079,6 +2099,63 @@ class SpeechPipeline:self._ack_pcm = b""self._task_ack_pcm.clear()+ def set_stt_language(self, language: str) -> bool:+ """Live-apply a new recognition language. Returns True when it took.++ The utterance recogniser carries its language from construction, so+ changing the setting used to do nothing at all until the app was+ restarted — while the settings route reported the change as applied,+ because "applied" only ever meant the WAKE plan. The honest outcome is+ either a recogniser that actually speaks the new language now, or a+ False the caller can turn into "restart to apply".++ Rebuilding is cheap: cloud providers are a constructor plus an HTTP+ client, and the local faster-whisper loads its weights lazily on the+ first transcription. The swap is a clean cut-over like ``set_tts`` — an+ in-flight transcription keeps the old instance and finishes normally+ (AP-24: never reach into a native engine that is mid-inference).++ The WAKE recogniser (``self._stt``) is deliberately untouched: it is+ acoustically tied to the wake phrase and has its own language setting.+ """+ cfg_stt = getattr(getattr(self, "_config", None), "stt", None)+ if cfg_stt is None:+ return False+ try:+ cfg_stt.language = language+ except Exception as exc: # noqa: BLE001 — a frozen model is not an error+ log.debug("in-memory stt.language update skipped: %s", exc)+ try:+ from jarvis.plugins.stt import build_stt_from_config++ rebuilt = build_stt_from_config(cfg_stt)+ except Exception as exc: # noqa: BLE001 — never break voice on a settings click+ log.warning("STT language live-switch failed to build a provider: %s", exc)+ return False+ if rebuilt is None:+ return False++ try:+ from jarvis.speech.stt_dictionary import wrap_stt_with_dictionary++ rebuilt = wrap_stt_with_dictionary(rebuilt)+ except Exception as exc: # noqa: BLE001 — corrections are not load-bearing here+ log.debug("STT dictionary wrapper unavailable on live switch: %s", exc)++ previous = self._utterance_stt+ self._utterance_stt = rebuilt+ # The preview probe follows only when it was the SAME object — in the+ # local-Whisper path it is the wake model, which must keep its own+ # language (AP-27: the wake never rides on the utterance setting).+ if previous is not None and self._probe_stt is previous:+ self._probe_stt = rebuilt+ log.info(+ "STT-Live-Switch: recognition language is now %r (%s)",+ language,+ type(rebuilt).__name__,+ )+ return True+def set_silence_window_ms(self, ms: int) -> None:"""Live-apply a new voice silence window to the running VAD.@@ -2351,6 +2428,7 @@ class SpeechPipeline:ptt: list[str] | None = None,dictate: list[str] | None = None,dictate_toggle: list[str] | None = None,+ paste_last: list[str] | None = None,) -> None:"""Live-apply changed voice keybinds — no app/pipeline restart.@@ -2367,7 +2445,11 @@ class SpeechPipeline:Every keyword here is spelled exactly like its entry in``config_writer.KEYBIND_ACTIONS``: the settings route calls``set_keybinds(**{action: [...]})``, so a keyword that drifts from the- action string turns a successful save into a silent no-op.+ action string turns a successful save into a silent no-op — and a+ keyword that is MISSING turns it into a ``TypeError`` the route catches+ and reports as "applies on restart", which is worse: it is a promise+ nothing downstream keeps. Every action in ``KEYBIND_ACTIONS`` therefore+ needs a keyword here, and a binding in ``_build_hotkey_bindings``."""if call is not None:self._call_hotkeys = list(call)@@ -2379,14 +2461,17 @@ class SpeechPipeline:self._dictate_hotkeys = list(dictate)if dictate_toggle is not None:self._dictate_toggle_hotkeys = list(dictate_toggle)+ if paste_last is not None:+ self._paste_last_hotkeys = list(paste_last)log.info("Keybinds live-switched: CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s] "- "DICTATE-TOGGLE=[%s]",+ "DICTATE-TOGGLE=[%s] PASTE-LAST=[%s]",", ".join(self._call_hotkeys),", ".join(self._ptt_hotkeys) or "off",", ".join(self._hangup_hotkeys),", ".join(self._dictate_hotkeys) or "off",", ".join(self._dictate_toggle_hotkeys) or "off",+ ", ".join(getattr(self, "_paste_last_hotkeys", None) or []) or "off",)self._hotkey_reload_event.set()@@ -2435,6 +2520,11 @@ class SpeechPipeline:# Never an edge binding: the whole point of a toggle is one event# per press. Asking for both edges would start on the down edge and# stop again on the up edge, i.e. turn it back into push-to-talk.+ paste_last = getattr(self, "_paste_last_hotkeys", None) or []+ if paste_last:+ # Single-fire on release, like every non-hold action: holding the+ # key must paste once, not once per polling tick.+ bindings["paste_last"] = list(paste_last)return bindings, edge_events# ------------------------------------------------------------------@@ -4264,7 +4354,7 @@ class SpeechPipeline:hotkey_bindings, ptt_events = self._build_hotkey_bindings()log.info("Pipeline ready. CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s/%s] "- "DICTATE-TOGGLE=[%s] OWW=%s "+ "DICTATE-TOGGLE=[%s] PASTE-LAST=[%s] OWW=%s ""WAKE=%s (threshold=%.2f) WHISPER-WAKE=%s TURN-MODE=%s",", ".join(self._call_hotkeys),", ".join(self._ptt_hotkeys) or "off",@@ -4272,6 +4362,7 @@ class SpeechPipeline:", ".join(self._dictate_hotkeys) or "off",self._dictate_mode,", ".join(getattr(self, "_dictate_toggle_hotkeys", None) or []) or "off",+ ", ".join(getattr(self, "_paste_last_hotkeys", None) or []) or "off","on" if self._openwakeword_enabled else "off",list(self._wake._keywords),self._wake._threshold,@@ -4779,6 +4870,8 @@ class SpeechPipeline:elif event_name == "dictate_toggle":# The dedicated hands-free key. Same handler, its own binding.self._on_dictate_toggle()+ elif event_name == "paste_last":+ self._on_paste_last()elif event_name == "hangup":log.info("📵 HANGUP via Hotkey")self._trigger_voice_hangup()@@ -4860,6 +4953,80 @@ class SpeechPipeline:returnself.start_dictation(target=self._configured_dictation_target())+ def _on_paste_last(self) -> None:+ """"Insert the last dictation again" key — re-deliver the last transcript.++ Needs no microphone, no speech-to-text and no recording, which is the+ whole point: it stays useful exactly where dictation itself cannot run.++ Scheduled as a task rather than executed here, because the work behind+ it is blocking — it parses the history file and sleeps around the paste+ chord — and this handler runs ON the pipeline's event loop, the same+ loop a live voice turn uses (AP-9). A press while one is still running+ is dropped rather than queued: two overlapping pastes race over the+ clipboard restore and the loser puts the WRONG content back.+ """+ if getattr(self, "_paste_last_busy", False):+ log.debug("paste-last key ignored: a paste is already in flight")+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ log.debug("paste-last key ignored: no running event loop")+ return+ self._paste_last_busy = True+ loop.create_task(self._paste_last_dictation(), name="dictation-paste-last")++ async def _paste_last_dictation(self) -> None:+ """The blocking half of :meth:`_on_paste_last`. Never raises.++ Goes through ``insert_last_dictation`` — the SAME delivery path the+ REST route and a fresh dictation use — so the three can never drift+ apart. Anything short of "the text was typed where you were pointing"+ is announced on the bus instead of logged: the reported bug for this+ whole feature was a key that looked bound and did nothing visible.+ """+ try:+ from jarvis.dictation.insert import insert_last_dictation++ result = await asyncio.to_thread(+ insert_last_dictation, settings=getattr(self, "_dictation_cfg", None)+ )+ except Exception as exc: # noqa: BLE001 — a paste is never worth a crash+ log.warning("paste-last failed (non-fatal)", exc_info=True)+ self._refuse_dictation(+ "paste_unavailable",+ "The last dictation could not be pasted again "+ f"({type(exc).__name__}).",+ )+ return+ finally:+ self._paste_last_busy = False++ reason = str(getattr(result, "reason", "") or "")+ detail = str(getattr(result, "detail", "") or "")+ insert = getattr(result, "insert", None)+ status = str(getattr(insert, "status", "") or "")+ log.info(+ "📋 paste-last: ok=%s reason=%s status=%s (%d chars)",+ bool(getattr(result, "ok", False)),+ reason or "-",+ status or "-",+ len(str(getattr(result, "text", "") or "")),+ )+ if getattr(result, "ok", False) and status not in ("clipboard_only", "paste_sent"):+ return # the text is in the field the user was looking at — proof enough+ # Everything else owes an explanation: nothing saved, history off, or a+ # host that cannot type into another window (the text is on the+ # clipboard then, which the detail sentence says).+ token = {+ "not_found": "nothing_to_paste",+ "history_disabled": "history_disabled",+ }.get(reason, "paste_unavailable")+ self._refuse_dictation(+ token, detail or "The last dictation could not be pasted again."+ )+def _configured_dictation_target(self) -> str:"""``[dictation].target`` — ``auto`` by default, resolved at start."""cfg = getattr(self, "_dictation_cfg", None)@@ -8199,12 +8366,21 @@ class SpeechPipeline:pinned_language = str(getattr(cfg, "language", "auto") or "auto").strip().lower()forced_language = pinned_language if pinned_language not in ("", "auto") else None- async def _transcribe(pcm: bytes) -> tuple[str, str]:- """One transcription. Returns ``(text, language)``; never raises.+ async def _transcribe(pcm: bytes) -> tuple[str, str, bool]:+ """One transcription. ``(text, language, ok)``; never raises.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.++ ``ok`` is the part the caller cannot do without: an empty ``text``+ has TWO causes that need opposite handling — silence (the segment is+ genuinely done) and a failed call (the audio has not been read yet).+ Without this flag the segment loop treated both as "done" and+ advanced past audio nobody had transcribed, so one network hiccup+ deleted eight seconds of speech from the middle of the result with+ nothing anywhere saying so. That is the reported "I said more than+ this" bug in its entirety."""nonlocal stt_errorinference_active.set()@@ -8224,13 +8400,13 @@ class SpeechPipeline:except Exception as exc: # noqa: BLE001 — one failed call is not fatallog.debug("dictation transcribe failed: %s", exc)stt_error = f"{type(exc).__name__}: {exc}".strip()- return "", ""+ return "", "", Falsefinally:inference_active.clear()stt_error = Nonetext = (getattr(transcript, "text", "") or "").strip()lang = str(getattr(transcript, "language", "") or "")- return text, lang+ return text, lang, Trueasync def _probe() -> None:"""Close finished segments and publish the live transcript."""@@ -8255,21 +8431,42 @@ class SpeechPipeline:cut = quietest_cut(tail, segment_bytes, bytes_per_second)if cut >= min_bytes:- text, lang = await _transcribe(tail[:cut])+ text, lang, ok = await _transcribe(tail[:cut])if stop_event.is_set():return+ if not ok:+ # The CALL failed — the audio is unread, not+ # silent. Closing the segment here would delete+ # those seconds from the result permanently+ # (a closed segment is never re-sent) and the+ # next successful call would clear ``stt_error``,+ # so the user would be handed a transcript with+ # a hole in it and no hint that anything went+ # wrong. Leave the segment open instead: the+ # next tick retries it, and if every retry fails+ # the final pass still transcribes the whole+ # tail. Slower on a flaky link, never lossy.+ log.info(+ "dictation segment kept open after a failed "+ "transcription (%s) — retrying with the next "+ "tick rather than dropping %.1fs of audio.",+ stt_error or "unknown error",+ cut / bytes_per_second,+ )+ continueif text:closed_parts.append(text)language = lang or language- # Advance regardless: a segment that transcribed to- # nothing was silence, and re-sending it forever- # would rebuild the very O(n²) loop this replaces.+ # Advance on SUCCESS only: a segment that transcribed+ # to nothing really was silence, and re-sending it+ # forever would rebuild the very O(n²) loop this+ # replaces.closed_bytes += cuttail = bytes(buffer[closed_bytes:])tail_text = ""if len(tail) >= min_bytes:- tail_text, lang = await _transcribe(tail)+ tail_text, lang, _ok = await _transcribe(tail)language = lang or languageif stop_event.is_set():return@@ -8372,8 +8569,27 @@ class SpeechPipeline:tail = bytes(buffer[closed_bytes:])tail_text = ""if len(tail) >= min_bytes:- tail_text, lang = await _transcribe(tail)- language = lang or language+ # RETRIED, unlike every call before it. A probe-tick failure+ # costs a retry a second later; this one is the last chance+ # the audio ever gets — the buffer is dropped the moment+ # this function returns. One transient 429 / socket reset+ # here used to silently truncate the dictation at the last+ # closed segment, which is the worst possible moment to give+ # up: the user has finished speaking and is waiting.+ for attempt in range(_DICTATION_FINAL_ATTEMPTS):+ tail_text, lang, ok = await _transcribe(tail)+ language = lang or language+ if ok:+ break+ if attempt + 1 < _DICTATION_FINAL_ATTEMPTS:+ log.info(+ "final dictation transcription failed (%s) — "+ "retry %d/%d.",+ stt_error or "unknown error",+ attempt + 1,+ _DICTATION_FINAL_ATTEMPTS - 1,+ )+ await asyncio.sleep(_DICTATION_FINAL_RETRY_DELAY_S)raw_text = " ".join([*closed_parts, tail_text]).strip()final_text = raw_text@@ -8489,6 +8705,36 @@ class SpeechPipeline:# reason="no_rules", i.e. no cleanup at all despite an explicit pin.pinned = str(getattr(cfg, "language", "auto") or "auto").strip().lower()effective_language = pinned if pinned not in ("", "auto") else language+ # Last resort: read the language off the TEXT. Not every provider+ # reports one — ``transcribe_pcm`` is only contracted to return text —+ # and on ``[dictation].language = auto`` (the shipped default) a silent+ # provider left ``effective_language`` empty, which the cleanup can only+ # answer with "no rules for this language". The observable consequence+ # is the whole filler removal never running: every "äh" and "ähm" the+ # user hesitated with shipped straight into the text while the setting+ # said it was on. Resolved through the ONE canonical language resolver+ # (CLAUDE.md §1: no layer invents its own detection), and only when+ # nothing better is known — a provider that DID report a language keeps+ # the last word.+ if raw_text and not hung_up:+ try:+ from jarvis.core.turn_language import (+ detect_text_language,+ normalize_language_tag,+ )++ if normalize_language_tag(effective_language) == "unknown":+ detected = detect_text_language(raw_text)+ if detected != "unknown":+ log.debug(+ "dictation language resolved from the transcript: %s "+ "(the provider reported %r)",+ detected,+ language,+ )+ effective_language = detected+ except Exception: # noqa: BLE001 — a detection hiccup is not fatal+ log.debug("dictation language detection failed", exc_info=True)if raw_text and not hung_up:try:@@ -11802,6 +12048,11 @@ async def _main() -> None:if config.trigger.hotkey_dictate_toggle.strip()else ()),+ paste_last_hotkeys=(+ (config.trigger.hotkey_paste_last,)+ if config.trigger.hotkey_paste_last.strip()+ else ()+ ),dictate_mode=config.dictation.mode,dictation_config=config.dictation,hangup_hotkeys=(diff --git a/jarvis/speech/watchdog.py b/jarvis/speech/watchdog.pyindex 971ae5ee22..3146a4b1f7 100644--- a/jarvis/speech/watchdog.py+++ b/jarvis/speech/watchdog.py@@ -138,6 +138,11 @@ async def _main() -> None:if config.trigger.hotkey_dictate_toggle.strip()else ()),+ paste_last_hotkeys=(+ (config.trigger.hotkey_paste_last,)+ if config.trigger.hotkey_paste_last.strip()+ else ()+ ),dictate_mode=config.dictation.mode,dictation_config=config.dictation,hangup_hotkeys=(diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 0163f789bb..accec91c7b 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2912,6 +2912,15 @@ class DesktopApp:if self.cfg.trigger.hotkey_dictate_toggle.strip()else ()),+ # "Insert the last dictation again". Editable in the same tab,+ # so it has to be armed here for the same reason the two above+ # are — a shortcut the UI can change but the pipeline never+ # reads is a row that lies.+ paste_last_hotkeys=(+ (self.cfg.trigger.hotkey_paste_last,)+ if self.cfg.trigger.hotkey_paste_last.strip()+ else ()+ ),dictate_mode=self.cfg.dictation.mode,dictation_config=self.cfg.dictation,hangup_hotkeys=(diff --git a/tests/unit/dictation/test_dictate_keybind.py b/tests/unit/dictation/test_dictate_keybind.pyindex 7aba5c1940..cc006f3bbf 100644--- a/tests/unit/dictation/test_dictate_keybind.py+++ b/tests/unit/dictation/test_dictate_keybind.py@@ -37,6 +37,56 @@ def test_hands_free_dictation_is_its_own_keybind_action() -> None:assert hasattr(TriggerConfig(), "hotkey_dictate_toggle")+def test_paste_last_is_its_own_keybind_action() -> None:+ """Needs no microphone and no provider, so it is not a mode of dictation."""+ assert "paste_last" in KEYBIND_ACTIONS+ assert KEYBIND_TOML_KEY["paste_last"] == "hotkey_paste_last"+ assert hasattr(TriggerConfig(), "hotkey_paste_last")+++#: The attribute holding each action's live combos on the pipeline. Written out+#: rather than derived, so a NEW action fails the two tests below loudly instead+#: of quietly skipping itself.+_ACTION_ATTR = {+ "call": "_call_hotkeys",+ "hangup": "_hangup_hotkeys",+ "dictate": "_dictate_hotkeys",+ "dictate_toggle": "_dictate_toggle_hotkeys",+ "paste_last": "_paste_last_hotkeys",+}+++def test_every_keybind_action_has_a_live_apply_keyword() -> None:+ """The settings route calls ``set_keybinds(**{action: [...]})``.++ An action WITHOUT a matching keyword raises ``TypeError`` there, which the+ route catches and reports as "applies on restart" — a promise the next boot+ does not keep either, because the same gap exists in the binding table. That+ is exactly how ``paste_last`` shipped as a row the UI could edit and nothing+ could fire. One assertion is cheaper than the bug report.+ """+ import inspect++ params = inspect.signature(SpeechPipeline.set_keybinds).parameters+ missing = [action for action in KEYBIND_ACTIONS if action not in params]+ assert missing == [], f"set_keybinds cannot live-apply: {missing}"+ assert sorted(_ACTION_ATTR) == sorted(KEYBIND_ACTIONS)+++def test_every_keybind_action_reaches_the_os_binding_table() -> None:+ """A bound action that never reaches ``_build_hotkey_bindings`` is a row+ that saves, displays, survives a restart — and never fires."""+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._ptt_hotkeys = []+ pipe._dictate_mode = "hold"+ for index, action in enumerate(KEYBIND_ACTIONS):+ setattr(pipe, _ACTION_ATTR[action], [f"ctrl+alt+f{index + 1}"])++ bindings, _edges = pipe._build_hotkey_bindings()+ missing = [action for action in KEYBIND_ACTIONS if action not in bindings]+ assert missing == [], f"never registered with the OS: {missing}"++def test_dictation_ships_bound_on_both_rows() -> None:"""Maintainer directive 2026-07-28. Shipping unbound made the headlinefeature do nothing on a fresh install; these two combos are curated@@ -199,6 +249,22 @@ def test_an_unbound_hands_free_row_arms_nothing() -> None:assert "dictate_toggle" not in bindings+def test_paste_last_fires_once_per_press() -> None:+ """Single-fire on release. Both edges would paste once per polling tick."""+ pipe = _pipeline(dictate=[])+ pipe._paste_last_hotkeys = ["ctrl+alt+v"]+ bindings, edges = pipe._build_hotkey_bindings()+ assert bindings["paste_last"] == ["ctrl+alt+v"]+ assert "paste_last" not in edges+++def test_an_unbound_paste_last_row_arms_nothing() -> None:+ pipe = _pipeline(dictate=[])+ pipe._paste_last_hotkeys = []+ bindings, _edges = pipe._build_hotkey_bindings()+ assert "paste_last" not in bindings++# --------------------------------------------------------------------------# Hotkey edges# --------------------------------------------------------------------------@@ -382,6 +448,39 @@ async def test_the_hands_free_key_stops_a_running_dictation() -> None:assert pipe.started == []+async def test_the_paste_last_event_reaches_its_handler() -> None:+ """The third half of the wiring: registered, fired — and dispatched.++ Without this arm the key registers with the OS, the OS delivers it, and the+ loop drops it on the floor.+ """+ pipe = _RecordingPipeline()+ calls: list[str] = []+ pipe._on_paste_last = lambda: calls.append("paste") # type: ignore[method-assign]++ await pipe._hotkey_loop(_ScriptedTrigger(["paste_last"]))++ assert calls == ["paste"]+ # It records nothing and stops nothing — it only re-delivers saved text.+ assert pipe.started == []+ assert pipe.stopped == 0+++async def test_a_paste_already_in_flight_is_not_queued_a_second_time() -> None:+ """Two overlapping pastes race over the clipboard restore, and the loser+ puts the PREVIOUS clipboard content back over the transcript."""+ pipe = _RecordingPipeline()+ pipe._paste_last_busy = True+ scheduled: list[object] = []+ pipe._paste_last_dictation = lambda: scheduled.append(1) # type: ignore[method-assign]++ pipe._on_paste_last()++ assert scheduled == []++@pytest.mark.asyncioasync def test_the_hold_key_edges_still_dispatch_unchanged() -> None:pipe = _RecordingPipeline()diff --git a/tests/unit/speech/test_dictation_no_audio_dropped.py b/tests/unit/speech/test_dictation_no_audio_dropped.pynew file mode 100644index 0000000000..4bdd10ee17--- /dev/null+++ b/tests/unit/speech/test_dictation_no_audio_dropped.py@@ -0,0 +1,286 @@+"""A failed transcription must never delete audio from a dictation.++The reported symptom was "I said more than that" — a transcript that is missing+a stretch from the middle, with nothing anywhere saying so. The cause was in the+segment loop: it closed a segment and advanced past its audio *regardless* of+whether the transcription had succeeded, on the reasoning that an empty result+means silence. An empty result has two causes, and the other one is a failed+call — so one 429 / socket reset deleted eight seconds of speech permanently (a+closed segment is never re-sent), and the next successful call reset+``stt_error`` back to ``None``, which took the last trace of it away too.++Pinned here:++* a failed segment transcription leaves the segment OPEN, so the final pass+ still sees every byte the microphone captured;+* a successful one still closes it (no O(n²) regression — that loop is the+ reason segmenting exists);+* the FINAL transcription is retried, because it is the last thing that ever+ sees the audio;+* the filler cleanup resolves a language even when the provider reports none.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import numpy as np+import pytest++import jarvis.speech.pipeline as pipeline_mod+from jarvis.core.bus import EventBus+from jarvis.core.config import DictationConfig+from jarvis.speech.pipeline import PipelineState, SpeechPipeline++BYTES_PER_SECOND = 16_000 * 2+++def _speech_then_pause(loud_bytes: int, quiet_bytes: int) -> bytes:+ """PCM that is loud, then silent — so ``quietest_cut`` cuts at the pause.++ Constant-amplitude audio would put the cut at the very first probe window+ (every window scores the same), which is below the minimum segment size and+ would close no segment at all — the test would then pass for the wrong+ reason.+ """+ loud = (np.ones(loud_bytes // 2, dtype=np.int16) * 5_000).tobytes()+ quiet = np.zeros(quiet_bytes // 2, dtype=np.int16).tobytes()+ return loud + quiet+++#: Three chunks of "speech, then a pause", each long enough to close a segment+#: at ``segment_seconds = 0.5``.+_CHUNKS = [_speech_then_pause(12_800, 6_400) for _ in range(3)]+_TOTAL_BYTES = sum(len(c) for c in _CHUNKS)+++class _ScriptedSTT:+ """Records every PCM it is handed; fails the first ``fail_first`` calls."""++ def __init__(self, *, fail_first: int, text: str = "recovered") -> None:+ self.calls: list[bytes] = []+ self._fail_first = fail_first+ self._text = text++ async def transcribe_pcm(self, pcm: bytes, language: str | None = None):+ self.calls.append(bytes(pcm))+ if len(self.calls) <= self._fail_first:+ raise RuntimeError("provider hiccup")+ return SimpleNamespace(text=self._text, language="de", is_partial=False)+++class _ScriptedMic:+ """Yields the fixed chunk list, then holds the stream open."""++ def __init__(self, *args: object, **kwargs: object) -> None:+ pass++ async def __aenter__(self) -> _ScriptedMic:+ return self++ async def __aexit__(self, *exc: object) -> bool:+ return False++ async def stream(self): # type: ignore[no-untyped-def]+ for chunk in _CHUNKS:+ yield SimpleNamespace(pcm=chunk)+ await asyncio.Event().wait()+++def _pipeline(bus: EventBus, stt: _ScriptedSTT, cfg: DictationConfig) -> SpeechPipeline:+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._bus = bus+ pipe._utterance_stt = stt+ pipe._dictation_task = None+ pipe._dictation_stop_event = asyncio.Event()+ pipe._dictation_cfg = cfg+ pipe._dictation_max_s = 30.0+ pipe._dictation_wake_block_until = 0.0+ pipe._dictation_completion_published = True+ pipe._ptt_mode = False+ pipe._ptt_partial_interval_s = 0.0+ pipe._state = PipelineState.IDLE+ pipe._muted = False+ pipe._input_device = "default"+ pipe._input_priority = ()+ pipe._hangup_event = asyncio.Event()+ return pipe+++async def _run_dictation(+ monkeypatch, stt: _ScriptedSTT, cfg: DictationConfig, *, wait_for_calls: int+) -> dict[str, object]:+ """Run one dictation to completion; return the kwargs ``_finish`` received."""+ bus = EventBus()+ pipe = _pipeline(bus, stt, cfg)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _ScriptedMic)++ captured: dict[str, object] = {}++ async def _fake_finish(**kwargs: object) -> str:+ captured.update(kwargs)+ pipe._dictation_completion_published = True+ return str(kwargs.get("raw_text") or "")++ pipe._finish_dictation = _fake_finish # type: ignore[method-assign]++ assert pipe.start_dictation(target="chat") is True+ # Wait for the probe to have done its work rather than sleeping a fixed+ # amount — a timing-based test on a loaded CI box is a flake generator.+ deadline = asyncio.get_running_loop().time() + 5.0+ while len(stt.calls) < wait_for_calls:+ if asyncio.get_running_loop().time() > deadline:+ break+ await asyncio.sleep(0.01)+ pipe.stop_dictation()+ await asyncio.wait_for(pipe._dictation_task, timeout=10.0)+ return captured+++async def test_a_failed_segment_does_not_delete_its_audio(monkeypatch) -> None:+ """Every byte reaches the final pass when the provider keeps failing.++ Before the fix each probe tick closed its segment anyway, so by the time+ the user let go the final call only saw whatever was left after the holes —+ and the holes were the words the transcript was missing.+ """+ stt = _ScriptedSTT(fail_first=99) # nothing ever succeeds+ cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=0.5)++ await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=3)++ assert stt.calls, "the probe must have attempted at least one transcription"+ assert max(len(c) for c in stt.calls) == _TOTAL_BYTES, (+ "no call ever saw the whole recording — audio was closed off unread"+ )+++async def test_a_successful_segment_still_closes(monkeypatch) -> None:+ """The gegenprobe: segmenting must keep working, or every dictation pays+ the O(n²) cost this design exists to avoid."""+ stt = _ScriptedSTT(fail_first=0)+ cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=0.5)++ captured = await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=3)++ assert len(stt.calls[-1]) < _TOTAL_BYTES, (+ "the final call re-sent the whole buffer — no segment was ever closed"+ )+ assert str(captured.get("raw_text") or "")+++async def test_the_final_transcription_is_retried(monkeypatch) -> None:+ """The last call is the last chance the audio ever gets.++ With the live probe off there is exactly one transcription, at the end. A+ single transient failure there used to cost the entire dictation — at the+ 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)++ captured = await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=0)++ assert len(stt.calls) >= 2, "the failed final transcription was not retried"+ assert captured.get("raw_text") == "the words"+ assert captured.get("stt_error") is None+++async def test_the_retry_gives_up_instead_of_hanging(monkeypatch) -> None:+ """A genuinely dead provider must not turn into an endless retry loop."""+ stt = _ScriptedSTT(fail_first=99)+ cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=0.5)++ captured = await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=0)++ assert len(stt.calls) == pipeline_mod._DICTATION_FINAL_ATTEMPTS+ assert captured.get("raw_text") == ""+ # The failure survives to the delivery half, which is what separates+ # "the provider rejected us" from "you said nothing".+ assert captured.get("stt_error")+++# --------------------------------------------------------------------------+# Cleanup language resolution+# --------------------------------------------------------------------------+++class _NullBus:+ async def publish(self, event: object) -> None:+ return None+++def _delivery_pipeline() -> SpeechPipeline:+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._bus = _NullBus()+ pipe._dictation_cfg = DictationConfig(target="chat", language="auto")+ pipe._dictation_completion_published = True+ return pipe+++async def test_fillers_are_removed_even_when_the_provider_names_no_language(+ monkeypatch,+) -> None:+ """``transcribe_pcm`` is only contracted to return TEXT.++ A provider that reports no language left the cleanup with nothing to match+ on, so it resolved to "no rules for this language" and every hesitation+ sound the user made went into the text — while the setting said filler+ removal was on. The language is read off the transcript instead, through+ the one canonical resolver.+ """+ pipe = _delivery_pipeline()+ recorded: dict[str, object] = {}++ async def _no_history(**kwargs: object) -> None:+ recorded.update(kwargs)++ pipe._record_dictation = _no_history # type: ignore[method-assign]++ # The German hesitation sounds ARE the input under test (CLAUDE.md §1 #4):+ # the filler rules are per-language, so proving they ran needs a sentence+ # in a language that has rules.+ spoken = "Also ähm ich wollte äh kurz Bescheid sagen" # i18n-allow: input under test++ cleaned = await pipe._finish_dictation(+ raw_text=spoken,+ language="", # the provider said nothing+ duration_s=1.0,+ target="chat",+ hung_up=False,+ )++ assert "ähm" not in cleaned # i18n-allow: input vocabulary under test+ assert "äh " not in cleaned # i18n-allow: input vocabulary under test+ assert "Bescheid sagen" in cleaned # i18n-allow: content words must survive+ assert recorded.get("language") == "de"+++async def test_a_reported_language_still_wins_over_the_text(monkeypatch) -> None:+ """Detection is the LAST resort, not a second opinion: a provider that did+ report a language keeps it, so a short or mixed transcript can never+ reclassify a dictation the provider was sure about."""+ pipe = _delivery_pipeline()+ recorded: dict[str, object] = {}++ async def _no_history(**kwargs: object) -> None:+ recorded.update(kwargs)++ pipe._record_dictation = _no_history # type: ignore[method-assign]++ await pipe._finish_dictation(+ raw_text="uh the thing is basically fine",+ language="English",+ duration_s=1.0,+ target="chat",+ hung_up=False,+ )++ assert recorded.get("language") == "English"