Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(dictation): re-read a final window whose transcript stops at a pause

Ruben Lütke01ae695b1ab3
diff --git a/jarvis/dictation/merge.py b/jarvis/dictation/merge.py
index d775ec2d0c..75c49aea61 100644
--- a/jarvis/dictation/merge.py
+++ b/jarvis/dictation/merge.py
@@ -76,16 +76,16 @@ def _normalize(text: str) -> str:
#: absent: Hangul is written with spaces, so treating it as space-free would
#: run its words together.
_SPACE_FREE_RANGES: tuple[tuple[int, int], ...] = (
- (0x2E80, 0x2FFF), # CJK radicals, Kangxi
- (0x3040, 0x30FF), # Hiragana, Katakana
- (0x3400, 0x4DBF), # CJK Extension A
- (0x4E00, 0x9FFF), # CJK Unified Ideographs
- (0xF900, 0xFAFF), # CJK Compatibility Ideographs
- (0xFF66, 0xFF9F), # Halfwidth Katakana
- (0x0E00, 0x0E7F), # Thai
- (0x0E80, 0x0EFF), # Lao
- (0x1000, 0x109F), # Myanmar
- (0x1780, 0x17FF), # Khmer
+ (0x2E80, 0x2FFF), # CJK radicals, Kangxi
+ (0x3040, 0x30FF), # Hiragana, Katakana
+ (0x3400, 0x4DBF), # CJK Extension A
+ (0x4E00, 0x9FFF), # CJK Unified Ideographs
+ (0xF900, 0xFAFF), # CJK Compatibility Ideographs
+ (0xFF66, 0xFF9F), # Halfwidth Katakana
+ (0x0E00, 0x0E7F), # Thai
+ (0x0E80, 0x0EFF), # Lao
+ (0x1000, 0x109F), # Myanmar
+ (0x1780, 0x17FF), # Khmer
)
@@ -215,6 +215,24 @@ def merge_transcripts(parts: Sequence[str]) -> str:
return merged.strip()
+def transcript_token_count(text: str) -> int:
+ """How many spoken tokens ``text`` plausibly represents.
+
+ The unit a transcript is compared against seconds of speech in: words for
+ scripts written with spaces, characters for the space-free scripts (an
+ ideograph or kana is roughly one spoken syllable). Counting a Chinese
+ sentence as "one word" would make every Chinese transcript look truncated,
+ and no language is the default one (CLAUDE.md §1).
+ """
+ total = 0
+ for token in _normalize(text).split():
+ if all(_is_space_free(char) for char in token):
+ total += len(token)
+ else:
+ total += 1
+ return total
+
+
def _drop_leading_chars(text: str, count: int) -> str:
"""``text`` without the first ``count`` characters OF ITS NORMALISED view.
@@ -239,4 +257,5 @@ __all__ = [
"MIN_OVERLAP_CHARS",
"MIN_OVERLAP_WORDS",
"merge_transcripts",
+ "transcript_token_count",
]
diff --git a/jarvis/dictation/segment.py b/jarvis/dictation/segment.py
index a573256218..b244c74e39 100644
--- a/jarvis/dictation/segment.py
+++ b/jarvis/dictation/segment.py
@@ -198,6 +198,97 @@ _RELATIVE_SILENCE_FRACTION = 0.06
_RELATIVE_SILENCE_RMS = 250.0
+#: Frame width used when scanning a window for sustained pauses. Short enough
+#: to place a pause edge within a syllable, long enough that one frame's RMS is
+#: a meaningful loudness reading.
+_RUN_FRAME_S = 0.05
+
+#: A quiet gap must last at least this long before it splits two speech runs.
+#: Inter-word pauses are shorter; this is the "breath between sentences" scale
+#: — the pause length that makes a cloud recognizer stop transcribing.
+_RUN_MIN_PAUSE_S = 0.6
+
+#: Audio kept around each run so a soft onset or trailing consonant is not
+#: clipped off by the frame grid.
+_RUN_PAD_S = 0.15
+
+
+def speech_runs(
+ pcm: bytes,
+ *,
+ session_peak: float = 0.0,
+ bytes_per_second: int = 16_000 * BYTES_PER_SAMPLE,
+ min_pause_s: float = _RUN_MIN_PAUSE_S,
+ pad_s: float = _RUN_PAD_S,
+) -> list[tuple[int, int]]:
+ """Byte ranges of continuous speech in ``pcm``, split at sustained pauses.
+
+ The energy-only answer to "does this recording contain a mid-recording
+ pause, and where does the speech on each side of it live?". Quiet gaps
+ shorter than ``min_pause_s`` stay inside their run — they are the pauses
+ between words, and cutting there would hand a recognizer half-words. Each
+ run is padded by ``pad_s`` on both sides and clamped to the buffer.
+
+ Quiet is judged with the same two tests as :func:`is_silent_segment` —
+ absolute room-tone floor plus far-below-``session_peak`` — on ENERGY only,
+ never on transcribed content (the wake path's AP-27 lesson). Returns ``[]``
+ when nothing in ``pcm`` reaches speech loudness, and one whole-buffer run
+ is simply a recording without a sustained pause.
+ """
+ if not pcm:
+ return []
+ frame_bytes = _align(max(BYTES_PER_SAMPLE, int(_RUN_FRAME_S * bytes_per_second)))
+ try:
+ samples = np.frombuffer(
+ pcm[: len(pcm) - (len(pcm) % BYTES_PER_SAMPLE)], dtype=np.int16
+ ).astype(np.float32)
+ except (ValueError, TypeError):
+ return []
+ if samples.size == 0:
+ return []
+ frame_samples = max(1, frame_bytes // BYTES_PER_SAMPLE)
+ frame_count = int(np.ceil(samples.size / frame_samples))
+ padded = np.zeros(frame_count * frame_samples, dtype=np.float32)
+ padded[: samples.size] = samples
+ frames = padded.reshape(frame_count, frame_samples)
+ peaks = np.max(np.abs(frames), axis=1)
+ rms = np.sqrt(np.mean(np.square(frames), axis=1))
+
+ quiet = (peaks < _CERTAIN_SILENCE_PEAK) & (rms < _CERTAIN_SILENCE_RMS)
+ if session_peak >= _SPEECH_REFERENCE_PEAK:
+ quiet |= (peaks < session_peak * _RELATIVE_SILENCE_FRACTION) & (rms < _RELATIVE_SILENCE_RMS)
+
+ speech_frames = np.flatnonzero(~quiet)
+ if speech_frames.size == 0:
+ return []
+
+ min_pause_frames = max(1, int(round(min_pause_s / _RUN_FRAME_S)))
+ runs: list[tuple[int, int]] = [] # in frame indices, inclusive
+ start = int(speech_frames[0])
+ prev = start
+ for frame in speech_frames[1:]:
+ idx = int(frame)
+ if idx - prev - 1 >= min_pause_frames:
+ runs.append((start, prev))
+ start = idx
+ prev = idx
+ runs.append((start, prev))
+
+ pad_bytes = _align(max(0, int(pad_s * bytes_per_second)))
+ ranges: list[tuple[int, int]] = []
+ for first, last in runs:
+ begin = max(0, first * frame_bytes - pad_bytes)
+ end = min(len(pcm), (last + 1) * frame_bytes + pad_bytes)
+ begin, end = _align(begin), _align(end)
+ if ranges and begin <= ranges[-1][1]:
+ # Padding bridged the gap — the pause was barely over the
+ # threshold, and two touching runs are one run.
+ ranges[-1] = (ranges[-1][0], end)
+ else:
+ ranges.append((begin, end))
+ return ranges
+
+
def segment_energy(pcm: bytes) -> tuple[float, float]:
"""``(peak, rms)`` of ``pcm`` as int16 magnitudes. ``(0, 0)`` when empty.
@@ -251,4 +342,5 @@ __all__ = [
"quality_windows",
"quietest_cut",
"segment_energy",
+ "speech_runs",
]
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index b792c7920a..4b92923264 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1110,6 +1110,20 @@ def accept_recognition_reading(*, language: str, probability: float) -> str:
# back, which is a far better answer than a silent minute of waiting.
_DICTATION_FINAL_DEAD_PIECES = 2
+# The floor a final-pass transcript must reach, in spoken tokens per second of
+# VOICED audio, before it is believed to cover its window. Even slow, careful
+# dictation runs well above one word per second while actually speaking (pauses
+# are excluded — only the voiced runs count), so a window that comes back below
+# this is missing speech, not hearing a slow speaker. gpt-4o-class recognizers
+# have a reproducible failure mode behind it: audio with a sustained
+# mid-recording pause is transcribed up to the pause and everything after it is
+# silently dropped (live 2026-07-31 — an 11.6 s recording with a breath after
+# the first sentence came back as that sentence alone, twice in a row). The
+# 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
+
# 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
@@ -9422,6 +9436,10 @@ class SpeechPipeline:
stt_latency_ms = 0.0
stt_calls = 0
final_window_count = 0
+ # Windows whose transcript stopped at a mid-recording pause and were
+ # recovered by re-reading their speech runs. Reported in the audit so
+ # "the provider keeps dropping my second sentence" is measurable.
+ truncation_repairs = 0
def _append_unique(values: list[str], value: object) -> None:
text = str(value or "").strip()
@@ -9941,6 +9959,71 @@ class SpeechPipeline:
await asyncio.sleep(delay)
return "", False
+ async def _repair_truncated_read(
+ piece: bytes, text: str, *, ask_for: str | None
+ ) -> str:
+ """``text`` for ``piece``, with a pause-dropped tail read back in.
+
+ A recognizer handed audio with a sustained mid-recording pause can
+ stop at the pause and silently drop everything after it — the
+ transcript 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
+ original only when it actually carries more speech.
+
+ The runs are told the language the long window just detected
+ rather than asked to detect it themselves — a short clip guessing
+ its language is the translation trap the long windows exist to
+ avoid. A run that cannot be read keeps the original transcript: a
+ dropped middle is worse than the dropped tail it would repair.
+ """
+ nonlocal truncation_repairs
+ from jarvis.dictation.merge import (
+ merge_transcripts,
+ transcript_token_count,
+ )
+ from jarvis.dictation.segment import speech_runs
+
+ runs = speech_runs(
+ piece,
+ session_peak=session_peak,
+ bytes_per_second=bytes_per_second,
+ )
+ if len(runs) < 2:
+ return text
+ voiced_s = sum(end - start for start, end in runs) / bytes_per_second
+ tokens = transcript_token_count(text)
+ if tokens >= voiced_s * _DICTATION_TRUNCATION_TOKENS_PER_VOICED_S:
+ return text
+ log.warning(
+ "final dictation window looks truncated (%d tokens for %.1fs "
+ "of speech in %d runs) — re-reading it split at its pauses.",
+ tokens,
+ voiced_s,
+ len(runs),
+ )
+ run_ask = language if (not ask_for or ask_for == "auto") else ask_for
+ parts: list[str] = []
+ for start, end in runs:
+ run_piece = piece[start:end]
+ if len(run_piece) < min_bytes:
+ continue
+ run_text, run_read = await _read_piece(
+ run_piece, ask_for=run_ask or None
+ )
+ if not run_read:
+ return text
+ if run_text:
+ parts.append(run_text)
+ merged = merge_transcripts(parts)
+ if transcript_token_count(merged) > tokens:
+ truncation_repairs += 1
+ return merged
+ return text
+
async def _final_quality_text(audio: bytes) -> str:
"""Re-read the WHOLE recording in long, overlapping windows.
@@ -10022,6 +10105,9 @@ class SpeechPipeline:
if was_read:
dead_streak = 0
if text:
+ text = await _repair_truncated_read(
+ piece, text, ask_for=ask_for
+ )
parts.append(text)
else:
dead_streak += 1
@@ -10087,6 +10173,9 @@ class SpeechPipeline:
text, piece_read = await _read_piece(piece)
if piece_read:
if text:
+ text = await _repair_truncated_read(
+ piece, text, ask_for=None
+ )
parts.append(text)
dead_streak = 0
else:
@@ -10322,6 +10411,7 @@ class SpeechPipeline:
stt_audit=(
f"final_pass:{final_pass_status}",
f"final_windows:{final_window_count}",
+ f"truncation_repairs:{truncation_repairs}",
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_truncation_repair.py b/tests/unit/dictation/test_truncation_repair.py
new file mode 100644
index 0000000000..e7cf161b86
--- /dev/null
+++ b/tests/unit/dictation/test_truncation_repair.py
@@ -0,0 +1,247 @@
+"""A final-pass window that stops at a pause is re-read, not believed.
+
+The failure this guards (live 2026-07-31): gpt-4o-class recognizers handed a
+recording with a sustained mid-recording pause transcribe up to the pause and
+silently drop everything after it. An 11.6 s dictation whose speaker breathed
+after the first sentence came back as that sentence alone — fluent, punctuated,
+and half of what was said — and it did so twice in a row, so this is a
+behaviour, not a flake.
+
+The detection is energy-only (AP-27's lesson applied to dictation): a window
+whose transcript carries far fewer spoken tokens than its VOICED seconds must
+have contained is missing speech. The repair re-reads the window split at its
+pauses and keeps whichever reading carries more speech — never less.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+from dataclasses import dataclass
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.core.config import DictationConfig
+from jarvis.core.events import DictationCompleted
+from jarvis.dictation.merge import transcript_token_count
+from jarvis.dictation.segment import speech_runs
+from jarvis.speech.pipeline import SpeechPipeline
+
+# 16 kHz mono int16 — the capture contract every dictation records under.
+BYTES_PER_SECOND = 16_000 * 2
+
+
+def _paused_recording(first_s: float = 3.0, pause_s: float = 1.2, second_s: float = 3.0) -> bytes:
+ """Speech, a sentence-length pause, speech — the shape that truncates.
+
+ Sample value 0x2211 = 8721 is far above every silence threshold; the pause
+ is digital zero.
+ """
+ return (
+ b"\x11\x22" * int(16_000 * first_s)
+ + b"\x00\x00" * int(16_000 * pause_s)
+ + b"\x11\x22" * int(16_000 * second_s)
+ )
+
+
+# --------------------------------------------------------------------------
+# speech_runs — the energy scan the guard is built on
+# --------------------------------------------------------------------------
+
+
+def test_a_sustained_pause_splits_the_recording_into_two_runs() -> None:
+ pcm = _paused_recording()
+ runs = speech_runs(pcm, bytes_per_second=BYTES_PER_SECOND)
+
+ assert len(runs) == 2
+ first, second = runs
+ assert first[0] == 0
+ assert second[1] == len(pcm)
+ # The seam lies inside the silent stretch, not inside either run.
+ assert first[1] < second[0]
+ assert 3.0 * BYTES_PER_SECOND <= first[1] <= 3.4 * BYTES_PER_SECOND
+ assert 3.8 * BYTES_PER_SECOND <= second[0] <= 4.2 * BYTES_PER_SECOND
+
+
+def test_an_inter_word_pause_stays_inside_its_run() -> None:
+ pcm = _paused_recording(pause_s=0.3)
+ assert len(speech_runs(pcm, bytes_per_second=BYTES_PER_SECOND)) == 1
+
+
+def test_continuous_speech_is_one_run_and_silence_is_none() -> None:
+ loud = b"\x11\x22" * (3 * 16_000)
+ assert len(speech_runs(loud, bytes_per_second=BYTES_PER_SECOND)) == 1
+ silent = b"\x00\x00" * (3 * 16_000)
+ assert speech_runs(silent, bytes_per_second=BYTES_PER_SECOND) == []
+
+
+# --------------------------------------------------------------------------
+# transcript_token_count — spoken tokens, with no default language
+# --------------------------------------------------------------------------
+
+
+def test_tokens_are_words_for_spaced_scripts() -> None:
+ assert transcript_token_count("Please use simple words.") == 4
+
+
+def test_tokens_are_characters_for_space_free_scripts() -> None:
+ # Each ideograph or kana is roughly one spoken syllable; one "word" per
+ # sentence would make every Chinese transcript look truncated.
+ # i18n-allow: Japanese transcription fixture
+ assert transcript_token_count("今日は東京へ行きます") == 10
+ # i18n-allow: mixed-script fixture
+ assert transcript_token_count("ok 東京") == 3
+
+
+# --------------------------------------------------------------------------
+# The whole session — a truncated window is repaired, a healthy one is not
+# --------------------------------------------------------------------------
+
+
+@dataclass
+class _Transcript:
+ text: str
+ language: str = "en"
+
+
+class _ScriptedSTT:
+ """A provider answering a fixed script, one entry per call."""
+
+ def __init__(self, script: list[Any]) -> None:
+ self._script = list(script)
+ self.calls = 0
+
+ async def transcribe_pcm(self, pcm: bytes, language: str | None = None) -> Any:
+ self.calls += 1
+ step = self._script[min(self.calls, len(self._script)) - 1]
+ if isinstance(step, BaseException):
+ raise step
+ return _Transcript(text=step)
+
+
+class _Chunk:
+ def __init__(self, pcm: bytes) -> None:
+ self.pcm = pcm
+ self.timestamp_ns = 0
+
+
+class _FakeMic:
+ """One burst of prepared audio, then it waits to be cancelled."""
+
+ 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):
+ """A pipeline wired for exactly one ``_dictation_session`` run."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_cfg = DictationConfig(
+ history_enabled=False,
+ # Unsegmented and probe-free: every provider call in the test belongs
+ # to the final pass, so the script maps one entry per window or run.
+ 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))
+
+
+async def test_a_window_cut_at_a_pause_is_reread_and_the_tail_recovered() -> None:
+ # 6 s of voiced audio; the full-window read answers with 4 tokens — the
+ # exact live shape: a fluent first sentence and a silently dropped tail.
+ stt = _ScriptedSTT(
+ [
+ "Please use simple words.",
+ "Please use simple words.",
+ "by expressing yourself in simple, precise language.",
+ ]
+ )
+ pipe, events = _session_pipeline(stt, _paused_recording())
+
+ await _run_session(pipe)
+
+ completed = _completed(events)
+ assert "precise language" in completed.raw_text
+ assert stt.calls == 3
+ assert "truncation_repairs:1" in completed.stt_audit
+
+
+async 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"])
+ pipe, events = _session_pipeline(stt, _paused_recording())
+
+ await _run_session(pipe)
+
+ assert stt.calls == 1
+ assert "truncation_repairs:0" in _completed(events).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.
+ stt = _ScriptedSTT(
+ [
+ "Please use simple words.",
+ RuntimeError("provider went away"),
+ ]
+ )
+ pipe, events = _session_pipeline(stt, _paused_recording())
+
+ await _run_session(pipe)
+
+ completed = _completed(events)
+ assert completed.raw_text == "Please use simple words."
+ assert "truncation_repairs:0" in completed.stt_audit