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 words after a thinking pause stop disappearing
rubenluetke10-beepf50971f47be0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4aacc936fc..202d824e42 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,12 @@ versioning per [SemVer](https://semver.org/).dictation waited several seconds for its text. Windows are now read whileyou are still speaking, and whatever is left at release is read side by sideon providers that allow it; a local engine still takes one call at a time.+- **Dictation no longer loses the words after a thinking pause.** The+ recognizer used to be handed long pauses inside a window and sometimes+ stopped there, silently dropping everything after it. Every pause in an+ upload is now cut to half a second before it is sent, a transcript that ends+ well before your speech does gets only its missing tail read back in, and+ a hardware overflow on the microphone is counted as the real loss it is.- **The wake word no longer fires on a stray single word.** Since the 20 Augcrash fix, the check that decides between "Hey George" and whatever wasactually said had quietly lost its strongest comparison, so a lone word likediff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.pyindex 0b4d40a8c4..d95a3644c9 100644--- a/jarvis/audio/capture.py+++ b/jarvis/audio/capture.py@@ -794,6 +794,7 @@ class MicrophoneCapture:self._stream: sd.InputStream | None = Noneself._loop: asyncio.AbstractEventLoop | None = Noneself._drops = 0+ self._overflows = 0self._closed: bool = Falseself._last_chunk_monotonic: float = 0.0self._watchdog_task: asyncio.Task | None = None@@ -821,9 +822,16 @@ class MicrophoneCapture:that will be overwritten by the next callback) and dispatch themthread-safely into the asyncio queue."""- if status:- # Overflow/underflow — will be logged later via the event bus- pass+ if status and getattr(status, "input_overflow", False):+ # PortAudio's own word that its input buffer overran: audio was+ # lost BEFORE it reached this callback. It is the one hardware-level+ # loss signal there is, and it used to be discarded right here — so+ # a dictation with a hole in it was reported whole, and the only+ # loss anyone could see was a timestamp gap that cannot tell a real+ # hole from callback jitter. A plain increment on the audio thread+ # (atomic under the GIL); readers take the delta over their own+ # lifetime through ``overflow_count``.+ self._overflows += 1pcm_bytes = bytes(indata) # copyresampler = self._capture_resamplerif resampler is not None:@@ -1274,6 +1282,15 @@ class MicrophoneCapture:"""Number of frames lost due to a full queue."""return self._drops+ @property+ def overflow_count(self) -> int:+ """How often PortAudio reported an input overflow on this stream.++ Cumulative for the stream's lifetime — a consumer that wants "during+ my turn" takes the difference between two readings.+ """+ return self._overflows+@propertydef queue_depth(self) -> int:"""Current bound of the bridge queue, in chunks."""diff --git a/jarvis/dictation/segment.py b/jarvis/dictation/segment.pyindex 8dca97533b..00ef8b1b5d 100644--- a/jarvis/dictation/segment.py+++ b/jarvis/dictation/segment.py@@ -369,6 +369,70 @@ def speech_runs(return ranges+#: The longest pause a window may still contain when it is handed to a+#: recognizer. Whisper-class models meet a sustained mid-recording pause and+#: sometimes stop there, silently dropping everything after it (live+#: 2026-08-22: three tokens back for 22 s of speech). Pauses between sentences+#: run 0.5-1 s; a thinking pause runs seconds. Half a second keeps the prosodic+#: boundary the model punctuates on and removes the stretch it gives up in.+_MAX_UPLOADED_PAUSE_S = 0.5+++def compress_pauses(+ pcm: bytes,+ *,+ session_peak: float = 0.0,+ bytes_per_second: int = 16_000 * BYTES_PER_SAMPLE,+ max_pause_s: float = _MAX_UPLOADED_PAUSE_S,+) -> bytes:+ """``pcm`` with every sustained pause shortened to ``max_pause_s``.++ What gets UPLOADED for a final window, never what gets kept: the recording+ itself stays byte-identical (it is what the history's Restore re-reads),+ only the request is shaped so the recognizer never sits in a pause long+ enough to stop. Speech runs are copied untouched — every run already+ carries its onset/offset pad from :func:`speech_runs` — and the quiet+ between two runs is cut to the first ``max_pause_s`` of it; so is the+ quiet before the first run and after the last.++ A buffer with no pause longer than that comes back as the SAME object, so+ the ordinary window costs nothing here. A buffer with no speech at all is+ returned unchanged too: the caller's silence gate already decides about+ those, and shortening silence would only move its verdict.+ """+ if not pcm:+ return pcm+ runs = speech_runs(pcm, session_peak=session_peak, bytes_per_second=bytes_per_second)+ if not runs:+ return pcm+ # ``max_pause_s`` is the SILENCE the upload may hold, and every run already+ # reaches ``_RUN_PAD_S`` into the quiet on both sides — so the stretch kept+ # between two runs is the cap minus both pads, and at either edge of the+ # buffer the cap minus the one pad that borders it.+ cap = _align(max(0, int(max_pause_s * bytes_per_second)))+ pad = _align(max(0, int(_RUN_PAD_S * bytes_per_second)))+ keep_between = max(0, cap - 2 * pad)+ keep_edge = max(0, cap - pad)+ total = len(pcm)+ lead = runs[0][0]+ trail = total - runs[-1][1]+ widest_gap = max(+ (runs[i + 1][0] - runs[i][1] for i in range(len(runs) - 1)), default=0+ )+ if lead <= keep_edge and trail <= keep_edge and widest_gap <= keep_between:+ return pcm+ out = bytearray()+ out += pcm[max(0, lead - keep_edge) : lead]+ for index, (start, end) in enumerate(runs):+ out += pcm[start:end]+ if index + 1 < len(runs):+ gap_end = runs[index + 1][0]+ out += pcm[end : min(gap_end, end + keep_between)]+ last_end = runs[-1][1]+ out += pcm[last_end : min(total, last_end + keep_edge)]+ return bytes(out)++def segment_energy(pcm: bytes) -> tuple[float, float]:"""``(peak, rms)`` of ``pcm`` as int16 magnitudes. ``(0, 0)`` when empty.diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 4808d8e49a..833526a7c5 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -974,6 +974,53 @@ def _dictation_retry_worthwhile(exc: BaseException | None) -> bool:return status in _STT_TRANSIENT_STATUS+def _align_pcm(offset: int) -> int:+ """``offset`` rounded down to a whole int16 sample boundary."""+ return max(0, offset - (offset % 2))+++def _capture_counter(source: object, name: str) -> int:+ """A cumulative capture counter, wherever the stream keeps it.++ A dictation that borrows the wake stream sees a handoff buffer whose+ ``capture`` attribute is the microphone; one that opened its own stream+ sees the microphone directly. Either way a missing counter reads as zero —+ an honest degrade on a source that cannot report it.+ """+ for holder in (source, getattr(source, "capture", None)):+ if holder is None:+ continue+ value = getattr(holder, name, None)+ if value is not None:+ try:+ return int(value or 0)+ except (TypeError, ValueError):+ return 0+ return 0+++def _transcript_end_s(transcript: object) -> float | None:+ """Where the provider's transcript ENDS on its own clock, in seconds.++ Read from the ``segments`` a verbose response carries (Groq / OpenAI+ Whisper: ``{"start", "end", "text", …}`` per segment). ``None`` when the+ provider sent none — a Gemini-class answer, a provider predating the+ field — so the caller falls back to the energy-versus-token heuristic.+ Never raises: a malformed segment is treated as absent.+ """+ best: float | None = None+ for segment in getattr(transcript, "segments", ()) or ():+ if not isinstance(segment, dict):+ continue+ try:+ end = float(segment.get("end", 0.0) or 0.0)+ except (TypeError, ValueError):+ continue+ if end > 0.0 and (best is None or end > best):+ best = end+ return best++def resolve_dictation_language(*, pinned: str, reported: str, text: str) -> str:"""Which language a finished dictation is treated as. Never raises.@@ -1258,6 +1305,19 @@ _DICTATION_CAPTURE_QUEUE_CHUNKS = capture_chunks_for_duration(10.0)# wide unless the provider says otherwise (AP-24)._DICTATION_CONCURRENT_READS = 3+# When a provider's transcript carries segment timestamps, a window whose+# transcript ENDS this many seconds before its speech does has had its tail+# dropped — the recognizer stopped early and said nothing about it. The tail+# alone is then re-read from half a second before the transcript's end, so the+# head the provider got right is kept verbatim and only the missing part is+# asked for again. Judged on the transcript's own clock against the window's+# ENERGY (where the speech really ends), never on what the words say (AP-27).+# One and a half seconds of speech is three or four words — a loss worth a+# request — while the ~0.5-1 s a recognizer's last timestamp ordinarily trails+# the true end of speech stays well inside it.+_DICTATION_TAIL_DROP_MIN_S = 1.5+_DICTATION_TAIL_REREAD_BACK_S = 0.5+class _SessionInputBuffer:"""Replayable bounded handoff for one continuously captured mic stream.@@ -10691,6 +10751,7 @@ class SpeechPipeline:audio_quality = AudioQualityAccumulator()capture_reported_dropouts = 0capture_restart_count = 0+ capture_overflows = 0# Sub-0.4s of audio is almost always a near-silence Whisper# hallucination; wait until enough has accumulated before transcribing.min_bytes = int(0.4 * bytes_per_second)@@ -10816,6 +10877,12 @@ class SpeechPipeline:# ``_DICTATION_FINAL_DEAD_PIECES`` the provider is down, not flaky, and# further windows are counted as lost rather than asked for.dead_windows = 0+ # Tails read back in on the strength of the transcript's OWN+ # timestamps (a subset of ``truncation_repairs``), and how much pause+ # the uploads left out — both in the audit so the two repairs stay+ # measurable apart from each other.+ tail_repairs = 0+ pause_trim_bytes = 0# Wall-clock from key release to the final text being ready — the# number a person actually feels, kept apart from ``stt_latency_ms``# (the SUM of call durations, which concurrency makes larger than the@@ -10888,6 +10955,7 @@ class SpeechPipeline:*,ask_for: str | None = None,probe: bool = False,+ sink: dict[str, Any] | None = None,) -> tuple[str, str, bool, BaseException | None]:"""One transcription. ``(text, language, ok, error)``; never raises.@@ -10934,6 +11002,12 @@ class SpeechPipeline:— "is the PROBE mid-call?" — for ``_stop_ptt_live_transcription``;a prefetched final window in flight must not make the release waitfor a probe that is idle.++ ``sink``, when given, receives what the tuple has no room for and+ only the final pass needs: ``transcript_end_s`` — where the+ provider's transcript ends on its own clock (``None`` without+ segment timestamps), which is how a dropped tail is told apart+ from a slow speaker."""# ``stt_failures`` is appended to, never rebound, so it needs no# ``nonlocal`` — the list object itself is the shared state.@@ -11008,6 +11082,8 @@ class SpeechPipeline:).strip()lang = str(getattr(transcript, "language", "") or "")_record_stt_identity(transcript)+ if sink is not None:+ sink["transcript_end_s"] = _transcript_end_s(transcript)return text, lang, True, Nonedef preview_only_engine() -> Any:@@ -11316,7 +11392,10 @@ class SpeechPipeline:passasync def _read_piece(- piece: bytes, *, ask_for: str | None = None+ piece: bytes,+ *,+ ask_for: str | None = None,+ sink: dict[str, Any] | None = None,) -> tuple[str, bool]:"""One piece of audio, retried. ``(text, was_read)``; never raises.@@ -11331,7 +11410,9 @@ class SpeechPipeline:"""nonlocal language, session_languagefor attempt in range(_DICTATION_FINAL_ATTEMPTS):- text, lang, ok, exc = await _transcribe(piece, ask_for=ask_for)+ text, lang, ok, exc = await _transcribe(+ piece, ask_for=ask_for, sink=sink+ )language = lang or languageif ok:# The first piece to come back also answers "what language@@ -11389,10 +11470,31 @@ class SpeechPipeline:return "", Falseasync def _repair_truncated_read(- piece: bytes, text: str, *, ask_for: str | None+ piece: bytes,+ text: str,+ *,+ ask_for: str | None,+ transcript_end_s: float | None = None,) -> str:"""``text`` for ``piece``, with a pause-dropped tail read back in.+ Two detectors, tried in this order:++ * **The transcript's own clock.** When the provider sent segment+ timestamps, a transcript that ends+ ``_DICTATION_TAIL_DROP_MIN_S`` or more before the window's speech+ does (``speech_runs``, energy) has lost its tail. Only that tail+ is re-read, from half a second before the transcript's end, in+ the language the long window detected; the head the provider got+ right is kept verbatim and the two are merged at the seam. This+ is the precise detector — a dropped last sentence is a fifth of+ the text and sits far above the token floor below — and it is+ the one the polish pass can trust, because the re-read is short+ and pause-free.+ * **Tokens against voiced seconds**, as before, for providers+ without timestamps and for a window that came back short without+ a clock to say where it stopped.+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@@ -11419,7 +11521,7 @@ class SpeechPipeline: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+ nonlocal truncation_repairs, tail_repairsfrom jarvis.dictation.merge import (merge_transcripts,transcript_token_count,@@ -11439,6 +11541,37 @@ class SpeechPipeline:return textvoiced_s = sum(end - start for start, end in runs) / bytes_per_secondtokens = transcript_token_count(text)+ run_ask = language if (not ask_for or ask_for == "auto") else ask_for+ voiced_end_s = runs[-1][1] / bytes_per_second+ if (+ transcript_end_s is not None+ and voiced_end_s - transcript_end_s >= _DICTATION_TAIL_DROP_MIN_S+ ):+ tail_from = _align_pcm(+ int(+ max(0.0, transcript_end_s - _DICTATION_TAIL_REREAD_BACK_S)+ * bytes_per_second+ )+ )+ tail_piece = piece[tail_from:]+ if len(tail_piece) >= min_bytes and not is_silent_segment(+ tail_piece, session_peak=session_peak+ ):+ log.warning(+ "final dictation window's transcript ends at %.1fs but "+ "its speech runs to %.1fs — re-reading the dropped tail.",+ transcript_end_s,+ voiced_end_s,+ )+ tail_text, tail_read = await _read_piece(+ tail_piece, ask_for=run_ask or None+ )+ if tail_read and tail_text:+ merged = merge_transcripts([text, tail_text])+ if transcript_token_count(merged) > tokens:+ truncation_repairs += 1+ tail_repairs += 1+ return mergedif tokens >= voiced_s * _DICTATION_TRUNCATION_TOKENS_PER_VOICED_S:return textsplit_at_pauses = len(runs) > 1@@ -11467,7 +11600,6 @@ class SpeechPipeline:voiced_s,"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] = []for start, end in runs:run_piece = piece[start:end]@@ -11504,8 +11636,9 @@ class SpeechPipeline:lost, which is what degrades the outcome and keeps the recordingfor a later Restore."""- nonlocal session_peak, lost_audio_bytes, dead_windows+ nonlocal session_peak, lost_audio_bytes, dead_windows, pause_trim_bytesfrom jarvis.dictation.segment import (+ compress_pauses,is_silent_segment,segment_energy,)@@ -11538,12 +11671,24 @@ class SpeechPipeline:(end - start) / bytes_per_second,)return- text, was_read = await _read_piece(piece, ask_for=final_ask_for)+ # What is UPLOADED: the window with every sustained pause cut+ # to half a second, so the recognizer never sits in the pause+ # that makes it stop. The recording itself is untouched; the+ # loss accounting below stays in the recording's own bytes.+ sent = compress_pauses(+ piece, session_peak=session_peak, bytes_per_second=bytes_per_second+ )+ pause_trim_bytes += max(0, len(piece) - len(sent))+ sink: dict[str, Any] = {}+ text, was_read = await _read_piece(sent, ask_for=final_ask_for, sink=sink)if was_read:dead_windows = 0if text:text = await _repair_truncated_read(- piece, text, ask_for=final_ask_for+ sent,+ text,+ ask_for=final_ask_for,+ transcript_end_s=sink.get("transcript_end_s"),)else:dead_windows += 1@@ -11678,8 +11823,9 @@ class SpeechPipeline:only postpones a read; here it ends it, and the seconds behind thosebytes are words the user said that nothing will ever transcribe."""- nonlocal session_peak, lost_audio_bytes+ nonlocal session_peak, lost_audio_bytes, pause_trim_bytesfrom jarvis.dictation.segment import (+ compress_pauses,is_silent_segment,quietest_cut,segment_energy,@@ -11715,11 +11861,19 @@ class SpeechPipeline:session_peak = max(session_peak, peak)if is_silent_segment(piece, session_peak=session_peak):continue- text, piece_read = await _read_piece(piece)+ sent = compress_pauses(+ piece, session_peak=session_peak, bytes_per_second=bytes_per_second+ )+ pause_trim_bytes += max(0, len(piece) - len(sent))+ sink: dict[str, Any] = {}+ text, piece_read = await _read_piece(sent, sink=sink)if piece_read:if text:text = await _repair_truncated_read(- piece, text, ask_for=None+ sent,+ text,+ ask_for=None,+ transcript_end_s=sink.get("transcript_end_s"),)parts.append(text)dead_streak = 0@@ -11753,6 +11907,9 @@ class SpeechPipeline:# dictation never runs a second native input stream beside the wake# loop's (AP-24). The wake side gets its stream back on exit.async with self._capture_dictation_input() as source:+ # PortAudio's overflow counter is cumulative for the stream;+ # what this dictation lost is the difference from here.+ overflow_base = _capture_counter(source, "overflow_count")async def _drain() -> None:async for chunk in source.stream():@@ -11828,9 +11985,14 @@ class SpeechPipeline:"dictation input stream ended; finalizing what ""was captured.")+ capture_overflows = max(+ 0, _capture_counter(source, "overflow_count") - overflow_base+ )+ # Queue drops and hardware overflows are both frames that+ # never became audio; either is a real hole in the recording.capture_reported_dropouts = max(capture_reported_dropouts,- int(getattr(source, "dropped_frames", 0) or 0),+ int(getattr(source, "dropped_frames", 0) or 0) + capture_overflows,)capture_restart_count = max(capture_restart_count,@@ -11965,6 +12127,9 @@ class SpeechPipeline:f"final_windows_prefetched:{final_prefetched}",f"release_wait_ms:{release_wait_ms}",f"truncation_repairs:{truncation_repairs}",+ f"tail_repairs:{tail_repairs}",+ f"pause_trim_ms:{round(pause_trim_bytes * 1000 / bytes_per_second)}",+ f"capture_overflows:{capture_overflows}",f"code_switching:{'on' if code_switching else 'off'}",f"capture_restarts:{capture_restart_count}",*audio_preprocessing.audit(),diff --git a/tests/unit/dictation/test_incremental_final_pass.py b/tests/unit/dictation/test_incremental_final_pass.pyindex b646d7fb92..ed7bac9edb 100644--- a/tests/unit/dictation/test_incremental_final_pass.py+++ b/tests/unit/dictation/test_incremental_final_pass.py@@ -267,9 +267,10 @@ async def test_a_concurrent_provider_reads_the_remaining_windows_side_by_side(events = await _release_with_windows_left(stt)assert stt.calls >= 3+ # Side by side — overlap is the proof; the wall-clock bound stays loose+ # because a loaded test host cannot promise timing, only ordering.assert stt.max_in_flight >= 2- # Side by side: the whole pass took about one call, not one per window.- assert _audit(events, "release_wait_ms") < 400+ assert _audit(events, "release_wait_ms") < 1500text = _completed(events).raw_textassert text.index("alpha") < text.index("bravo") < text.index("charlie")diff --git a/tests/unit/dictation/test_pause_trim_and_tail_repair.py b/tests/unit/dictation/test_pause_trim_and_tail_repair.pynew file mode 100644index 0000000000..622bbdd7c5--- /dev/null+++ b/tests/unit/dictation/test_pause_trim_and_tail_repair.py@@ -0,0 +1,274 @@+"""No passage goes missing: pauses are trimmed before upload, dropped tails are+read back in on the transcript's own clock, and a hardware overflow is counted.++What this guards (live 2026-08-22): a Whisper-class recognizer handed a window+with a sustained pause inside it stops at the pause and silently drops the rest+— "3 tokens for 22.4 s of speech" in the log, three times in the last forty+dictations. Two defences, both energy- and timestamp-based, never content-based+(AP-27):++* every sustained pause in an uploaded window is shortened to half a second, so+ the recognizer never sits in the stretch it gives up in;+* when the transcript's last segment ends well before the window's speech does,+ only that tail is re-read and merged onto the head the provider got right.+"""++from __future__ import annotations++import asyncio+import contextlib+from dataclasses import dataclass, field+from types import SimpleNamespace+from typing import Any++from jarvis.audio.capture import MicrophoneCapture+from jarvis.core.config import DictationConfig+from jarvis.core.events import DictationCompleted+from jarvis.dictation.segment import compress_pauses, speech_runs+from jarvis.speech.pipeline import SpeechPipeline++BYTES_PER_SECOND = 16_000 * 2+++def _voiced(seconds: float) -> bytes:+ return b"\x11\x22" * int(16_000 * seconds)+++def _silence(seconds: float) -> bytes:+ return b"\x00\x00" * int(16_000 * seconds)+++# --------------------------------------------------------------------------+# compress_pauses+# --------------------------------------------------------------------------+++def test_a_long_pause_is_cut_to_half_a_second_and_the_speech_kept_whole() -> None:+ pcm = _voiced(3.0) + _silence(2.5) + _voiced(3.0)++ sent = compress_pauses(pcm, bytes_per_second=BYTES_PER_SECOND)++ # About 3 + 0.5 + 3 s remain (plus the runs' own onset/offset pads).+ assert 6.3 * BYTES_PER_SECOND <= len(sent) <= 7.0 * BYTES_PER_SECOND+ # Every voiced byte survived: the speech runs of the upload hold exactly+ # as much speech as the original's.+ voiced_before = sum(b - a for a, b in speech_runs(pcm, bytes_per_second=BYTES_PER_SECOND))+ voiced_after = sum(b - a for a, b in speech_runs(sent, bytes_per_second=BYTES_PER_SECOND))+ assert abs(voiced_before - voiced_after) <= 0.4 * BYTES_PER_SECOND+ # And no pause longer than the cap is left inside the upload.+ assert len(speech_runs(sent, bytes_per_second=BYTES_PER_SECOND)) == 1+++def test_leading_and_trailing_silence_are_trimmed_too() -> None:+ pcm = _silence(2.0) + _voiced(2.0) + _silence(3.0)++ sent = compress_pauses(pcm, bytes_per_second=BYTES_PER_SECOND)++ assert len(sent) < 3.5 * BYTES_PER_SECOND+++def test_a_window_without_a_long_pause_is_returned_as_is() -> None:+ pcm = _voiced(2.0) + _silence(0.3) + _voiced(2.0)+ assert compress_pauses(pcm, bytes_per_second=BYTES_PER_SECOND) is pcm+++def test_silence_and_empty_input_are_left_alone() -> None:+ silent = _silence(3.0)+ assert compress_pauses(silent, bytes_per_second=BYTES_PER_SECOND) is silent+ assert compress_pauses(b"", bytes_per_second=BYTES_PER_SECOND) == b""+++# --------------------------------------------------------------------------+# The session: upload shape and the timestamp tail repair+# --------------------------------------------------------------------------+++@dataclass+class _Transcript:+ text: str+ language: str = "en"+ segments: tuple[dict[str, Any], ...] = field(default_factory=tuple)+++class _ScriptedSTT:+ """Answers a script, one entry per call, and keeps every upload it saw."""++ def __init__(self, script: list[_Transcript]) -> None:+ self._script = list(script)+ self.calls = 0+ self.uploads: list[bytes] = []++ async def transcribe_pcm(self, pcm: bytes, language: str | None = None) -> Any:+ self.calls += 1+ self.uploads.append(pcm)+ return self._script[min(self.calls, len(self._script)) - 1]+++class _Chunk:+ def __init__(self, pcm: bytes) -> None:+ self.pcm = pcm+ self.timestamp_ns = 0+++class _FakeMic:+ def __init__(self, pcm: bytes) -> None:+ self._pcm = pcm++ async def stream(self): # noqa: ANN201 — an async generator of chunks+ yield _Chunk(self._pcm)+ await asyncio.sleep(3600)+++class _NullCapture:+ def __init__(self, source: Any) -> None:+ self._source = source++ async def __aenter__(self) -> Any:+ return self._source++ async def __aexit__(self, *exc: object) -> bool:+ return False+++def _session_pipeline(stt: Any, pcm: bytes):+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._dictation_cfg = DictationConfig(+ history_enabled=False,+ segment_seconds=0.0,+ partial_interval_s=0.0,+ polish=False,+ )+ pipe._dictation_target = "chat"+ pipe._dictation_completion_published = False+ pipe._dictation_max_s = 30.0+ pipe._dictation_stt_instance = stt+ pipe._stt_final_timeout_s = 8.0+ pipe._hangup_event = asyncio.Event()+ pipe._dictation_stop_event = asyncio.Event()+ events: list[object] = []++ async def _publish(event: object) -> None:+ events.append(event)++ pipe._publish_event = _publish # type: ignore[assignment]+ pipe._publish_event_soon = events.append # type: ignore[assignment]+ pipe._capture_dictation_input = lambda: _NullCapture(_FakeMic(pcm)) # type: ignore[assignment]+ pipe._insert_dictation = lambda text: SimpleNamespace( # type: ignore[assignment]+ status="inserted", detail="", method="clipboard+ctrl_v"+ )++ async def _stop_live(task, **_kwargs): # noqa: ANN001, ANN202+ task.cancel()+ with contextlib.suppress(asyncio.CancelledError, Exception):+ await task++ pipe._stop_ptt_live_transcription = _stop_live # type: ignore[assignment]+ return pipe, events+++async def _run_session(pipe: Any) -> None:+ task = asyncio.create_task(pipe._dictation_session())+ await asyncio.sleep(0)+ pipe._dictation_stop_event.set()+ await asyncio.wait_for(task, timeout=30)+++def _completed(events: list[object]) -> DictationCompleted:+ return next(e for e in events if isinstance(e, DictationCompleted))+++def _audit(events: list[object], key: str) -> int:+ token = next(t for t in _completed(events).stt_audit if t.startswith(key + ":"))+ return int(token.split(":", 1)[1])+++_TWELVE = "one two three four five six seven eight nine ten eleven twelve"+++async def test_the_upload_never_contains_the_long_pause() -> None:+ # 3 s speech, a 2.5 s thinking pause, 3 s speech — the exact shape that+ # makes a recognizer stop. Twelve tokens keep the token-rate guard quiet,+ # and a transcript end at the end of the upload keeps the clock guard+ # quiet, so the ONE call is the upload under test.+ stt = _ScriptedSTT([_Transcript(_TWELVE, segments=({"start": 0.0, "end": 6.6},))])+ pipe, events = _session_pipeline(stt, _voiced(3.0) + _silence(2.5) + _voiced(3.0))++ await _run_session(pipe)++ assert stt.calls == 1+ uploaded = stt.uploads[0]+ assert len(uploaded) < 7.2 * BYTES_PER_SECOND+ assert len(speech_runs(uploaded, bytes_per_second=BYTES_PER_SECOND)) == 1+ # The trim is reported: roughly two seconds of pause left out.+ assert 1500 <= _audit(events, "pause_trim_ms") <= 2500+ assert _audit(events, "tail_repairs") == 0+++async def test_a_transcript_that_ends_early_gets_its_tail_read_back_in() -> None:+ # Seven seconds of continuous speech; the provider answers with a fluent+ # head whose last segment ends at 3.0 s — it stopped and dropped four+ # seconds of speech. Ten tokens for seven voiced seconds sit ABOVE the+ # token floor (1.3/s -> 9.1), so only the transcript's clock can see this.+ head = _Transcript(+ "please use simple words and be exact yes indeed now",+ segments=({"start": 0.0, "end": 3.0},),+ )+ tail = _Transcript(+ "and this is the part that was dropped",+ segments=({"start": 0.0, "end": 4.4},),+ )+ stt = _ScriptedSTT([head, tail])+ pipe, events = _session_pipeline(stt, _voiced(7.0))++ await _run_session(pipe)++ assert stt.calls == 2+ # The tail re-read started half a second before the transcript's end, not+ # at the start of the window.+ assert 4.0 * BYTES_PER_SECOND <= len(stt.uploads[1]) <= 4.8 * BYTES_PER_SECOND+ text = _completed(events).raw_text+ assert text.startswith("please use simple words")+ assert "part that was dropped" in text+ assert _audit(events, "tail_repairs") == 1+ assert _audit(events, "truncation_repairs") == 1+++async def test_a_transcript_that_runs_to_the_end_is_not_reread() -> None:+ stt = _ScriptedSTT(+ [_Transcript(_TWELVE, segments=({"start": 0.0, "end": 6.6},))]+ )+ pipe, events = _session_pipeline(stt, _voiced(7.0))++ await _run_session(pipe)++ assert stt.calls == 1+ assert _audit(events, "tail_repairs") == 0+++async def test_without_timestamps_the_token_floor_still_decides() -> None:+ # No segments at all (a provider without them): the old energy-versus-+ # token guard is all there is, and it does not fire on a healthy count.+ stt = _ScriptedSTT([_Transcript(_TWELVE)])+ pipe, events = _session_pipeline(stt, _voiced(7.0))++ await _run_session(pipe)++ assert stt.calls == 1+ assert _audit(events, "truncation_repairs") == 0+++# --------------------------------------------------------------------------+# The microphone's own overflow flag is no longer thrown away+# --------------------------------------------------------------------------+++def test_portaudio_input_overflow_is_counted() -> None:+ mic = MicrophoneCapture()+ mic._loop = None # no event loop: the callback must still count+ indata = b"\x00\x00" * 16++ mic._callback(indata, 16, None, SimpleNamespace(input_overflow=True))+ mic._callback(indata, 16, None, SimpleNamespace(input_overflow=False))+ mic._callback(indata, 16, None, None)++ assert mic.overflow_count == 1