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): stop a pause from eating the words that follow it
Ruben Lütke69714e2e859f
diff --git a/jarvis/dictation/segment.py b/jarvis/dictation/segment.pyindex 29dadea16e..95b88335ae 100644--- a/jarvis/dictation/segment.py+++ b/jarvis/dictation/segment.py@@ -11,6 +11,17 @@ closed segment is never re-transcribed. So the cut point is not "exactly at Nseconds" but "at the quietest moment near N seconds" — which, in dictatedspeech, is a pause between words far more often than not.+A second job lives here: deciding that a stretch of audio holds no speech at+all, so it is never uploaded. Silence is not free — every silent second costs a+transcription request, and a request over silence is the single most reliable+way to make Whisper invent a sentence ("Thank you for watching", subtitle+credits, and friends). A user who pauses to think therefore paid twice: once in+rate limit, once in fabricated words landing in their text.++Judged on ENERGY only, never on what came back as text. That is the same rule+the wake path learned the hard way (AP-27): a content test cannot separate a+hallucination from a real utterance, because both are just words.+Pure functions over raw PCM: no model, no VAD state machine, no I/O. The VADproper is deliberately not reused here — it is a stateful component on thevoice hot path, and dictation must never contend with it.@@ -92,4 +103,77 @@ def quietest_cut(return _align(min(limit, best_centre * BYTES_PER_SAMPLE))-__all__ = ["BYTES_PER_SAMPLE", "quietest_cut"]+#: Below these an int16 microphone signal cannot be carrying speech on ANY+#: gain setting worth calling working — this is room tone, a fan, a desk bump.+#: ~1.2 % of full scale peak. Deliberately far under the quietest usable speech+#: (which peaks in the thousands) because the cost of the two mistakes is not+#: symmetric: skipping real speech deletes it permanently, while transcribing a+#: little silence only costs one request.+_CERTAIN_SILENCE_PEAK = 400.0+_CERTAIN_SILENCE_RMS = 120.0++#: The relative test only unlocks once the session has actually heard something+#: loud enough to BE speech. Without this floor a whole dictation recorded at a+#: very low input gain would measure its own quiet speech against itself and+#: skip all of it.+_SPEECH_REFERENCE_PEAK = 3_000.0++#: How far under the session's loudest moment a stretch has to sit before it+#: counts as a pause rather than quiet speech.+_RELATIVE_SILENCE_FRACTION = 0.06+_RELATIVE_SILENCE_RMS = 250.0+++def segment_energy(pcm: bytes) -> tuple[float, float]:+ """``(peak, rms)`` of ``pcm`` as int16 magnitudes. ``(0, 0)`` when empty.++ Never raises: a malformed buffer reports zero energy, which the caller+ treats as "nothing to transcribe" — the same as silence.+ """+ if not pcm:+ return 0.0, 0.0+ try:+ samples = np.frombuffer(pcm, dtype=np.int16)+ except (ValueError, TypeError):+ return 0.0, 0.0+ if samples.size == 0:+ return 0.0, 0.0+ as_float = samples.astype(np.float32)+ peak = float(np.max(np.abs(as_float)))+ rms = float(np.sqrt(np.mean(np.square(as_float))))+ return peak, rms+++def is_silent_segment(pcm: bytes, *, session_peak: float = 0.0) -> bool:+ """Whether ``pcm`` may be closed WITHOUT being transcribed.++ Two independent ways to qualify, and both are conservative by design —+ anything uncertain is transcribed, because a false "silent" verdict deletes+ words permanently while a false "speech" verdict costs one request:++ 1. **Absolute.** Quieter than any microphone carrying speech. Needs no+ context and is the one that catches a pause in the very first seconds.+ 2. **Relative.** Far below the loudest moment this session has heard, and+ only once that moment was loud enough to have been speech at all.++ ``session_peak`` is the running maximum peak the caller has observed. Pass+ ``0`` to use the absolute test alone.+ """+ peak, rms = segment_energy(pcm)+ if peak <= 0.0:+ return True+ if peak < _CERTAIN_SILENCE_PEAK and rms < _CERTAIN_SILENCE_RMS:+ return True+ return (+ session_peak >= _SPEECH_REFERENCE_PEAK+ and peak < session_peak * _RELATIVE_SILENCE_FRACTION+ and rms < _RELATIVE_SILENCE_RMS+ )+++__all__ = [+ "BYTES_PER_SAMPLE",+ "is_silent_segment",+ "quietest_cut",+ "segment_energy",+]diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 6633469a12..bd8bbd659c 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -687,6 +687,34 @@ _DICTATION_HANDOVER_POLL_S = 0.02_DICTATION_FINAL_ATTEMPTS = 3_DICTATION_FINAL_RETRY_DELAY_S = 0.6+# Ceiling on ONE final retry wait. The final pass runs while the user is already+# waiting for their text, so it may not inherit the probe's patient backoff.+_DICTATION_FINAL_RETRY_MAX_S = 2.0++# After this many consecutive pieces have exhausted every attempt, the provider+# is not flaky, it is down — and continuing to retry each remaining piece would+# make a 300 s dictation spend minutes proving it. Stop and say so: the audio is+# kept as a sidecar, so "Restore" can transcribe it again once the provider is+# back, which is a far better answer than a silent minute of waiting.+_DICTATION_FINAL_DEAD_PIECES = 2++# How far the live probe backs off after a failed transcription, and the ceiling+# it backs off to. A provider refusing calls — the everyday case is a rate limit,+# HTTP 429 — used to be answered by asking again at the same interval a second+# later, which is what turns a brief limit into a session-long one. Worse, every+# refused call leaves its segment open, so the open tail keeps growing and each+# retry uploads MORE audio than the last: the loop digs its own hole. Backing off+# lets the limit expire while the recording itself continues untouched.+_DICTATION_ERROR_BACKOFF_MIN_S = 1.5+_DICTATION_ERROR_BACKOFF_MAX_S = 12.0++# Queue depth for a dictation that opens its own microphone. The capture queue+# drops the OLDEST chunk when it overflows — correct for wake/VAD, where stale+# audio is worse than missing audio, and exactly wrong here: for a dictation+# every frame is the user's words. ~10 s of slack absorbs a provider stall+# without deleting speech (the default 20 chunks is 2 s).+_DICTATION_CAPTURE_QUEUE_CHUNKS = 100+class _SessionInputBuffer:"""Replayable bounded handoff for one continuously captured mic stream.@@ -5697,7 +5725,14 @@ class SpeechPipeline:returnasync with MicrophoneCapture(- device=self._input_device, device_priority=self._input_priority+ device=self._input_device,+ device_priority=self._input_priority,+ # A dictation is a BULK consumer: every frame is the user's words,+ # so the queue's drop-oldest policy deletes speech rather than+ # staleness. It cannot be turned off (the audio thread must never+ # block), so the defence is depth — enough slack that a slow+ # provider call cannot cost words.+ max_queue_chunks=_DICTATION_CAPTURE_QUEUE_CHUNKS,) as mic:yield mic@@ -8371,16 +8406,32 @@ class SpeechPipeline:stop_event = asyncio.Event()inference_active = asyncio.Event()language = ""+ # Loudest sample seen in any stretch judged so far. The silence test uses+ # it as the session's reference for "what speech sounds like here", so a+ # quiet microphone is measured against itself rather than an absolute+ # that was never calibrated for it.+ session_peak = 0.0+ # Audio closed without a request because it held no speech. Reported at+ # the end: it is the difference between "the provider was slow" and+ # "you paused for ninety seconds", and only one of those is a bug.+ skipped_silence_bytes = 0+ # Added to the probe interval after a failed call; see the constants.+ error_backoff_s = 0.0# The last transcription error, or None. Resolved ONCE per session at# the end: it is what separates "the provider rejected us" from "you# said nothing", and without it a 401 arrives in the history looking# exactly like silence — with no hint that a key needs fixing.stt_error: str | None = None- # ``[dictation].language`` pinned by the user; None means "auto", i.e.- # let the provider detect it. Resolved here rather than inside the- # closure so the config is read once per session, not once per segment.- pinned_language = str(getattr(cfg, "language", "auto") or "auto").strip().lower()- forced_language = pinned_language if pinned_language not in ("", "auto") else None+ # ``[dictation].language`` as chosen by the user. ``auto`` is passed+ # THROUGH to the provider rather than dropped: omitting the argument+ # means "no opinion", which lands on whatever ``[stt].language`` is+ # pinned to — so a user dictating German with the recognition language on+ # English got English words back and no setting in the dictation view+ # could fix it (live bug 2026-07-28). Resolved here rather than inside+ # the closure so the config is read once per session, not per segment.+ dictation_language = (+ str(getattr(cfg, "language", "auto") or "auto").strip().lower() or "auto"+ )async def _transcribe(pcm: bytes) -> tuple[str, str, bool]:"""One transcription. ``(text, language, ok)``; never raises.@@ -8401,18 +8452,15 @@ class SpeechPipeline:nonlocal stt_errorinference_active.set()try:- if forced_language is None:+ try:+ transcript = await stt.transcribe_pcm(+ pcm, language=dictation_language+ )+ except TypeError:+ # Provider predates the keyword (contract allows a bare+ # ``transcribe_pcm(pcm)``). Fall back rather than call the+ # choice a failure — precedent: rolling_whisper_wake.transcript = await stt.transcribe_pcm(pcm)- else:- try:- transcript = await stt.transcribe_pcm(- pcm, language=forced_language- )- except TypeError:- # Provider predates the keyword (contract allows a bare- # ``transcribe_pcm(pcm)``). Fall back rather than call- # the pin a failure — precedent: rolling_whisper_wake.- transcript = await stt.transcribe_pcm(pcm)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()@@ -8424,68 +8472,138 @@ class SpeechPipeline:lang = str(getattr(transcript, "language", "") or "")return text, lang, True+ async def _close_finished_segments() -> bool:+ """Close every segment the buffer already holds. ``False`` on a+ failed call, which leaves that segment — and everything after it —+ open for a later attempt.++ Draining in a LOOP rather than one segment per tick is what keeps+ the open tail bounded. One-per-tick can only keep up while every+ call is fast; the moment the provider slows down or refuses, the+ tail grows, and since the live preview re-uploads that whole tail on+ every tick, each round then costs more than the last. That spiral is+ what turned a rate limit into a dictation with most of its words+ missing: the loop stopped producing text, the upload work stalled the+ event loop, and the microphone queue dropped real speech to keep up.+ """+ nonlocal closed_bytes, language, session_peak, skipped_silence_bytes+ if not segment_bytes:+ return True+ from jarvis.dictation.segment import (+ is_silent_segment,+ quietest_cut,+ segment_energy,+ )++ while len(buffer) - closed_bytes >= segment_bytes:+ if stop_event.is_set():+ return True+ tail = bytes(buffer[closed_bytes:])+ # Cut at the quietest point in the last stretch, which keeps the+ # cut off the middle of a word in the overwhelming majority of+ # cases.+ cut = quietest_cut(tail, segment_bytes, bytes_per_second)+ if cut < min_bytes:+ return True+ piece = tail[:cut]+ peak, _rms = segment_energy(piece)+ session_peak = max(session_peak, peak)+ if is_silent_segment(piece, session_peak=session_peak):+ # A pause. Sending it would spend a request to be told+ # nothing — or, far worse, to be told "Thank you for+ # watching", which is what a transcription model does with+ # silence and what put invented sentences in the middle of+ # real dictations. Close it unread.+ closed_bytes += cut+ skipped_silence_bytes += cut+ continue+ text, lang, ok = await _transcribe(piece)+ if stop_event.is_set():+ return True+ 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 it open: a later tick+ # retries it, and the final pass sees it regardless.+ log.info(+ "dictation segment kept open after a failed "+ "transcription (%s) — backing off rather than dropping "+ "%.1fs of audio.",+ stt_error or "unknown error",+ cut / bytes_per_second,+ )+ return False+ if text:+ closed_parts.append(text)+ language = lang or language+ # 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 += cut+ return True+async def _probe() -> None:"""Close finished segments and publish the live transcript."""- nonlocal closed_bytes, last_published, language+ nonlocal last_published, language, error_backoff_s+ from jarvis.dictation.segment import is_silent_segment+try:while not stop_event.is_set():try:- await asyncio.wait_for(stop_event.wait(), timeout=interval)+ await asyncio.wait_for(+ stop_event.wait(), timeout=interval + error_backoff_s+ )except TimeoutError:passif stop_event.is_set():return- tail = bytes(buffer[closed_bytes:])- if len(tail) < min_bytes:- continue-- # Close a segment once the tail is long enough. Cutting at- # the quietest point in the last stretch keeps the cut off- # the middle of a word in the overwhelming majority of cases.- if segment_bytes and len(tail) >= segment_bytes:- from jarvis.dictation.segment import quietest_cut- cut = quietest_cut(tail, segment_bytes, bytes_per_second)- if cut >= min_bytes:- 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,- )- continue- if text:- closed_parts.append(text)- language = lang or language- # 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 += cut- tail = bytes(buffer[closed_bytes:])+ # Closing segments has priority over the preview: it is the+ # half that produces the final text, and the half that keeps+ # the tail — and therefore every upload — small.+ if not await _close_finished_segments():+ error_backoff_s = min(+ _DICTATION_ERROR_BACKOFF_MAX_S,+ max(_DICTATION_ERROR_BACKOFF_MIN_S, error_backoff_s * 2),+ )+ continue+ if stop_event.is_set():+ return+ tail = bytes(buffer[closed_bytes:])+ # Hard cap on the preview upload. After the drain above the+ # tail is normally shorter than one segment anyway; this is+ # the backstop for the case where it is not (a cut that+ # landed too early, or the legacy unsegmented mode), so a+ # preview can never grow into a multi-megabyte request that+ # blocks the loop the microphone is being drained on.+ if segment_bytes and len(tail) > segment_bytes:+ tail = tail[-segment_bytes:]tail_text = ""- if len(tail) >= min_bytes:- tail_text, lang, _ok = await _transcribe(tail)- language = lang or language+ if len(tail) >= min_bytes and not is_silent_segment(+ tail, session_peak=session_peak+ ):+ tail_text, lang, ok = await _transcribe(tail)if stop_event.is_set():return+ if not ok:+ error_backoff_s = min(+ _DICTATION_ERROR_BACKOFF_MAX_S,+ max(+ _DICTATION_ERROR_BACKOFF_MIN_S,+ error_backoff_s * 2,+ ),+ )+ continue+ language = lang or language+ error_backoff_s = 0.0+ # Published even when the tail was skipped as silence: a+ # segment may just have closed, and freezing the preview+ # through every pause is exactly what "it stopped+ # transcribing" looked like from the user's side.live = " ".join([*closed_parts, tail_text]).strip()if not live or live == last_published:continue@@ -8503,9 +8621,84 @@ class SpeechPipeline:except asyncio.CancelledError:pass+ async def _finalize_tail(tail: bytes) -> str:+ """Transcribe everything still open, in segment-sized pieces.++ One upload for the whole remainder is the wrong shape for the last+ call the audio ever gets: after a stretch of failures the remainder+ can be minutes long, and then a single timeout loses ALL of it. Piece+ by piece, one bad piece costs one piece. Each is retried, because+ unlike a probe tick there is no "next time" — the buffer is gone when+ this returns.+ """+ nonlocal language, session_peak+ from jarvis.dictation.segment import (+ is_silent_segment,+ quietest_cut,+ segment_energy,+ )++ parts: list[str] = []+ remaining = tail+ dead_streak = 0+ while len(remaining) >= min_bytes:+ if dead_streak >= _DICTATION_FINAL_DEAD_PIECES:+ log.warning(+ "final dictation transcription abandoned after %d "+ "consecutive failed pieces (%s) — %.1fs of audio kept "+ "for a later retry rather than making you wait.",+ dead_streak,+ stt_error or "unknown error",+ len(remaining) / bytes_per_second,+ )+ break+ if segment_bytes and len(remaining) > segment_bytes:+ cut = quietest_cut(remaining, segment_bytes, bytes_per_second)+ if cut < min_bytes:+ cut = min(len(remaining), segment_bytes)+ else:+ cut = len(remaining)+ piece, remaining = remaining[:cut], remaining[cut:]+ peak, _rms = segment_energy(piece)+ session_peak = max(session_peak, peak)+ if is_silent_segment(piece, session_peak=session_peak):+ continue+ for attempt in range(_DICTATION_FINAL_ATTEMPTS):+ text, lang, ok = await _transcribe(piece)+ language = lang or language+ if ok:+ if text:+ parts.append(text)+ dead_streak = 0+ break+ if attempt + 1 >= _DICTATION_FINAL_ATTEMPTS:+ dead_streak += 1+ else:+ # Widening, not fixed: three attempts inside one second+ # all land in the same rate-limit window, which is the+ # case this retry exists for. Still bounded — the user+ # has stopped speaking and is waiting for their text.+ delay = min(+ _DICTATION_FINAL_RETRY_MAX_S,+ _DICTATION_FINAL_RETRY_DELAY_S * (2**attempt),+ )+ log.info(+ "final dictation transcription failed (%s) — "+ "retry %d/%d in %.1fs.",+ stt_error or "unknown error",+ attempt + 1,+ _DICTATION_FINAL_ATTEMPTS - 1,+ delay,+ )+ await asyncio.sleep(delay)+ return " ".join(parts).strip()+final_text = ""raw_text = ""hung_up = False+ # Set when the RECORDING ended before the user did — a different failure+ # from a transcription that went wrong, and one that used to be invisible.+ capture_error: str | None = None# True once the delivery half has been entered, so the crash handler# below can tell "we never got to deliver" from "delivery itself blew# up" and never runs the delivery twice.@@ -8546,6 +8739,34 @@ class SpeechPipeline:return_when=asyncio.FIRST_COMPLETED,)hung_up = hangup_task in done or self._hangup_event.is_set()+ if drain_task in done and not drain_task.cancelled():+ # The RECORDING stopped on its own. Every way that+ # happens (a handoff buffer whose replay window the+ # drain fell behind, a microphone that went away) ends+ # the dictation early with whatever was captured so far+ # — which reads, from the user's side, exactly like "it+ # stopped transcribing halfway through". It was swallowed+ # here with the cancellations; name it instead, so the+ # history row and the completion message say what+ # happened rather than presenting a truncated transcript+ # as the whole thing.+ drain_exc = drain_task.exception()+ if drain_exc is not None:+ capture_error = (+ f"{type(drain_exc).__name__}: {drain_exc}".strip()+ )+ log.warning(+ "dictation recording ended early — %s", capture_error+ )+ else:+ # A source that simply RAN OUT is not a fault — it is+ # how a finite stream ends. Noted, never promoted to+ # an error: doing so would mask a real transcription+ # failure behind a message about the microphone.+ log.info(+ "dictation input stream ended; finalizing what "+ "was captured."+ )finally:# Freeze the probe BEFORE tearing anything else down so a# stop edge cannot race one more transcription into flight.@@ -8582,30 +8803,7 @@ class SpeechPipeline:if not hung_up:# Finalize ONLY the open tail — every closed segment is done.- tail = bytes(buffer[closed_bytes:])- tail_text = ""- if len(tail) >= min_bytes:- # 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)+ tail_text = await _finalize_tail(bytes(buffer[closed_bytes:]))raw_text = " ".join([*closed_parts, tail_text]).strip()final_text = raw_text@@ -8617,17 +8815,23 @@ class SpeechPipeline:duration_s=duration_s,target=target,hung_up=hung_up,- stt_error=stt_error,+ # A recording that ended early outranks a transcription error:+ # it explains a short transcript that every later layer would+ # otherwise present as complete.+ stt_error=capture_error or stt_error,audio=bytes(buffer),)final_text = resultlog.info(- "🎙️ dictation ended (%d chars, %.1fs, target=%s%s%s).",+ "🎙️ dictation ended (%d chars, %.1fs, target=%s, %.1fs silence "+ "skipped%s%s%s).",len(final_text),duration_s,target,+ skipped_silence_bytes / bytes_per_second,", hung up" if hung_up else "",f", stt error: {stt_error}" if stt_error else "",+ f", capture: {capture_error}" if capture_error else "",)except Exception as exc: # noqa: BLE001 — dictation must never break voicelog.warning("dictation session crashed (non-fatal)", exc_info=True)diff --git a/tests/unit/dictation/test_silence_detection.py b/tests/unit/dictation/test_silence_detection.pynew file mode 100644index 0000000000..4cced89f30--- /dev/null+++ b/tests/unit/dictation/test_silence_detection.py@@ -0,0 +1,96 @@+"""The silence test may skip pauses — it may never skip speech.++Skipping a stretch of audio closes it unread and it is never sent again, so a+wrong "silent" verdict deletes words permanently. A wrong "speech" verdict costs+one request. The thresholds are therefore deliberately lopsided, and these tests+exist to keep them that way: the speech cases here are quiet, awkward, and+close to the line on purpose.+"""++from __future__ import annotations++import numpy as np++from jarvis.dictation.segment import is_silent_segment, segment_energy+++def _tone(amplitude: int, seconds: float = 1.0, sample_rate: int = 16_000) -> bytes:+ """A sine at ``amplitude`` — speech-like in that it is not a flat DC block."""+ t = np.arange(int(seconds * sample_rate), dtype=np.float32)+ wave = np.sin(2.0 * np.pi * 220.0 * t / sample_rate) * amplitude+ return wave.astype(np.int16).tobytes()+++def _room_tone(seconds: float = 1.0, sample_rate: int = 16_000) -> bytes:+ """Not digital zero: a real room has a fan, a desk, a mains hum."""+ rng = np.random.default_rng(20260729)+ noise = rng.normal(0.0, 40.0, int(seconds * sample_rate))+ return noise.astype(np.int16).tobytes()+++def test_digital_silence_is_silent() -> None:+ assert is_silent_segment(np.zeros(16_000, dtype=np.int16).tobytes())+++def test_an_empty_buffer_is_silent() -> None:+ assert is_silent_segment(b"")+++def test_room_tone_is_silent() -> None:+ """The everyday pause: the user stopped talking, the room did not."""+ assert is_silent_segment(_room_tone(8.0))+++def test_normal_speech_is_not_silent() -> None:+ assert not is_silent_segment(_tone(6_000))+++def test_quiet_speech_is_not_silent() -> None:+ """A badly gained microphone still records words, and they must survive.++ This is the case where a threshold picked for a loud headset deletes a whole+ dictation on somebody else's hardware.+ """+ assert not is_silent_segment(_tone(900))+++def test_quiet_speech_survives_a_loud_session_reference() -> None:+ """The relative test must not turn a quiet sentence into a pause.++ Someone who leans back and finishes their thought more quietly is still+ speaking; only something far below the session's speech level counts as a+ gap.+ """+ assert not is_silent_segment(_tone(1_200), session_peak=12_000.0)+++def test_a_pause_inside_a_loud_session_is_silent() -> None:+ assert is_silent_segment(_room_tone(8.0), session_peak=12_000.0)+++def test_the_relative_test_stays_locked_without_a_speech_reference() -> None:+ """A session that has never been loud has no calibration to judge by.++ Without this floor a quiet recording measures itself against itself and+ skips everything — every word gone, no error anywhere.+ """+ quiet = _tone(700)+ assert not is_silent_segment(quiet, session_peak=1_500.0)+++def test_a_short_word_in_an_otherwise_silent_stretch_is_not_silent() -> None:+ """Peak, not just average: one word in eight seconds of pause is still a+ word, and an RMS-only test would average it away."""+ pause = np.zeros(int(7.5 * 16_000), dtype=np.int16).tobytes()+ assert not is_silent_segment(pause + _tone(5_000, seconds=0.5))+++def test_energy_reports_peak_and_rms() -> None:+ peak, rms = segment_energy(_tone(8_000))+ assert 7_900 <= peak <= 8_000+ assert 5_000 <= rms <= 6_000+++def test_malformed_audio_reports_no_energy() -> None:+ """An odd byte count is not a valid int16 buffer; it must not raise."""+ assert segment_energy(b"\x01") == (0.0, 0.0)diff --git a/tests/unit/speech/test_dictation_no_audio_dropped.py b/tests/unit/speech/test_dictation_no_audio_dropped.pyindex 4bdd10ee17..b6b3207d88 100644--- a/tests/unit/speech/test_dictation_no_audio_dropped.py+++ b/tests/unit/speech/test_dictation_no_audio_dropped.py@@ -36,25 +36,39 @@ from jarvis.speech.pipeline import PipelineState, SpeechPipelineBYTES_PER_SECOND = 16_000 * 2-def _speech_then_pause(loud_bytes: int, quiet_bytes: int) -> bytes:+def _speech_then_pause(loud_bytes: int, quiet_bytes: int, amplitude: 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 andwould close no segment at all — the test would then pass for the wrongreason.++ ``amplitude`` differs per chunk so a test can tell WHICH audio reached the+ provider. "Some audio was transcribed" is a claim the broken version could+ make too; "this second was transcribed" is not."""- loud = (np.ones(loud_bytes // 2, dtype=np.int16) * 5_000).tobytes()+ loud = (np.ones(loud_bytes // 2, dtype=np.int16) * amplitude).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)]+_AMPLITUDES = (5_000, 6_000, 7_000)+_CHUNKS = [_speech_then_pause(12_800, 6_400, amp) for amp in _AMPLITUDES]_TOTAL_BYTES = sum(len(c) for c in _CHUNKS)+def _amplitudes_seen(calls: list[bytes]) -> set[int]:+ """Which of the marker amplitudes reached the provider at all."""+ seen: set[int] = set()+ for call in calls:+ samples = np.frombuffer(call, dtype=np.int16)+ seen |= {int(v) for v in np.unique(np.abs(samples))} & set(_AMPLITUDES)+ return seen++class _ScriptedSTT:"""Records every PCM it is handed; fails the first ``fail_first`` calls."""@@ -140,20 +154,29 @@ async def _run_dictation(@pytest.mark.asyncioasync def test_a_failed_segment_does_not_delete_its_audio(monkeypatch) -> None:- """Every byte reaches the final pass when the provider keeps failing.+ """Every byte still reaches the provider once it recovers.Before the fix each probe tick closed its segment anyway, so by the timethe user let go the final call only saw whatever was left after the holes —and the holes were the words the transcript was missing.++ The failures here are transient, which is the case this guarantee is about:+ a provider that never recovers is a different promise (see+ ``test_the_retry_gives_up_instead_of_hanging``), because at some point+ continuing to retry costs the user more than it can possibly return."""- stt = _ScriptedSTT(fail_first=99) # nothing ever succeeds+ stt = _ScriptedSTT(fail_first=2)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"+ # Coverage, not a single call over everything: the final pass deliberately+ # goes out in segment-sized pieces (one timeout must not cost every second+ # still open). What must hold is that no stretch was closed off unread.+ assert _amplitudes_seen(stt.calls) == set(_AMPLITUDES), (+ "a stretch of the recording was never sent to the provider at all — "+ "audio was closed off unread")@@ -186,19 +209,31 @@ async def test_the_final_transcription_is_retried(monkeypatch) -> None: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"+ # The remainder leaves in segment-sized pieces, so the scripted provider is+ # asked once per piece — what matters is that the retry recovered the text+ # rather than losing it.+ assert "the words" in str(captured.get("raw_text") or "")assert captured.get("stt_error") is None@pytest.mark.asyncioasync def test_the_retry_gives_up_instead_of_hanging(monkeypatch) -> None:- """A genuinely dead provider must not turn into an endless retry loop."""+ """A genuinely dead provider must not turn into an endless retry loop.++ With the remainder finalized piece by piece, "give up" needs a second+ bound: retrying every piece three times would make a five-minute dictation+ spend minutes proving the provider is still down, with the user watching.+ Consecutive total failures end the pass instead — the audio is kept, so+ Restore can try again once the provider is back.+ """stt = _ScriptedSTT(fail_first=99)cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=0.5)captured = await _run_dictation(monkeypatch, stt, cfg, wait_for_calls=0)- assert len(stt.calls) == pipeline_mod._DICTATION_FINAL_ATTEMPTS+ assert len(stt.calls) == (+ pipeline_mod._DICTATION_FINAL_ATTEMPTS * pipeline_mod._DICTATION_FINAL_DEAD_PIECES+ )assert captured.get("raw_text") == ""# The failure survives to the delivery half, which is what separates# "the provider rejected us" from "you said nothing".diff --git a/tests/unit/speech/test_dictation_pause_does_not_truncate.py b/tests/unit/speech/test_dictation_pause_does_not_truncate.pynew file mode 100644index 0000000000..093ba976dd--- /dev/null+++ b/tests/unit/speech/test_dictation_pause_does_not_truncate.py@@ -0,0 +1,338 @@+"""A pause in the middle of a dictation must not cost the words after it.++The reported symptom: speak, stop to think for ten-odd seconds while still+holding the key, speak again — and everything after the pause is missing, while+the bar kept showing an active dictation the whole time. The live log of that+session shows the mechanism in full:++* the live preview re-uploaded the whole open tail on every tick, so a pause was+ billed as a request per tick while producing no text;+* Groq answered ``429 Too Many Requests``, and a refused call correctly leaves+ its segment OPEN — so the tail grew, and the next tick uploaded even more;+* from there each round cost more than the last, the uploads stalled the event+ loop the microphone was being drained on, and the capture queue's drop-oldest+ policy deleted real speech to keep up (``Mic closed (drops=94)`` — 9.4 s);+* and the silence itself came back as invented sentences, which is what put+ "Thank you for watching!" in the middle of a German dictation.++What is pinned here is the shape that breaks that chain: silence is never+uploaded, a backlog is drained in one tick rather than one segment per tick, a+failed call backs off instead of hammering, and the final pass goes out in+pieces so one bad piece cannot cost the whole remainder.++Every judgement about silence is made on ENERGY, never on the text that came+back (AP-27) — a content rule cannot tell a hallucination from a real sentence.+"""++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++#: What a transcription model does with silence. Not a joke: this exact string+#: is in the maintainer's dictation history, in the middle of a German sentence.+HALLUCINATION = "Thank you for watching!"+++def _word(index: int, seconds: float = 0.5) -> bytes:+ """A stretch of "speech" whose amplitude identifies it uniquely.++ Being able to tell WHICH words reached the provider is the whole point:+ "some audio was transcribed" is exactly the claim the broken version could+ also make.+ """+ amplitude = 4_000 + index * 500+ samples = int(seconds * 16_000)+ return (np.ones(samples, dtype=np.int16) * amplitude).tobytes()+++def _silence(seconds: float) -> bytes:+ return np.zeros(int(seconds * 16_000), dtype=np.int16).tobytes()+++class _MarkerSTT:+ """Reports which marker words a piece of audio contains.++ Mimics the real failure modes: silence comes back as a hallucinated+ sentence (never as ``""``), and the first ``fail_first`` calls are refused+ the way a rate limit refuses them.+ """++ def __init__(self, *, fail_first: int = 0) -> None:+ self.calls: list[bytes] = []+ self.silent_calls = 0+ self._fail_first = fail_first++ 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("429 Too Many Requests")+ samples = np.frombuffer(pcm, dtype=np.int16)+ amplitudes = {int(v) for v in np.unique(np.abs(samples)) if v}+ words = [f"w{(a - 4_000) // 500}" for a in sorted(amplitudes)]+ if not words:+ # Every real transcription model does this, and it is why silence+ # must never be uploaded in the first place.+ self.silent_calls += 1+ return SimpleNamespace(text=HALLUCINATION, language="en")+ return SimpleNamespace(text=" ".join(words), language="de")+++class _ScriptedMic:+ """Yields a fixed script of chunks, then holds the stream open."""++ script: list[bytes] = []++ 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 type(self).script:+ yield SimpleNamespace(pcm=chunk)+ # Let the probe run between chunks, so the test exercises the real+ # interleaving of "audio arrives while a transcription is in flight"+ # instead of handing the loop a finished buffer.+ await asyncio.sleep(0)+ await asyncio.Event().wait()+++def _pipeline(bus: EventBus, stt: _MarkerSTT, 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(+ monkeypatch,+ *,+ script: list[bytes],+ stt: _MarkerSTT,+ cfg: DictationConfig,+) -> dict[str, object]:+ """Record the whole script, release the key, return ``_finish``'s kwargs."""+ bus = EventBus()+ pipe = _pipeline(bus, stt, cfg)+ _ScriptedMic.script = script+ 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 recording itself to be complete rather than for a fixed+ # sleep: a timing-based assertion on a loaded box is a flake generator.+ total = sum(len(c) for c in script)+ deadline = asyncio.get_running_loop().time() + 10.0+ while asyncio.get_running_loop().time() < deadline:+ if pipe._dictation_task is None or pipe._dictation_task.done():+ break+ await asyncio.sleep(0.01)+ # The drain has seen everything once the probe can no longer grow.+ if total and stt.calls and asyncio.get_running_loop().time() > deadline - 9.0:+ break+ pipe.stop_dictation()+ await asyncio.wait_for(pipe._dictation_task, timeout=10.0)+ return captured+++async def test_words_after_a_long_pause_still_reach_the_transcript(monkeypatch) -> None:+ """The reported bug, end to end.++ Speech, a long think-pause, more speech. Before the fix the pause was+ uploaded tick after tick, which is what spent the rate limit and then took+ the words after it down with the rest.+ """+ script = [_word(0), _word(1), _silence(12.0), _word(2), _word(3)]+ stt = _MarkerSTT()+ cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=2.0)++ captured = await _run(monkeypatch, script=script, stt=stt, cfg=cfg)++ text = str(captured.get("raw_text") or "")+ for marker in ("w0", "w1", "w2", "w3"):+ assert marker in text, f"{marker} was spoken but never made it into {text!r}"+++async def test_a_pause_is_never_uploaded(monkeypatch) -> None:+ """Silence costs neither a request nor an invented sentence.++ Both halves matter: the requests are what ran into the rate limit, and the+ invented sentence is what the user found in the middle of their own text.+ """+ script = [_word(0), _silence(12.0), _word(1)]+ stt = _MarkerSTT()+ cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=2.0)++ captured = await _run(monkeypatch, script=script, stt=stt, cfg=cfg)++ assert stt.silent_calls == 0, "a silent stretch was sent to the provider"+ assert HALLUCINATION not in str(captured.get("raw_text") or "")+++async def test_the_open_tail_never_grows_past_one_segment(monkeypatch) -> None:+ """No upload may keep getting bigger.++ This is the spiral itself: an ever-growing tail means every tick uploads+ more audio than the last, until the work of building those requests stalls+ the loop the microphone is drained on. The cap holds even when the audio+ arrives faster than the probe can close segments.+ """+ script = [_word(i, seconds=1.0) for i in range(12)]+ stt = _MarkerSTT()+ cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=2.0)++ await _run(monkeypatch, script=script, stt=stt, cfg=cfg)++ segment_bytes = int(2.0 * BYTES_PER_SECOND)+ biggest = max(len(c) for c in stt.calls)+ assert biggest <= segment_bytes, (+ f"an upload reached {biggest / BYTES_PER_SECOND:.1f}s of audio — the "+ f"tail is growing without bound again"+ )+++async def test_refused_calls_do_not_cost_the_words(monkeypatch) -> None:+ """A refused call leaves its audio open, so a later attempt still reads it.++ The refusal under test is the real one: HTTP 429. The recording is untouched+ by it — the words have to arrive in full once a call gets through.+ """+ script = [_word(0), _word(1), _word(2)]+ stt = _MarkerSTT(fail_first=2)+ cfg = DictationConfig(partial_interval_s=0.02, segment_seconds=1.0)++ captured = await _run(monkeypatch, script=script, stt=stt, cfg=cfg)++ text = str(captured.get("raw_text") or "")+ for marker in ("w0", "w1", "w2"):+ assert marker in text, f"{marker} was lost to the refused calls: {text!r}"+++async def test_one_dead_piece_does_not_cost_the_others(monkeypatch) -> None:+ """The point of finalizing in pieces.++ A piece whose every attempt fails is a real loss — but a bounded one. As a+ single upload of the whole remainder, that same failure took every second+ still open with it, which is how a transient error at the end used to cost+ a dictation the user had already finished speaking.+ """++ class _OneBadPiece(_MarkerSTT):+ async def transcribe_pcm(self, pcm: bytes, language: str | None = None):+ samples = np.frombuffer(pcm, dtype=np.int16)+ if 4_000 in {int(v) for v in np.unique(np.abs(samples))}:+ self.calls.append(bytes(pcm))+ raise RuntimeError("429 Too Many Requests")+ return await super().transcribe_pcm(pcm, language)++ script = [_word(i, seconds=1.0) for i in range(4)]+ stt = _OneBadPiece()+ cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=1.0)++ captured = await _run(monkeypatch, script=script, stt=stt, cfg=cfg)++ text = str(captured.get("raw_text") or "")+ assert "w0" not in text, "the failing piece was expected to be lost"+ for marker in ("w1", "w2", "w3"):+ assert marker in text, (+ f"{marker} was taken down by an unrelated failing piece: {text!r}"+ )+++async def test_the_final_pass_goes_out_in_pieces(monkeypatch) -> None:+ """One timeout must not cost every second still open.++ With the preview off, everything lands on the final pass. It has to leave in+ segment-sized pieces — a single upload of the whole remainder is the shape+ where one failure loses all of it.+ """+ script = [_word(i, seconds=1.0) for i in range(6)]+ stt = _MarkerSTT()+ cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=2.0)++ captured = await _run(monkeypatch, script=script, stt=stt, cfg=cfg)++ assert len(stt.calls) > 1, "the whole remainder went out as one upload"+ text = str(captured.get("raw_text") or "")+ for marker in (f"w{i}" for i in range(6)):+ assert marker in text, f"{marker} was lost by the chunked final pass: {text!r}"+++async def test_a_recording_that_ends_early_is_reported(monkeypatch) -> None:+ """A truncated transcript must never be presented as the whole thing.++ The handoff buffer a dictation borrows from the wake loop raises once its+ replay window is exceeded. That killed the drain task, and the failure was+ swallowed with the teardown's cancellations — so the user got a transcript+ that stopped halfway with nothing anywhere saying why.+ """++ class _DyingMic(_ScriptedMic):+ async def stream(self): # type: ignore[no-untyped-def]+ yield SimpleNamespace(pcm=_word(0))+ raise RuntimeError("Voice input exceeded the 30-second replay window")++ stt = _MarkerSTT()+ cfg = DictationConfig(partial_interval_s=0.0, segment_seconds=2.0)+ bus = EventBus()+ pipe = _pipeline(bus, stt, cfg)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _DyingMic)++ 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+ await asyncio.wait_for(pipe._dictation_task, timeout=10.0)++ assert "replay window" in str(captured.get("stt_error") or ""), (+ "the recording died and the dictation reported nothing about it"+ )