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): the end of what you said stops disappearing (BUG-162)
Haraldde4c1ea528b3
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 8539890d06..abec2d7f58 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -11368,3 +11368,89 @@ that IS necessary still costs one round of re-granting. A Developer-ID signingidentity is the structural fix. The rebuild guard also arms only after thefirst rebuild it observes, so an install already caught in the loop pays forone more round before it stops.++## BUG-162: dictation silently drops the end of what was said — a deep queue that never applied, a truncation guard that fired once in 797 recordings, and a loss nothing reported (HIGH, FIXED 2026-08-21)++**Symptom (reported 2026-08-21).** "Sometimes the last sentence just is not+transcribed." Intermittent, never reproducible on demand, and every affected+dictation reported itself as a clean success.++**Evidence.** 797 consecutive dictations from the local flight recorder, seven+days. Three independent causes, each producing the same user-visible symptom.++**Root cause 1 — the bulk queue depth never applied to a real dictation.**+`_capture_dictation_input()` opens its fallback capture with+`_DICTATION_CAPTURE_QUEUE_CHUNKS` (10 s), commented "the defence is depth".+That path only runs when NO wake stream exists. With a wake word configured —+the default, and the shipped state — every dictation instead borrows the wake+stream, which is opened at `DEFAULT_QUEUE_CHUNKS` (2 s) because a detector+wants fresh audio, not deep buffers. So the defence written for dictation was+dead code on exactly the installs that needed it. When the event loop stalls+longer than the queue holds, `MicrophoneCapture._safe_put` drops the OLDEST+frame per arrival and that speech is gone for good: it never became a chunk+anyone read, so no retry, no re-read and no Restore reaches it. Measured: 448+of 797 dictations (56 %) lost frames; 177 s of 10 293 s recorded; worst single+case 7.4 s missing from a 15.4 s recording. Confirmed independently by+differencing the recording's wall time against its captured audio seconds,+which reproduces the same figures.++**Root cause 2 — the truncation guard was calibrated out of reach.**+`_repair_truncated_read` re-reads a final-pass window whose transcript carries+fewer than `_DICTATION_TRUNCATION_TOKENS_PER_VOICED_S` tokens per voiced+second. At 1.0 that demanded a recognizer swallow some 60 % of a window before+anyone looked — real speech in the sample runs at a median 2.5 tokens per+second of WHOLE recording, pauses included. A dropped last sentence is a fifth+of the text, not two thirds, so the ordinary case never qualified. Across 797+dictations the repair fired **once**. Second gate, independent of the first:+the guard returned immediately unless the window held two or more speech runs,+so continuous speech — no pause to split at — was believed in full whatever it+came back as. Live examples, all with zero capture dropouts and+`truncation_repairs:0`: an 11.9 s recording ending "…interested in context+management **for**", a 15.7 s one ending "…as it right now is, **then**".++**Root cause 3 — nothing reported the loss.** `lost_audio_s` (recorded but+never transcribed) degrades the outcome to `partial` and offers Restore.+Capture dropouts had no equivalent: `audio_dropouts` / `audio_dropout_ms` went+to telemetry only, so a recording with seconds missing from the middle was+delivered as `inserted` with no caveat anywhere.++**Fix (2026-08-21).**+(a) `MicrophoneCapture.set_queue_depth()` re-bounds the bridge queue in place,+and `_capture_dictation_input()` deepens a BORROWED stream for the dictation+and restores the shallow bound on the way out — including on the crash path,+or this trades itself for a wake word scored against stale audio. In place, not+a fresh queue: replacing the object strands the drain already parked in+`get()`, which would stop the recording outright.+(b) `_DICTATION_TRUNCATION_TOKENS_PER_VOICED_S` 1.0 → 1.3 (78 wpm of actual+speech, against the sample's 150 wpm median), and a window with a single+speech run is now halved at its quietest middle moment+(`jarvis.dictation.segment.halve_at_quietest`) instead of returning early. The+merged reading still only wins by carrying MORE speech, so a false positive+costs one discarded read and never a worse transcript.+(c) `_finish_dictation(dropped_audio_s=…)` degrades to `partial` above 0.5 s —+one word at the measured speaking rate — and says so. Deliberately kept apart+from `lost_audio_s` and deliberately silent about Restore: the audio it would+re-read is the audio that was never recorded. Marks 10.8 % of the sample, every+one of them a real loss.++**Guards.** `tests/unit/audio/test_capture_overflow.py::test_the_depth_can_be_raised_while_the_stream_is_open`,+`::test_a_deepened_queue_stops_dropping_what_the_shallow_one_lost`,+`::test_the_queue_object_survives_a_resize`,+`::test_a_depth_below_one_is_refused`,+`tests/unit/speech/test_dictation_mic_handoff.py::test_the_borrowed_stream_is_deepened_for_the_dictation_and_handed_back`,+`::test_the_depth_is_restored_even_when_the_dictation_blows_up`,+`tests/unit/dictation/test_truncation_repair.py::test_continuous_speech_that_came_back_short_is_reread_in_halves`,+`::test_a_halved_reread_that_finds_no_more_speech_keeps_the_original`,+`::test_halving_covers_the_whole_buffer_with_an_overlap_at_the_seam`,+`tests/unit/dictation/test_partial_outcome.py::test_dropped_capture_audio_degrades_the_outcome_and_says_so`,+`::test_a_loss_too_small_to_have_taken_a_word_stays_a_success`,+`::test_both_kinds_of_loss_are_reported_in_one_sentence_each`.++**Still open.** What STALLS the loop long enough to overflow a 2 s queue is not+diagnosed — the deeper bound raises the ceiling to 10 s, it does not remove the+cause. There is no event-loop lag monitor anywhere in the process, so the stall+is currently invisible; the dictation lane runs a local preview decode every+1.2 s beside the drain, which is the first thing to measure. Cause 2's floor+also remains a density heuristic: it cannot catch a truncation that drops only+a short final clause, because no token count distinguishes that from ordinary+speech. A recognizer offering word timestamps would settle it directly.diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.pyindex d0dbaa431a..0b4d40a8c4 100644--- a/jarvis/audio/capture.py+++ b/jarvis/audio/capture.py@@ -678,6 +678,33 @@ def _resolve_input_device(return None+class _ResizableQueue(asyncio.Queue[AudioChunk]):+ """The capture bridge queue, whose bound may change while it is in use.++ One microphone stream serves consumers with opposite needs. A wake detector+ wants a SHALLOW bound so a CPU that falls behind sees near-present audio; a+ dictation wants a DEEP one, because every frame is a word the user said and+ the drop-oldest policy deletes speech rather than staleness. The stream is+ handed from the first to the second mid-flight (the wake handoff), so the+ bound has to move with it.++ ``asyncio.Queue`` exposes ``maxsize`` read-only and offers no resize. The+ obvious alternative — build a new queue and copy the items over — silently+ strands any consumer already parked in ``get()`` on the old object, which on+ this path is the drain that owns the recording. So the bound is moved in+ place instead: ``_maxsize`` is read afresh by ``full()`` on every put, so a+ raise takes effect on the very next frame and nobody is left waiting.+ """++ #: Declared for the type checker: the base class keeps it as a plain+ #: attribute behind the read-only ``maxsize`` property.+ _maxsize: int++ def set_maxsize(self, value: int) -> None:+ """Change the bound. Never below one — a zero bound means UNbounded."""+ self._maxsize = max(1, int(value))++class MicrophoneCapture:"""Async wrapper around sounddevice.InputStream.@@ -757,7 +784,11 @@ class MicrophoneCapture:# silence and the wake word are seen near-present, not 2 s late — the# "stuck listening / missed wake on a weaker laptop" bug. A machine that# keeps up never fills the queue, so the depth is invisible there.- self._queue: asyncio.Queue[AudioChunk] = asyncio.Queue(+ #+ # The depth is not frozen at construction: a stream opened for wake is+ # handed to a dictation without being reopened, and the two want+ # opposite bounds (see ``set_queue_depth``).+ self._queue: _ResizableQueue = _ResizableQueue(maxsize=max(1, int(max_queue_chunks)))self._stream: sd.InputStream | None = None@@ -1243,6 +1274,29 @@ class MicrophoneCapture:"""Number of frames lost due to a full queue."""return self._drops+ @property+ def queue_depth(self) -> int:+ """Current bound of the bridge queue, in chunks."""+ return self._queue.maxsize++ def set_queue_depth(self, max_queue_chunks: int) -> int:+ """Re-bound the bridge queue for a new kind of consumer. Returns the old bound.++ The one lever that decides whether a slow moment costs WORDS. When the+ event loop stalls longer than the queue holds, ``_safe_put`` starts+ dropping the oldest frame per arrival and that speech is gone for good —+ no retry reaches it, because it never became a chunk anyone read. A+ bulk consumer therefore raises the bound for as long as it owns the+ stream and puts it back afterwards, so the wake detector does not+ inherit a depth that would let it score seconds-stale audio.++ Takes effect immediately, including for a consumer already waiting in+ ``stream()`` — the queue object itself never changes identity.+ """+ previous = self._queue.maxsize+ self._queue.set_maxsize(max_queue_chunks)+ return previous+@propertydef restart_count(self) -> int:"""Number of stream restarts triggered by the stall watchdog."""diff --git a/jarvis/dictation/segment.py b/jarvis/dictation/segment.pyindex f1523a9112..c756b5af39 100644--- a/jarvis/dictation/segment.py+++ b/jarvis/dictation/segment.py@@ -108,6 +108,51 @@ def quietest_cut(#: costs a whole request to be told so._MIN_WINDOW_S = 1.0+#: Audio the two halves of a re-read share. Same job as the overlap between+#: quality windows: a word sitting on the seam is spoken in full inside one of+#: them, and the duplicate that creates is removed from the TEXT afterwards.+#: Small, because the cut already went looking for the quietest moment.+_REREAD_OVERLAP_S = 0.4+++def halve_at_quietest(+ pcm: bytes,+ *,+ bytes_per_second: int = 16_000 * BYTES_PER_SAMPLE,+ overlap_s: float = _REREAD_OVERLAP_S,+) -> list[tuple[int, int]]:+ """Two overlapping halves of ``pcm``, split at its quietest middle moment.++ The re-read shape for a window a recognizer stopped short on WITHOUT+ leaving the energy scan a sustained pause to split at — continuous speech+ that simply arrived half-transcribed. :func:`speech_runs` reports one run+ for that recording and has nothing to offer; halving it does, because the+ second request is handed audio that begins where the delivered text went+ quiet, and a recognizer that truncates a long read rarely truncates a short+ one at the same place.++ Not a substitute for the pause split: a recording that HAS pauses should be+ cut there, since those seams cost nothing. This is the fallback for the one+ that does not.++ Returns ``[]`` when the buffer is too short for the split to mean anything,+ which the caller reads as "keep what the recognizer said".+ """+ total = len(pcm)+ min_half = int(_MIN_WINDOW_S * bytes_per_second)+ if total < 2 * min_half:+ return []+ cut = quietest_cut(pcm, _align(total // 2), bytes_per_second)+ if cut < min_half or total - cut < min_half:+ # The quiet scan landed somewhere that would leave a sliver. The plain+ # midpoint is no worse a guess and keeps both halves worth reading.+ cut = _align(total // 2)+ overlap = _align(max(0, int(overlap_s * bytes_per_second)))+ return [+ (0, _align(min(total, cut + overlap))),+ (_align(max(0, cut - overlap)), total),+ ]+def quality_windows(pcm: bytes,@@ -338,6 +383,7 @@ def is_silent_segment(pcm: bytes, *, session_peak: float = 0.0) -> bool:__all__ = ["BYTES_PER_SAMPLE",+ "halve_at_quietest","is_silent_segment","quality_windows","quietest_cut",diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 150db7d347..587dd5b5c4 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1197,7 +1197,36 @@ _DICTATION_FINAL_DEAD_PIECES = 2# verdict is judged on ENERGY versus token count, never on what the text says# (AP-27's lesson); the repair re-reads the window split at its pauses and the# longer reading wins.-_DICTATION_TRUNCATION_TOKENS_PER_VOICED_S = 1.0+#+# Raised from 1.0 after measuring what it actually caught: across 797 live+# dictations the repair fired ONCE. Real speech in that sample runs at a median+# 2.5 tokens per second of WHOLE recording — pauses included, so the voiced rate+# is higher still. A floor of 1.0 therefore demanded that a recognizer swallow+# some 60 % of a window before anyone even looked, which is why every ordinary+# truncation (a dropped last sentence is a fifth of the text, not two thirds)+# went unexamined.+#+# 1.3 is where the two costs cross. Tokens-per-WHOLE-second is a lower bound on+# tokens-per-voiced-second, so the share of the sample under a threshold bounds+# the re-read rate from above: at most 12.9 % here, against 7.8 % at the old+# floor, and a false positive only ever costs one extra read whose result is+# discarded unless it carries MORE speech. In words per minute of ACTUAL speech+# — every pause already excluded — the floor now sits at 78 wpm, against the+# 150 wpm median of the sample. Anything under that is worth one confirming+# read (``test_a_healthy_window_is_not_reread`` pins the healthy side).+_DICTATION_TRUNCATION_TOKENS_PER_VOICED_S = 1.3++# How much audio the CAPTURE may lose before the dictation says so. Frames the+# queue dropped are not a transcription failure — they never became audio at+# all, so no retry, no re-read and no Restore can bring them back; the only+# honest thing left is to tell the user their recording has a hole in it.+#+# The floor is a WORD. At the measured 2.5 tokens per second of speech one word+# is ~400 ms, so anything under half a second cannot have taken a whole one and+# saying "words are missing" would be the wrong kind of true. Across the same+# 797 live dictations this marks 10.8 % of them — every one a real loss, and+# every one previously delivered as if it were complete.+_DICTATION_DROPPED_AUDIO_NOTICE_S = 0.5# 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,@@ -1236,7 +1265,16 @@ class _SessionInputBuffer:*,initial: tuple[AudioChunk, ...] = (),max_buffer_bytes: int = _SESSION_START_BUFFER_MAX_BYTES,+ capture: MicrophoneCapture | None = None,) -> None:+ #: The still-open stream behind this handoff, when the frames come from+ #: a live microphone rather than a test's hand-fed list. Carried purely+ #: so a consumer that takes the stream over can re-bound its queue for+ #: the kind of consumer IT is — a dictation records every frame, while+ #: the wake detector this stream was opened for wants shallow and fresh+ #: (``MicrophoneCapture.set_queue_depth``). ``None`` means there is+ #: nothing to re-bound, which every caller treats as fine.+ self.capture = captureself._chunks: deque[tuple[int, AudioChunk]] = deque()self._max_buffer_bytes = max(1, int(max_buffer_bytes))self._retained_bytes = 0@@ -7115,7 +7153,7 @@ class SpeechPipeline:max_queue_chunks=REALTIME_QUEUE_CHUNKS,device_priority=self._input_priority,) as mic:- buffer = _SessionInputBuffer()+ buffer = _SessionInputBuffer(capture=mic)async def _unmuted_capture() -> AsyncIterator[AudioChunk]:async for chunk in mic.stream():@@ -7204,12 +7242,37 @@ class SpeechPipeline:wake loop re-arms its own microphone as soon as the dictation's block onactivation lifts — including on the crash path, because the release runsin a ``finally``.++ Either way the stream ends up bound for a BULK consumer. That mattered+ more than it looked: the borrowed path is the one that actually runs on+ any install with a wake word, and it used to inherit the wake stream's+ shallow default. So the deep queue written for dictation below was dead+ code on exactly the machines that needed it, and a stalled loop cost+ seconds of speech — measured on the maintainer's box at 7.4 s gone from+ a 15.4 s recording, with nothing anywhere saying so."""buffer = await self._claim_wake_capture_for_dictation()if buffer is not None:+ restore_depth: int | None = None+ capture = getattr(buffer, "capture", None)+ if capture is not None:+ try:+ restore_depth = capture.set_queue_depth(+ _DICTATION_CAPTURE_QUEUE_CHUNKS+ )+ except Exception: # noqa: BLE001 — a bound is a safeguard, never a gate+ log.debug("dictation could not deepen the capture queue", exc_info=True)try:yield bufferfinally:+ if capture is not None and restore_depth is not None:+ # Hand the wake detector its shallow bound back. Leaving the+ # deep one on would trade this fix for the other failure:+ # a wake word scored against seconds-stale audio.+ try:+ capture.set_queue_depth(restore_depth)+ except Exception: # noqa: BLE001 — teardown never fails a dictation+ log.debug("capture queue depth not restored", exc_info=True)# ``close()`` sets ``released`` before it awaits anything, so# the wake owner is freed even if this task is being cancelled.await buffer.close()@@ -7638,7 +7701,7 @@ class SpeechPipeline:else tuple(recent_chunks))self._discard_wake_preroll()- handoff_buffer = _SessionInputBuffer(initial=initial)+ handoff_buffer = _SessionInputBuffer(initial=initial, capture=mic)self._wake_handoff_buffer = handoff_bufferself._wake_handoff_ready.set()return handoff_buffer@@ -11257,17 +11320,27 @@ class SpeechPipeline:A recognizer handed audio with a sustained mid-recording pause canstop at the pause and silently drop everything after it — thetranscript arrives fluent, punctuated, and half the length of what- was said. Detected here on energy alone: when the piece holds more- than one speech run and the transcript's token count is far below- what its VOICED seconds must have contained- (``_DICTATION_TRUNCATION_TOKENS_PER_VOICED_S``), the piece is- re-read as its individual runs and the merged result replaces the+ was said. Detected here on energy alone: when the transcript's+ token count is far below what its VOICED seconds must have+ contained (``_DICTATION_TRUNCATION_TOKENS_PER_VOICED_S``), the+ piece is re-read in parts and the merged result replaces theoriginal only when it actually carries more speech.- The runs are told the language the long window just detected+ Where to cut is decided by the audio, in that order of preference:++ * **At its pauses**, when the energy scan found more than one+ speech run. Those seams cost nothing — no word sits on them.+ * **In half at its quietest middle moment**, when it found only+ one. That case used to return early and stand: continuous speech+ that came back half-transcribed had no pause to split on, so the+ guard looked at the most ordinary truncation there is and did+ nothing. A recognizer that stops short on a long read rarely+ stops at the same place on a short one.++ The parts are told the language the long window just detectedrather than asked to detect it themselves — a short clip guessingits language is the translation trap the long windows exist to- avoid. A run that cannot be read keeps the original transcript: a+ avoid. A part that cannot be read keeps the original transcript: adropped middle is worse than the dropped tail it would repair."""nonlocal truncation_repairs@@ -11275,25 +11348,48 @@ class SpeechPipeline:merge_transcripts,transcript_token_count,)- from jarvis.dictation.segment import speech_runs+ from jarvis.dictation.segment import (+ halve_at_quietest,+ is_silent_segment,+ speech_runs,+ )runs = speech_runs(piece,session_peak=session_peak,bytes_per_second=bytes_per_second,)- if len(runs) < 2:+ if not runs: # No speech to be missing any of.return textvoiced_s = sum(end - start for start, end in runs) / bytes_per_secondtokens = transcript_token_count(text)if tokens >= voiced_s * _DICTATION_TRUNCATION_TOKENS_PER_VOICED_S:return text+ split_at_pauses = len(runs) > 1+ if not split_at_pauses:+ # Halve the RUN, never the window. A window is mostly silence+ # whenever the speaker paused to think, and halving that hands+ # one request a stretch with no speech in it — the single most+ # reliable way to make a recognizer invent a sentence, and a+ # request spent to be told nothing. Offsets are mapped back so+ # the reads still come from the window's own audio.+ speech_start, speech_end = runs[0]+ halves = halve_at_quietest(+ piece[speech_start:speech_end],+ bytes_per_second=bytes_per_second,+ )+ if not halves: # Too short to halve — nothing useful to ask twice.+ return text+ runs = [+ (speech_start + start, speech_start + end)+ for start, end in halves+ ]log.warning("final dictation window looks truncated (%d tokens for %.1fs "- "of speech in %d runs) — re-reading it split at its pauses.",+ "of speech) — re-reading it %s.",tokens,voiced_s,- len(runs),+ "split at its pauses" if split_at_pauses else "in two halves",)run_ask = language if (not ask_for or ask_for == "auto") else ask_forparts: list[str] = []@@ -11301,6 +11397,12 @@ class SpeechPipeline:run_piece = piece[start:end]if len(run_piece) < min_bytes:continue+ if is_silent_segment(run_piece, session_peak=session_peak):+ # Costs nothing to check and saves a request over silence,+ # which is the one input a recognizer answers with words+ # nobody said. Skipped, never counted as a failed read: a+ # piece with no speech in it has nothing to contribute.+ continuerun_text, run_read = await _read_piece(run_piece, ask_for=run_ask or None)@@ -11692,6 +11794,7 @@ class SpeechPipeline:# the failure that actually cost the user something.stt_error=capture_error or lost_reason or stt_error,lost_audio_s=lost_audio_s,+ dropped_audio_s=quality_metrics.dropout_duration_ms / 1000.0,audio=bytes(buffer),stt_providers=tuple(stt_providers),stt_models=tuple(stt_models),@@ -11920,6 +12023,7 @@ class SpeechPipeline:hung_up: bool,stt_error: str | None = None,lost_audio_s: float = 0.0,+ dropped_audio_s: float = 0.0,audio: bytes | None = None,stt_providers: tuple[str, ...] = (),stt_models: tuple[str, ...] = (),@@ -11961,6 +12065,15 @@ class SpeechPipeline:and to keep its audio. Defaults to zero so every existing caller (andthe crash path below) keeps today's behaviour exactly.+ ``dropped_audio_s`` is the OTHER way to end up missing words, and it is+ kept apart from ``lost_audio_s`` because the two owe the user different+ sentences. Lost audio was recorded and never read — a retry could still+ read it, which is what Restore offers. Dropped audio was never recorded:+ the capture queue overflowed while the loop was busy and those frames+ are gone, so promising Restore would point at a button that cannot help.+ Both degrade the outcome to ``partial``; only the first one promises+ anything.+``audio`` is the session's raw PCM; it is written to a local sidecaronly when the dictation left the user missing words AND they allow it(``[dictation].keep_failed_audio``), which is what a later Restore@@ -12266,6 +12379,37 @@ class SpeechPipeline:stt_error or "unknown",)+ # The other hole, and the one nothing used to mention: frames the+ # CAPTURE dropped. When the event loop stalls longer than the mic+ # queue holds, ``_safe_put`` deletes the oldest frame per arrival and+ # that speech never becomes audio anyone can read — measured across 797+ # live dictations at 56 % of them losing something and one losing 7.4 s+ # out of 15.4 s, every one of them delivered as a clean success.+ #+ # Said FIRST when both holes are present: this is the unrecoverable+ # one. It also deliberately does not mention Restore — the audio it+ # would re-read is the audio that was never recorded.+ if (+ dropped_audio_s >= _DICTATION_DROPPED_AUDIO_NOTICE_S+ and not hung_up+ and cleaned.strip()+ ):+ outcome_name = "partial"+ detail = " ".join(+ part+ for part in (+ f"About {dropped_audio_s:.1f}s of audio was lost while "+ "recording, so words are missing.",+ detail,+ )+ if part+ )+ log.warning(+ "dictation degraded to partial: %.1fs of audio never reached "+ "the recording (capture queue overflow) — not recoverable.",+ dropped_audio_s,+ )+# Mark the turn closed BEFORE the publish attempt: this flag answers# "does the teardown still owe a terminal event", and a publish that# raised is not a reason to fire a second, contradictory completion.diff --git a/tests/unit/audio/test_capture_overflow.py b/tests/unit/audio/test_capture_overflow.pyindex ba841d1750..41ab4b211d 100644--- a/tests/unit/audio/test_capture_overflow.py+++ b/tests/unit/audio/test_capture_overflow.py@@ -58,6 +58,72 @@ def test_safe_put_drops_oldest_and_keeps_newest_on_overflow() -> None:assert mic.dropped_frames == 1+# --------------------------------------------------------------------------+# Re-bounding a live stream — the wake mic becomes a dictation mic mid-flight+# --------------------------------------------------------------------------+++def test_the_depth_can_be_raised_while_the_stream_is_open() -> None:+ """A bulk consumer takes a shallow stream over and deepens it.++ Not a hypothetical: with a wake word configured, EVERY dictation borrows+ the wake stream rather than opening its own, so the deep bulk depth written+ for dictation only ever applied on installs with no wake word at all.+ """+ mic = MicrophoneCapture(max_queue_chunks=REALTIME_QUEUE_CHUNKS)++ previous = mic.set_queue_depth(DEFAULT_QUEUE_CHUNKS)++ assert previous == REALTIME_QUEUE_CHUNKS+ assert mic.queue_depth == DEFAULT_QUEUE_CHUNKS+ assert mic.set_queue_depth(previous) == DEFAULT_QUEUE_CHUNKS+ assert mic.queue_depth == REALTIME_QUEUE_CHUNKS+++def test_a_deepened_queue_stops_dropping_what_the_shallow_one_lost() -> None:+ """The whole point: the frames a stall would have deleted are still there."""+ mic = MicrophoneCapture(max_queue_chunks=2)+ mic.set_queue_depth(4)++ for tag in (1, 2, 3, 4):+ mic._safe_put(_chunk(tag))++ drained = []+ while not mic._queue.empty():+ drained.append(mic._queue.get_nowait().timestamp_ns)++ assert drained == [1, 2, 3, 4], drained+ assert mic.dropped_frames == 0+++def test_the_queue_object_survives_a_resize() -> None:+ """Identity matters: a consumer parked in ``get()`` holds the old object.++ Building a fresh queue and copying the items across would leave the+ dictation's drain waiting on a queue nothing puts to again — the recording+ would simply stop, which is the failure this whole change is about.+ """+ mic = MicrophoneCapture(max_queue_chunks=2)+ before = mic._queue+ mic._safe_put(_chunk(7))++ mic.set_queue_depth(9)++ assert mic._queue is before+ assert mic._queue.get_nowait().timestamp_ns == 7+++def test_a_depth_below_one_is_refused() -> None:+ """``asyncio.Queue(0)`` means UNBOUNDED — the opposite of a tight bound."""+ mic = MicrophoneCapture(max_queue_chunks=5)++ mic.set_queue_depth(0)+ assert mic.queue_depth == 1++ mic.set_queue_depth(-3)+ assert mic.queue_depth == 1++def test_safe_put_no_drop_when_not_full() -> None:mic = MicrophoneCapture(max_queue_chunks=8)for tag in range(5):diff --git a/tests/unit/dictation/test_partial_outcome.py b/tests/unit/dictation/test_partial_outcome.pyindex 79c1adfdfe..cd51ecfb22 100644--- a/tests/unit/dictation/test_partial_outcome.py+++ b/tests/unit/dictation/test_partial_outcome.py@@ -30,6 +30,7 @@ from typing import Anyimport pytest+import jarvis.speech.pipeline as pipeline_modfrom jarvis.core.config import DictationConfigfrom jarvis.core.events import DictationCompletedfrom jarvis.dictation.insert import InsertResult@@ -290,6 +291,125 @@ async def test_the_recording_reaches_the_store_with_the_degraded_outcome() -> Noassert is_recoverable(row["outcome_name"]) is True+# --------------------------------------------------------------------------+# The OTHER hole: audio the capture never recorded+# --------------------------------------------------------------------------+#+# Frames the mic queue dropped are not a transcription failure. When the event+# loop stalls longer than the queue holds, the drop-oldest policy deletes the+# oldest frame per arrival and that speech never becomes audio at all — no+# retry reaches it, and neither does Restore, because there is nothing in the+# recording to re-read. Measured across 797 live dictations: 56 % lost frames,+# the worst 7.4 s out of a 15.4 s recording, every one of them delivered as a+# clean success with nothing anywhere saying a word had gone missing.+++async def test_dropped_capture_audio_degrades_the_outcome_and_says_so() -> None:+ pipe, events, _recorded = _pipeline()++ await pipe._finish_dictation(+ raw_text="the half of it that reached the recording",+ language="en",+ duration_s=12.0,+ target="chat",+ hung_up=False,+ dropped_audio_s=2.4,+ )++ completed = _completed(events)+ assert completed.outcome == "partial"+ assert "2.4s" in completed.detail+ assert "words are missing" in completed.detail+ # Never Restore: the audio it would re-read is the audio never recorded.+ assert "Restore" not in completed.detail+++async def test_a_loss_too_small_to_have_taken_a_word_stays_a_success() -> None:+ """One dropped 32 ms frame is not "words are missing".++ Degrading on any loss at all would mark 56 % of real dictations, which is+ the same as marking none: a caveat on everything says nothing about+ anything. The floor is one WORD of speech.+ """+ pipe, events, _recorded = _pipeline()++ await pipe._finish_dictation(+ raw_text="all of it arrived",+ language="en",+ duration_s=4.0,+ target="chat",+ hung_up=False,+ dropped_audio_s=pipeline_mod._DICTATION_DROPPED_AUDIO_NOTICE_S - 0.05,+ )++ assert _completed(events).outcome == "chat"+ assert _completed(events).detail == ""+++async def test_there_is_no_partial_of_nothing_when_capture_dropped_frames() -> None:+ """An empty transcript stays ``empty``/``failed``, exactly as for lost audio."""+ pipe, events, _recorded = _pipeline()++ await pipe._finish_dictation(+ raw_text="",+ language="en",+ duration_s=9.0,+ target="chat",+ hung_up=False,+ dropped_audio_s=5.0,+ )++ assert _completed(events).outcome == "empty"+++async def test_a_cancelled_dictation_is_not_degraded_by_dropped_frames() -> None:+ """The user called it off; unread seconds after that are their decision."""+ pipe, events, _recorded = _pipeline()++ await pipe._finish_dictation(+ raw_text="never mind",+ language="en",+ duration_s=6.0,+ target="chat",+ hung_up=True,+ dropped_audio_s=4.0,+ )++ assert _completed(events).outcome == "cancelled"+++async def test_both_kinds_of_loss_are_reported_in_one_sentence_each() -> None:+ """They are different losses and only one of them promises Restore."""+ pipe, events, _recorded = _pipeline(+ DictationConfig(history_enabled=False, keep_failed_audio=True)+ )++ await pipe._finish_dictation(+ raw_text="what survived both holes",+ language="en",+ duration_s=40.0,+ target="chat",+ hung_up=False,+ lost_audio_s=8.0,+ dropped_audio_s=3.0,+ )++ completed = _completed(events)+ assert completed.outcome == "partial"+ assert "3.0s of audio was lost while recording" in completed.detail+ assert "8.0s of the recording could not be transcribed" in completed.detail+ # The Restore offer belongs to the half that has a recording to restore.+ assert completed.detail.index("was lost while recording") < completed.detail.index(+ "could not be transcribed"+ )+ assert "Restore" in completed.detail++@pytest.mark.asyncioasync def test_the_default_keeps_every_existing_caller_on_todays_behaviour() -> None:"""``lost_audio_s`` defaults to zero on purpose.diff --git a/tests/unit/dictation/test_truncation_repair.py b/tests/unit/dictation/test_truncation_repair.pyindex e7cf161b86..a0b0f357eb 100644--- a/tests/unit/dictation/test_truncation_repair.py+++ b/tests/unit/dictation/test_truncation_repair.py@@ -24,7 +24,7 @@ from typing import Anyfrom jarvis.core.config import DictationConfigfrom jarvis.core.events import DictationCompletedfrom jarvis.dictation.merge import transcript_token_count-from jarvis.dictation.segment import speech_runs+from jarvis.dictation.segment import halve_at_quietest, speech_runsfrom jarvis.speech.pipeline import SpeechPipeline# 16 kHz mono int16 — the capture contract every dictation records under.@@ -218,9 +218,17 @@ async def test_a_window_cut_at_a_pause_is_reread_and_the_tail_recovered() -> Nonasync def test_a_healthy_window_is_not_reread() -> None:- # Same pause, but the transcript's token count covers its voiced seconds- # — eight tokens for ~6 s of speech is a normal reading, not a truncation.- stt = _ScriptedSTT(["one two three four five six seven eight"])+ # Same pause, but the transcript's token count covers its voiced seconds.+ #+ # Twelve tokens for ~6.6 voiced seconds is 109 words per minute of actual+ # speech — an ordinary dictation. The count was eight while the floor sat+ # at 1.0 token per voiced second; that floor demanded a recognizer swallow+ # some 60 % of a window before anyone looked, so it caught one truncation+ # in 797 live dictations and the ordinary case — a dropped last sentence —+ # went unexamined. At the raised floor, eight tokens across 6.6 voiced+ # seconds is 73 wpm with every pause already excluded, which is slow enough+ # to be worth one confirming read.+ stt = _ScriptedSTT(["one two three four five six seven eight nine ten again yes"])pipe, events = _session_pipeline(stt, _paused_recording())await _run_session(pipe)@@ -229,6 +237,95 @@ async def test_a_healthy_window_is_not_reread() -> None:assert "truncation_repairs:0" in _completed(events).stt_audit+# --------------------------------------------------------------------------+# halve_at_quietest — the re-read shape for speech with no pause to split at+# --------------------------------------------------------------------------+++def test_halving_covers_the_whole_buffer_with_an_overlap_at_the_seam() -> None:+ # 6 s, a breath too short to count as a pause, 6 s — one speech run, so+ # the pause split has nothing to offer and the halves are all there is.+ pcm = _paused_recording(first_s=6.0, pause_s=0.3, second_s=6.0)+ assert len(speech_runs(pcm, bytes_per_second=BYTES_PER_SECOND)) == 1++ halves = halve_at_quietest(pcm, bytes_per_second=BYTES_PER_SECOND)++ assert len(halves) == 2+ first, second = halves+ assert first[0] == 0+ assert second[1] == len(pcm)+ # Overlapping, so a word on the seam is spoken in full inside one of them.+ assert second[0] < first[1]+ # The cut itself is the middle of that shared stretch, and it landed in the+ # quiet spot rather than at the blind midpoint.+ cut = (first[1] + second[0]) // 2+ assert 5.9 * BYTES_PER_SECOND <= cut <= 6.4 * BYTES_PER_SECOND+++def test_a_buffer_too_short_to_halve_is_left_alone() -> None:+ """Two slivers are two hallucinated subtitle credits, not a repair."""+ assert halve_at_quietest(b"\x11\x22" * 8_000, bytes_per_second=BYTES_PER_SECOND) == []+ assert halve_at_quietest(b"", bytes_per_second=BYTES_PER_SECOND) == []+++def test_continuous_speech_halves_near_the_middle() -> None:+ """No quiet spot anywhere — the split still has to make two real halves."""+ pcm = b"\x11\x22" * (12 * 16_000)++ first, second = halve_at_quietest(pcm, bytes_per_second=BYTES_PER_SECOND)++ assert first[0] == 0 and second[1] == len(pcm)+ for start, end in (first, second):+ assert end - start >= 4.0 * BYTES_PER_SECOND+++# --------------------------------------------------------------------------+# The session, for speech that never paused — the case that used to stand+# --------------------------------------------------------------------------+++async def test_continuous_speech_that_came_back_short_is_reread_in_halves() -> None:+ """One run, a transcript far too small for it — and nobody used to look.++ ``speech_runs`` reports a single run for continuous speech, and the guard+ returned on the spot. So the most ordinary truncation there is — a fluent+ recording whose last sentences simply never arrived — was believed in full.+ """+ stt = _ScriptedSTT(+ [+ "Please use simple words.",+ "Please use simple words.",+ "and then finish the thought properly at the end.",+ ]+ )+ pcm = _paused_recording(first_s=6.0, pause_s=0.3, second_s=6.0)+ pipe, events = _session_pipeline(stt, pcm)++ await _run_session(pipe)++ completed = _completed(events)+ assert "finish the thought" in completed.raw_text+ assert stt.calls == 3 # the long read, then one per half+ assert "truncation_repairs:1" in completed.stt_audit+++async def test_a_halved_reread_that_finds_no_more_speech_keeps_the_original() -> None:+ """The merged reading only ever wins by carrying MORE.++ A false positive must cost one wasted pair of requests and nothing else —+ never a transcript rebuilt out of two worse reads.+ """+ stt = _ScriptedSTT(["Six words is not very many.", "Six words", "is not"])+ pcm = _paused_recording(first_s=6.0, pause_s=0.3, second_s=6.0)+ pipe, events = _session_pipeline(stt, pcm)++ await _run_session(pipe)++ completed = _completed(events)+ assert completed.raw_text == "Six words is not very many."+ assert "truncation_repairs:0" in completed.stt_audit++async def test_a_failed_run_read_keeps_the_original_transcript() -> None:# The second run's read dies for good. Delivering the half-merged split# would trade a dropped tail for a dropped middle — keep the original.diff --git a/tests/unit/speech/test_dictation_mic_handoff.py b/tests/unit/speech/test_dictation_mic_handoff.pyindex 1142767253..d24599975a 100644--- a/tests/unit/speech/test_dictation_mic_handoff.py+++ b/tests/unit/speech/test_dictation_mic_handoff.py@@ -50,12 +50,22 @@ class _StubSTT:class _ControlledMic:"""A microphone whose open/close edges and frames the test drives."""- def __init__(self) -> None:+ def __init__(self, queue_depth: int = 63) -> None:self.frames: asyncio.Queue[AudioChunk | BaseException] = asyncio.Queue()self.entered = asyncio.Event()self.open_count = 0self.close_count = 0self.closed = False+ #: Mirrors ``MicrophoneCapture``: the bound a borrower may re-set for+ #: the kind of consumer it is, and every depth it was ever left at.+ self.queue_depth = queue_depth+ self.depth_history: list[int] = []++ def set_queue_depth(self, max_queue_chunks: int) -> int:+ previous = self.queue_depth+ self.queue_depth = max(1, int(max_queue_chunks))+ self.depth_history.append(self.queue_depth)+ return previousasync def __aenter__(self) -> _ControlledMic:self.open_count += 1@@ -146,6 +156,75 @@ async def test_a_dictation_takes_the_live_wake_microphone_instead_of_opening_oneassert pipeline._wake_capture_released.is_set()+async def test_the_borrowed_stream_is_deepened_for_the_dictation_and_handed_back(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A borrowed wake stream must not keep the wake detector's shallow bound.++ The wake mic is opened shallow on purpose — a detector scoring seconds-old+ audio is its own bug. But a dictation is a BULK consumer: every frame is a+ word, and the queue's drop-oldest policy deletes speech rather than+ staleness. Live telemetry over 797 dictations: 56 % lost frames this way,+ the worst 7.4 s out of a 15.4 s recording, all reported as clean successes.++ The deep bound written for dictation only ever applied to the fallback+ capture, which never runs on an install with a wake word — so it protected+ nobody. Both halves are pinned here: it is raised while the dictation owns+ the stream, and it is PUT BACK, or this fix simply trades itself for the+ missed-wake-word bug.+ """+ pipeline, mic, _factory_calls = _wake_pipeline(monkeypatch)+ shallow = mic.queue_depth++ wake_task = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)+ assert mic.queue_depth == shallow++ async with pipeline._capture_dictation_input():+ assert mic.queue_depth == pipeline_mod._DICTATION_CAPTURE_QUEUE_CHUNKS+ assert mic.queue_depth > shallow++ assert mic.queue_depth == shallow+ assert mic.depth_history == [+ pipeline_mod._DICTATION_CAPTURE_QUEUE_CHUNKS,+ shallow,+ ]+ await asyncio.wait_for(wake_task, timeout=1.0)+++async def test_the_depth_is_restored_even_when_the_dictation_blows_up(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A crash inside the recording must not leave wake deaf-by-staleness."""+ pipeline, mic, _factory_calls = _wake_pipeline(monkeypatch)+ shallow = mic.queue_depth++ wake_task = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)++ with pytest.raises(RuntimeError, match="recording fell over"):+ async with pipeline._capture_dictation_input():+ assert mic.queue_depth > shallow+ raise RuntimeError("recording fell over")++ assert mic.queue_depth == shallow+ await asyncio.wait_for(wake_task, timeout=1.0)+++async def test_a_handoff_without_a_capture_behind_it_still_dictates() -> None:+ """A hand-fed buffer (every unit test, and the Restore route) has no mic.++ The re-bound is a safeguard, never a gate: nothing about it may turn a+ missing attribute into a failed dictation.+ """+ buffer = pipeline_mod._SessionInputBuffer()++ assert buffer.capture is None++@pytest.mark.asyncioasync def test_a_dictation_opens_one_capture_when_no_wake_stream_exists(monkeypatch: pytest.MonkeyPatch,