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
feat(dictation): read the final windows while you are still speaking, and side by side at release
rubenluetke10-beepc43d83cfd88c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a2ad01c88d..d1ac765595 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,15 @@ versioning per [SemVer](https://semver.org/).## [Unreleased]+### Fixed++- **Dictation delivers its text about as fast after a long recording as after+ a short one.** The final read used to start only after the key was released+ and work through the recording one window at a time, so a one-minute+ dictation waited several seconds for its text. Windows are now read while+ you are still speaking, and whatever is left at release is read side by side+ on providers that allow it; a local engine still takes one call at a time.+## [1.5.3] — 2026-08-22### Addeddiff --git a/jarvis/dictation/segment.py b/jarvis/dictation/segment.pyindex c756b5af39..8dca97533b 100644--- a/jarvis/dictation/segment.py+++ b/jarvis/dictation/segment.py@@ -187,7 +187,49 @@ def quality_windows(total = len(pcm)if total <= 0 or window_bytes <= 0:return []+ ranges: list[tuple[int, int]] = []+ start = 0+ while start < total:+ window, start = next_quality_window(+ pcm[start:],+ start=start,+ total=total,+ window_bytes=window_bytes,+ overlap_bytes=overlap_bytes,+ bytes_per_second=bytes_per_second,+ )+ ranges.append(window)+ return ranges+++def next_quality_window(+ scan: bytes,+ *,+ start: int,+ total: int,+ window_bytes: int,+ overlap_bytes: int = 0,+ bytes_per_second: int = 16_000 * BYTES_PER_SAMPLE,+) -> tuple[tuple[int, int], int]:+ """One step of :func:`quality_windows`: the window at ``start`` and where+ the next one begins.++ ``scan`` is the audio FROM ``start`` onward — at least one window of it+ when the recording holds that much; ``total`` is the recording's length in+ bytes. Returns ``((start, end), next_start)``; ``next_start == total`` when+ this was the last window.++ Public because the dictation lane closes final windows WHILE the user is+ still speaking, one per tick, so that on key release only the open tail is+ left to read. Sharing this step is what keeps that incremental shape+ byte-identical to the one-shot ``quality_windows`` over the finished+ recording: the cut depends only on the audio inside the window, so a+ window closed mid-recording is the very window the finished recording+ would have produced.+ """window = _align(window_bytes)+ if window <= 0:+ return (start, total), total# More than half a window of overlap can never improve a seam enough to# justify re-reading most of the same audio. More importantly, clamping to# ``window - one sample`` technically made progress but could turn a bad@@ -195,31 +237,24 @@ def quality_windows(# still far above the recommended 1--2 seconds and gives a hard O(n) bound.overlap = max(0, min(_align(overlap_bytes), window // 2))min_window = int(_MIN_WINDOW_S * bytes_per_second)-- ranges: list[tuple[int, int]] = []- start = 0- while start < total:- remaining = total - start- if remaining <= window:- ranges.append((start, total))- break- cut = quietest_cut(pcm[start:], window, bytes_per_second)- if cut < min_window:- # The scan found its quiet spot too early to be a useful window —- # take the nominal length instead. The overlap is what protects the- # word this cut may land inside.- cut = window- end = _align(min(total, start + cut))- if end <= start: # pragma: no cover — _align keeps this unreachable- end = min(total, start + window)- ranges.append((start, end))- # Step back by the overlap, but never to (or behind) this window's own- # start: that would transcribe the same audio forever.- # A pause search may cut as early as 60% of the nominal window. Keep a- # half-window minimum stride even then: otherwise a legal 50% overlap- # plus the earliest cut advances by only 10% and multiplies requests.- start = max(end - overlap, start + window // 2)- return ranges+ remaining = total - start+ if remaining <= window:+ return (start, total), total+ cut = quietest_cut(scan, window, bytes_per_second)+ if cut < min_window:+ # The scan found its quiet spot too early to be a useful window —+ # take the nominal length instead. The overlap is what protects the+ # word this cut may land inside.+ cut = window+ end = _align(min(total, start + cut))+ if end <= start: # pragma: no cover — _align keeps this unreachable+ end = min(total, start + window)+ # Step back by the overlap, but never to (or behind) this window's own+ # start: that would transcribe the same audio forever.+ # A pause search may cut as early as 60% of the nominal window. Keep a+ # half-window minimum stride even then: otherwise a legal 50% overlap+ # plus the earliest cut advances by only 10% and multiplies requests.+ return (start, end), max(end - overlap, start + window // 2)#: Below these an int16 microphone signal cannot be carrying speech on ANYdiff --git a/jarvis/plugins/stt/gemini_api.py b/jarvis/plugins/stt/gemini_api.pyindex 2201baaf74..0745905608 100644--- a/jarvis/plugins/stt/gemini_api.py+++ b/jarvis/plugins/stt/gemini_api.py@@ -123,6 +123,12 @@ class GeminiSTT:name = "gemini-api"supports_streaming = False+ #: Concurrent ``transcribe_pcm`` calls are safe here: each is one HTTP+ #: request on a shared async client, with no native engine behind it. The+ #: dictation lane reads this to decide whether its final windows may be+ #: transcribed side by side (AP-24 forbids that on a native engine, which+ #: is why the attribute is opt-in and the local providers never set it).+ supports_concurrent_requests = True#: Credential family this recognizer bills against. Distinct from ``name``#: (the entry-point id) because several plugin ids can share one account —#: and, for the Vertex sibling, because the account is a different one.diff --git a/jarvis/plugins/stt/groq_api.py b/jarvis/plugins/stt/groq_api.pyindex 589c620f50..edc1921d5f 100644--- a/jarvis/plugins/stt/groq_api.py+++ b/jarvis/plugins/stt/groq_api.py@@ -93,6 +93,12 @@ class GroqWhisperAPI:name = "groq-api"supports_streaming = False+ #: Concurrent ``transcribe_pcm`` calls are safe here: each is one HTTP+ #: request on a shared async client, with no native engine behind it. The+ #: dictation lane reads this to decide whether its final windows may be+ #: transcribed side by side (AP-24 forbids that on a native engine, which+ #: is why the attribute is opt-in and the local providers never set it).+ supports_concurrent_requests = Truedef __init__(self,diff --git a/jarvis/plugins/stt/openai_api.py b/jarvis/plugins/stt/openai_api.pyindex 37e7cdee3e..907a0b33e0 100644--- a/jarvis/plugins/stt/openai_api.py+++ b/jarvis/plugins/stt/openai_api.py@@ -132,6 +132,12 @@ class OpenAIWhisperAPI:name = "openai-api"supports_streaming = False+ #: Concurrent ``transcribe_pcm`` calls are safe here: each is one HTTP+ #: request on a shared async client, with no native engine behind it. The+ #: dictation lane reads this to decide whether its final windows may be+ #: transcribed side by side (AP-24 forbids that on a native engine, which+ #: is why the attribute is opt-in and the local providers never set it).+ supports_concurrent_requests = Truedef __init__(self,diff --git a/jarvis/plugins/stt/openrouter_stt.py b/jarvis/plugins/stt/openrouter_stt.pyindex be8d130fbf..83e1d5ff50 100644--- a/jarvis/plugins/stt/openrouter_stt.py+++ b/jarvis/plugins/stt/openrouter_stt.py@@ -140,6 +140,12 @@ class OpenRouterSTT:name = "openrouter-stt"supports_streaming = False+ #: Concurrent ``transcribe_pcm`` calls are safe here: each is one HTTP+ #: request on a shared async client, with no native engine behind it. The+ #: dictation lane reads this to decide whether its final windows may be+ #: transcribed side by side (AP-24 forbids that on a native engine, which+ #: is why the attribute is opt-in and the local providers never set it).+ supports_concurrent_requests = Truedef __init__(self,diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 587dd5b5c4..4808d8e49a 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1246,6 +1246,18 @@ _DICTATION_ERROR_BACKOFF_MAX_S = 12.0# silently shrinks the safety margin._DICTATION_CAPTURE_QUEUE_CHUNKS = capture_chunks_for_duration(10.0)+# How many final-pass windows may be in flight at once on a provider that+# advertises ``supports_concurrent_requests`` (the cloud HTTP ones). The final+# pass used to read its windows strictly one after another, so the wait after+# key release grew with the recording: measured on the live history, 2.2 s+# median for a 25-50 s dictation and 4.6 s past 50 s, against 0.66 s for a+# short one. Three keeps well inside every provider's per-minute limit while+# the windows already finalized during the recording (see+# ``_prefetch_final_windows``) mean there is rarely more than one left to read+# at release anyway. A native engine never sees concurrency: the gate is one+# wide unless the provider says otherwise (AP-24).+_DICTATION_CONCURRENT_READS = 3+class _SessionInputBuffer:"""Replayable bounded handoff for one continuously captured mic stream.@@ -10783,6 +10795,51 @@ class SpeechPipeline:# recovered by re-reading their speech runs. Reported in the audit so# "the provider keeps dropping my second sentence" is measurable.truncation_repairs = 0+ # The final pass, INCREMENTAL. It used to run only after key release —+ # the whole recording, window after window — so the wait for the text+ # grew with every second spoken. Now each final window is closed and+ # read as soon as the recording has grown past it, while the user is+ # still talking; on release only the open tail is left. The shape of+ # the windows is unchanged (``next_quality_window`` is the very step+ # ``quality_windows`` takes), only WHEN they are read moved.+ #+ # ``final_reads`` maps a window's index to ``(text, was_read)`` once its+ # read finished; ``final_tasks`` holds the reads in flight;+ # ``final_next_start`` is the byte offset the next window begins at.+ final_reads: dict[int, tuple[str, bool]] = {}+ final_tasks: dict[int, asyncio.Task[None]] = {}+ final_next_start = 0+ final_next_index = 0+ # Windows read BEFORE release — the ones the user no longer waits for.+ final_prefetched = 0+ # Consecutive final windows that exhausted every attempt. Past+ # ``_DICTATION_FINAL_DEAD_PIECES`` the provider is down, not flaky, and+ # further windows are counted as lost rather than asked for.+ dead_windows = 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+ # wait it describes).+ release_wait_ms = 0+ # One gate for every provider call this session makes. Width follows+ # the provider's own word: a cloud HTTP client takes several requests+ # at once, a native engine takes exactly one (AP-24) — and the gate is+ # what stops a prefetched window and the live probe from colliding on+ # it.+ stt_gate = asyncio.Semaphore(+ _DICTATION_CONCURRENT_READS+ if getattr(stt, "supports_concurrent_requests", False)+ else 1+ )+ # ``auto`` is passed explicitly rather than omitted: an absent language+ # argument means "no opinion" to a provider, which lands on whatever the+ # recognition language is pinned to — the exact inheritance that used+ # to write German speech in English.+ final_ask_for = (+ "auto"+ if code_switching or dictation_language == "auto"+ else dictation_language+ )def _append_unique(values: list[str], value: object) -> None:text = str(value or "").strip()@@ -10830,6 +10887,7 @@ class SpeechPipeline:pcm: bytes,*,ask_for: str | None = None,+ probe: bool = False,) -> tuple[str, str, bool, BaseException | None]:"""One transcription. ``(text, language, ok, error)``; never raises.@@ -10870,6 +10928,12 @@ class SpeechPipeline:guarantee that the provider stopped working. That is still the wholedifference between a dictation that ends with an honest error andone that never ends at all.++ ``probe`` marks a call made by the live probe task. Only those+ raise ``inference_active``, because that flag answers one question+ — "is the PROBE mid-call?" — for ``_stop_ptt_live_transcription``;+ a prefetched final window in flight must not make the release wait+ for a probe that is idle."""# ``stt_failures`` is appended to, never rebound, so it needs no# ``nonlocal`` — the list object itself is the shared state.@@ -10887,41 +10951,44 @@ class SpeechPipeline:# Startup/live-switch warm-up and this call share one native task.# Joining it avoids both an 11 s cold final decode and a concurrent# model call that would return TranscribeBusy (AP-24).- stt = await self._join_dictation_warmup(stt)- inference_active.set()- call_started = time.perf_counter()- try:+ async with stt_gate:+ stt = await self._join_dictation_warmup(stt)+ if probe:+ inference_active.set()+ call_started = time.perf_counter()try:- transcript = await asyncio.wait_for(- stt.transcribe_pcm(pcm, language=ask_for),- timeout=ceiling,- )- 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 asyncio.wait_for(- stt.transcribe_pcm(pcm), timeout=ceiling+ try:+ transcript = await asyncio.wait_for(+ stt.transcribe_pcm(pcm, language=ask_for),+ timeout=ceiling,+ )+ 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 asyncio.wait_for(+ stt.transcribe_pcm(pcm), timeout=ceiling+ )+ except TimeoutError as exc:+ stt_error_detail = (+ f"the provider did not answer within {ceiling:.0f}s "+ f"for {len(pcm) / bytes_per_second:.1f}s of audio")- except TimeoutError as exc:- stt_error_detail = (- f"the provider did not answer within {ceiling:.0f}s "- f"for {len(pcm) / bytes_per_second:.1f}s of audio"- )- stt_error = classify_stt_failure(exc)- stt_failures.append(stt_error)- log.warning("dictation transcribe timed out: %s", stt_error_detail)- return "", "", False, exc- except Exception as exc: # noqa: BLE001 — one failed call is not fatal- stt_error_detail = f"{type(exc).__name__}: {exc}".strip()- stt_error = classify_stt_failure(exc)- stt_failures.append(stt_error)- log.debug("dictation transcribe failed: %s", stt_error_detail)- return "", "", False, exc- finally:- stt_calls += 1- stt_latency_ms += (time.perf_counter() - call_started) * 1000.0- inference_active.clear()+ stt_error = classify_stt_failure(exc)+ stt_failures.append(stt_error)+ log.warning("dictation transcribe timed out: %s", stt_error_detail)+ return "", "", False, exc+ except Exception as exc: # noqa: BLE001 — one failed call is not fatal+ stt_error_detail = f"{type(exc).__name__}: {exc}".strip()+ stt_error = classify_stt_failure(exc)+ stt_failures.append(stt_error)+ log.debug("dictation transcribe failed: %s", stt_error_detail)+ return "", "", False, exc+ finally:+ stt_calls += 1+ stt_latency_ms += (time.perf_counter() - call_started) * 1000.0+ if probe:+ inference_active.clear()stt_error = Nonestt_error_detail = ""# ``raw_text`` when the provider offers it, ``text`` otherwise. A@@ -11025,7 +11092,7 @@ class SpeechPipeline:)text, lang, ok = (local_text or ""), "", Trueelse:- text, lang, ok, _exc = await _transcribe(piece)+ text, lang, ok, _exc = await _transcribe(piece, probe=True)if stop_event.is_set():return Trueif not ok:@@ -11073,6 +11140,13 @@ class SpeechPipeline:if stop_event.is_set():return+ # Final windows first: a window the recording has grown+ # past is read NOW, in the background, so the user never+ # waits for it after release. Launching costs no call on+ # this task — the read runs beside the probe behind the+ # provider gate.+ _prefetch_final_windows()+# 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.@@ -11204,7 +11278,9 @@ class SpeechPipeline:# headless install), and then strictly within its budget so# it can never again outbid the transcript for requests.if want_preview and preview_budget().try_spend():- tail_text, lang, ok, _exc = await _transcribe(tail)+ tail_text, lang, ok, _exc = await _transcribe(+ tail, probe=True+ )if stop_event.is_set():returnif not ok:@@ -11416,8 +11492,120 @@ class SpeechPipeline:return mergedreturn text+ async def _read_final_window(idx: int, start: int, end: int) -> None:+ """Read ONE final window of the recording and file its result.++ Runs as its own task — during the recording for a prefetched+ window, after release for the tail — so everything it needs is+ taken from the shared buffer and everything it learns goes into+ ``final_reads``; ``_final_quality_text`` assembles the windows in+ order once all of them are in. Never raises: a window that could+ not be read is filed as ``("", False)`` and its audio counted as+ lost, which is what degrades the outcome and keeps the recording+ for a later Restore.+ """+ nonlocal session_peak, lost_audio_bytes, dead_windows+ from jarvis.dictation.segment import (+ is_silent_segment,+ segment_energy,+ )++ try:+ piece = bytes(buffer[start:end])+ if len(piece) < min_bytes:+ final_reads[idx] = ("", True)+ return+ peak, _rms = segment_energy(piece)+ session_peak = max(session_peak, peak)+ if is_silent_segment(piece, session_peak=session_peak):+ final_reads[idx] = ("", True)+ return+ if dead_windows >= _DICTATION_FINAL_DEAD_PIECES:+ # The provider is not flaky, it is down. Counting this+ # window as lost is what degrades the outcome, and the+ # degraded outcome is what keeps the audio for a later+ # Restore — far better than making the user wait through+ # another full retry ladder to be told the same thing.+ lost_audio_bytes += max(0, (end - start) - final_overlap_bytes)+ final_reads[idx] = ("", False)+ log.warning(+ "final dictation window %d not read — %d consecutive "+ "windows already failed (%s); %.1fs of audio kept for "+ "a later retry rather than making you wait.",+ idx,+ dead_windows,+ stt_error_detail or stt_error or "unknown error",+ (end - start) / bytes_per_second,+ )+ return+ text, was_read = await _read_piece(piece, ask_for=final_ask_for)+ if was_read:+ dead_windows = 0+ if text:+ text = await _repair_truncated_read(+ piece, text, ask_for=final_ask_for+ )+ else:+ dead_windows += 1+ # Only the audio this window did not SHARE with its+ # neighbour is at risk; the overlap is read by the window+ # after it. Counting the whole window would report a loss+ # the user never experienced.+ lost_audio_bytes += max(0, (end - start) - final_overlap_bytes)+ final_reads[idx] = (text, was_read)+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — one window must not end the pass+ log.warning(+ "final dictation window %d crashed (non-fatal)",+ idx,+ exc_info=True,+ )+ lost_audio_bytes += max(0, (end - start) - final_overlap_bytes)+ final_reads[idx] = ("", False)++ def _launch_final_window(start: int, end: int, *, prefetched: bool) -> None:+ nonlocal final_next_index, final_prefetched+ idx = final_next_index+ final_next_index += 1+ if prefetched:+ final_prefetched += 1+ final_tasks[idx] = asyncio.create_task(+ _read_final_window(idx, start, end),+ name=f"dictation-final-{idx}",+ )++ def _prefetch_final_windows() -> None:+ """Close and start reading every final window the recording holds.++ Called from the probe on every tick. A window is closed the moment+ the recording has grown a full window past the last one — at the+ quietest point near the nominal length, exactly where the one-shot+ pass would have cut it — and its read starts at once. The scan is+ handed one window of audio, so the copy stays bounded however long+ the recording gets; only ``total`` tells it how much there is.+ """+ nonlocal final_next_start+ if not final_quality_pass or final_window_bytes <= 0:+ return+ from jarvis.dictation.segment import next_quality_window++ total = len(buffer)+ while total - final_next_start > final_window_bytes:+ start = final_next_start+ scan = bytes(buffer[start : start + final_window_bytes])+ (w_start, w_end), final_next_start = next_quality_window(+ scan,+ start=start,+ total=total,+ window_bytes=final_window_bytes,+ overlap_bytes=final_overlap_bytes,+ bytes_per_second=bytes_per_second,+ )+ _launch_final_window(w_start, w_end, prefetched=True)+async def _final_quality_text(audio: bytes) -> str:- """Re-read the WHOLE recording in long, overlapping windows.+ """The WHOLE recording read in long, overlapping windows.This is the transcript the user is handed, and it is a differentrequest from the one the live line makes. Two properties, both of@@ -11440,74 +11628,39 @@ class SpeechPipeline:from the text (``jarvis.dictation.merge``), which is possible,while recovering half a word is not.+ Most windows were already read while the user was speaking+ (``_prefetch_final_windows``). What is left here is the open tail —+ and, should the probe have been slow or absent, any window it did+ not get to — started together and awaited together, so the wait+ after release is one window's read, not the recording's length.+Returns ``""`` when nothing could be read — the caller then fallsback to the incremental text rather than losing the dictation."""- nonlocal session_peak, lost_audio_bytes, final_window_count+ nonlocal final_window_count, final_next_startfrom jarvis.dictation.merge import merge_transcripts- from jarvis.dictation.segment import (- is_silent_segment,- quality_windows,- segment_energy,- )-- windows = quality_windows(- audio,- window_bytes=final_window_bytes,- overlap_bytes=final_overlap_bytes,- bytes_per_second=bytes_per_second,- )- if not windows:+ from jarvis.dictation.segment import quality_windows++ total = len(audio)+ if total > final_next_start:+ base = final_next_start+ for start, end in quality_windows(+ audio[base:],+ window_bytes=final_window_bytes,+ overlap_bytes=final_overlap_bytes,+ bytes_per_second=bytes_per_second,+ ):+ _launch_final_window(base + start, base + end, prefetched=False)+ final_next_start = total+ final_window_count = len(final_tasks)+ if not final_tasks:return ""- final_window_count = len(windows)- # ``auto`` is passed explicitly rather than omitted: an absent- # language argument means "no opinion" to a provider, which lands- # on whatever the recognition language is pinned to — the exact- # inheritance that used to write German speech in English.- ask_for = (- "auto"- if code_switching or dictation_language == "auto"- else dictation_language- )- parts: list[str] = []- dead_streak = 0- for start, end in windows:- piece = audio[start:end]- if len(piece) < min_bytes:- continue- peak, _rms = segment_energy(piece)- session_peak = max(session_peak, peak)- if is_silent_segment(piece, session_peak=session_peak):- continue- if dead_streak >= _DICTATION_FINAL_DEAD_PIECES:- # The provider is not flaky, it is down. Counting the rest- # as lost is what degrades the outcome, and the degraded- # outcome is what keeps the audio for a later Restore.- lost_audio_bytes += len(audio) - start- log.warning(- "final dictation transcription abandoned after %d "- "consecutive failed windows (%s) — %.1fs of audio kept "- "for a later retry rather than making you wait.",- dead_streak,- stt_error_detail or stt_error or "unknown error",- (len(audio) - start) / bytes_per_second,- )- break- text, was_read = await _read_piece(piece, ask_for=ask_for)- 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- # Only the audio this window did not SHARE with its- # neighbour is at risk; the overlap is read by the window- # after it. Counting the whole window would report a loss- # the user never experienced.- lost_audio_bytes += max(0, (end - start) - final_overlap_bytes)+ await asyncio.gather(*final_tasks.values(), return_exceptions=True)+ parts = [+ final_reads[idx][0]+ for idx in sorted(final_reads)+ if final_reads[idx][0]+ ]return merge_transcripts(parts)async def _finalize_tail(tail: bytes) -> str:@@ -11726,7 +11879,11 @@ class SpeechPipeline:# a recognizer given twenty-five seconds instead of eight# knows which language it is hearing — which is the whole# difference between a transcript and a translation.+ release_started = time.monotonic()quality_text = await _final_quality_text(bytes(buffer))+ release_wait_ms = round(+ (time.monotonic() - release_started) * 1000.0+ )if quality_text:raw_text = quality_textfinal_pass_status = "applied" # noqa: S105 - status token@@ -11805,6 +11962,8 @@ class SpeechPipeline:stt_audit=(f"final_pass:{final_pass_status}",f"final_windows:{final_window_count}",+ f"final_windows_prefetched:{final_prefetched}",+ f"release_wait_ms:{release_wait_ms}",f"truncation_repairs:{truncation_repairs}",f"code_switching:{'on' if code_switching else 'off'}",f"capture_restarts:{capture_restart_count}",@@ -11902,6 +12061,12 @@ class SpeechPipeline:# also abort before it publishes. Both land here. Scheduled rather# than awaited, because awaiting inside a cancelled task is not# reliable.+ #+ # A hangup or a crash leaves prefetched final windows in flight;+ # nothing will read their answers, so stop asking for them.+ for pending in final_tasks.values():+ if not pending.done():+ pending.cancel()if not getattr(self, "_dictation_completion_published", True):self._dictation_completion_published = Truequality_metrics = audio_quality.snapshot(diff --git a/jarvis/speech/stt_fallback.py b/jarvis/speech/stt_fallback.pyindex ebb95ea4c3..e1f9390088 100644--- a/jarvis/speech/stt_fallback.py+++ b/jarvis/speech/stt_fallback.py@@ -29,6 +29,7 @@ What it does NOT do, on purpose:from __future__ import annotations+import asyncioimport loggingimport timefrom collections.abc import AsyncIterator, Sequence@@ -105,6 +106,13 @@ class FallbackSTT:# The alternate that last worked, tried first among the alternates so a# long dictation does not re-walk the whole chain on every segment.self._preferred: str | None = None+ # One lock per provider that cannot take concurrent calls. The chain is+ # handed concurrent requests by the dictation lane when its PRIMARY+ # allows them; a crossover to a native engine (faster-whisper raises+ # ``TranscribeBusy`` on a second caller, AP-24) must then serialise+ # those calls here rather than turn each of them into an ``engine_busy``+ # failure — which is exactly what the live 2026-08-15 history shows.+ self._serial_locks: dict[str, asyncio.Lock] = {}# ------------------------------------------------------------------# Delegation@@ -119,6 +127,17 @@ class FallbackSTT:def provider_label(self) -> str:return self._primary_name+ @property+ def supports_concurrent_requests(self) -> bool:+ """Whether callers may run several transcriptions at once.++ Answered by the PRIMARY, because that is the provider those concurrent+ calls normally land on. A crossover mid-flight to a provider that+ cannot take them is serialised inside :meth:`_call`, so a caller that+ read ``True`` here stays safe either way.+ """+ return bool(getattr(self._primary, "supports_concurrent_requests", False))+@propertydef last_used_provider(self) -> str:"""Which provider produced the most recent transcript."""@@ -208,7 +227,12 @@ class FallbackSTT:if fn is None:continuetry:- result = await fn(*args, **kwargs)+ if getattr(provider, "supports_concurrent_requests", False):+ result = await fn(*args, **kwargs)+ else:+ lock = self._serial_locks.setdefault(name, asyncio.Lock())+ async with lock:+ result = await fn(*args, **kwargs)except Exception as exc: # noqa: BLE001 — classified belowkind = _classify(exc)if not kind:diff --git a/tests/unit/dictation/test_incremental_final_pass.py b/tests/unit/dictation/test_incremental_final_pass.pynew file mode 100644index 0000000000..b646d7fb92--- /dev/null+++ b/tests/unit/dictation/test_incremental_final_pass.py@@ -0,0 +1,354 @@+"""The final pass keeps up with the recording instead of starting after it.++What this guards (live history 2026-08-14 → 08-22, 202 dictations): the wait+after key release grew with the recording — 0.66 s median for a short one,+2.2 s for 25–50 s, 4.6 s past 50 s — because the final-quality windows were+read only after release, one after another. Now a window is closed and read+the moment the recording has grown past it, while the user is still talking,+and whatever is left at release is read concurrently when the provider allows+it. The windows themselves are the ones the one-shot pass would have cut; only+WHEN they are read moved.+"""++from __future__ import annotations++import asyncio+import contextlib+import time+from dataclasses import dataclass+from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.core.config import DictationConfig+from jarvis.core.events import DictationCompleted+from jarvis.dictation.segment import next_quality_window, quality_windows+from jarvis.speech.pipeline import SpeechPipeline+from jarvis.speech.stt_fallback import FallbackSTT++# 16 kHz mono int16 — the capture contract every dictation records under.+BYTES_PER_SECOND = 16_000 * 2+# Ten tokens per answer: well above the truncation floor for any window these+# tests cut, so the guard that re-reads a short transcript never fires here.+_ANSWERS = [+ "alpha one two three four five six seven eight nine",+ "bravo one two three four five six seven eight nine",+ "charlie one two three four five six seven eight nine",+ "delta one two three four five six seven eight nine",+ "echo one two three four five six seven eight nine",+]+++def _voiced(seconds: float) -> bytes:+ """Speech-loud audio; sample 0x2211 = 8721 sits far above every silence floor."""+ return b"\x11\x22" * int(16_000 * seconds)+++@dataclass+class _Transcript:+ text: str+ language: str = "en"+++class _CountingSTT:+ """A provider answering a fixed script, measuring how many calls overlap."""++ supports_streaming = False++ def __init__(+ self, *, delay_s: float = 0.0, concurrent: bool = False, script: list[str] | None = None+ ) -> None:+ self._script = list(script or _ANSWERS)+ self._delay_s = delay_s+ self.calls = 0+ self.in_flight = 0+ self.max_in_flight = 0+ self.call_times: list[float] = []+ if concurrent:+ self.supports_concurrent_requests = True++ async def transcribe_pcm(self, pcm: bytes, language: str | None = None) -> Any:+ self.calls += 1+ self.call_times.append(time.monotonic())+ index = min(self.calls, len(self._script)) - 1+ self.in_flight += 1+ self.max_in_flight = max(self.max_in_flight, self.in_flight)+ try:+ if self._delay_s:+ await asyncio.sleep(self._delay_s)+ return _Transcript(text=self._script[index])+ finally:+ self.in_flight -= 1+++class _Chunk:+ def __init__(self, pcm: bytes) -> None:+ self.pcm = pcm+ self.timestamp_ns = 0+++class _FakeMic:+ """Prepared audio delivered in slices, then it waits to be cancelled."""++ def __init__(self, pcm: bytes, *, slice_s: float = 0.0, pace_s: float = 0.0) -> None:+ self._pcm = pcm+ self._slice = int(slice_s * BYTES_PER_SECOND) or len(pcm)+ self._pace_s = pace_s+ self.delivered = asyncio.Event()++ async def stream(self): # noqa: ANN201 — an async generator of chunks+ for offset in range(0, len(self._pcm), self._slice):+ yield _Chunk(self._pcm[offset : offset + self._slice])+ if self._pace_s:+ await asyncio.sleep(self._pace_s)+ self.delivered.set()+ 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, mic: _FakeMic, **cfg: Any):+ """A pipeline wired for exactly one ``_dictation_session`` run."""+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._dictation_cfg = DictationConfig(+ history_enabled=False,+ polish=False,+ # Five-second windows — the smallest the schema allows — so a short+ # synthetic recording holds several of them.+ final_window_seconds=5.0,+ final_overlap_seconds=0.5,+ **cfg,+ )+ pipe._dictation_target = "chat"+ pipe._dictation_completion_published = False+ pipe._dictation_max_s = 60.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(mic) # 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+++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])+++def _no_preview(monkeypatch: pytest.MonkeyPatch) -> None:+ """No on-device engine and no cloud preview budget: every provider call in+ these tests belongs to the final pass."""+ import jarvis.dictation.local_preview as local_preview+ import jarvis.dictation.preview_budget as preview_budget++ monkeypatch.setattr(local_preview, "local_preview", lambda: None)+ monkeypatch.setattr(+ preview_budget,+ "preview_budget",+ lambda: SimpleNamespace(try_spend=lambda: False),+ )+++# --------------------------------------------------------------------------+# Windows are read while the user is still speaking+# --------------------------------------------------------------------------+++async def test_windows_are_read_before_release_and_only_the_tail_after(+ _no_preview: None,+) -> None:+ # Twelve seconds of speech arriving in half-second slices while the probe+ # ticks every 20 ms: the 5 s windows at 0 s and ~4.5 s are complete long+ # before the key is released, so they are read then; only the ~3 s tail+ # is left for release.+ stt = _CountingSTT()+ mic = _FakeMic(_voiced(12.0), slice_s=0.5, pace_s=0.01)+ pipe, events = _session_pipeline(+ stt, mic, segment_seconds=0.0, partial_interval_s=0.02+ )++ task = asyncio.create_task(pipe._dictation_session())+ await asyncio.wait_for(mic.delivered.wait(), timeout=10)+ # A few probe ticks so the last prefetchable window is launched and read.+ await asyncio.sleep(0.2)+ calls_before_release = stt.calls+ pipe._dictation_stop_event.set()+ await asyncio.wait_for(task, timeout=30)++ assert calls_before_release >= 2, "prefetched windows were not read before release"+ prefetched = _audit(events, "final_windows_prefetched")+ # At least two windows were closed while the recording was still growing+ # (the quietest-point search may cut a window short of its nominal length,+ # so the exact count depends on the audio); exactly ONE window — the open+ # tail — was left for release, and every window was read exactly once.+ assert prefetched >= 2+ assert _audit(events, "final_windows") == prefetched + 1+ assert stt.calls == prefetched + 1+ # The windows are assembled in recording order, whatever order they came+ # back in.+ assert _completed(events).raw_text.split()[0] == "alpha"+ assert "charlie" in _completed(events).raw_text+ assert _completed(events).raw_text.index("bravo") < _completed(events).raw_text.index(+ "charlie"+ )+++async def test_a_short_recording_is_one_window_read_at_release(_no_preview: None) -> None:+ stt = _CountingSTT()+ mic = _FakeMic(_voiced(3.0))+ pipe, events = _session_pipeline(stt, mic, segment_seconds=0.0, partial_interval_s=0.0)++ task = asyncio.create_task(pipe._dictation_session())+ await asyncio.sleep(0)+ pipe._dictation_stop_event.set()+ await asyncio.wait_for(task, timeout=30)++ assert stt.calls == 1+ assert _audit(events, "final_windows_prefetched") == 0+ assert _audit(events, "final_windows") == 1+ assert _completed(events).raw_text.startswith("alpha")+++# --------------------------------------------------------------------------+# What is left at release is read together, when the provider allows it+# --------------------------------------------------------------------------+++async def _release_with_windows_left(stt: _CountingSTT) -> list[object]:+ # No probe at all (interval 0): nothing is prefetched, so every window of+ # a 14 s recording is still to be read when the key is released — the+ # shape of a slow or absent probe, and the one that used to serialise.+ mic = _FakeMic(_voiced(14.0))+ pipe, events = _session_pipeline(stt, mic, segment_seconds=0.0, partial_interval_s=0.0)+ task = asyncio.create_task(pipe._dictation_session())+ await asyncio.sleep(0)+ pipe._dictation_stop_event.set()+ await asyncio.wait_for(task, timeout=30)+ return events+++async def test_a_concurrent_provider_reads_the_remaining_windows_side_by_side(+ _no_preview: None,+) -> None:+ stt = _CountingSTT(delay_s=0.15, concurrent=True)++ events = await _release_with_windows_left(stt)++ assert stt.calls >= 3+ 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+ text = _completed(events).raw_text+ assert text.index("alpha") < text.index("bravo") < text.index("charlie")+++async def test_a_native_engine_never_sees_two_reads_at_once(_no_preview: None) -> None:+ # No capability flag: the provider is treated as a native engine (AP-24)+ # and its windows are read strictly one after another.+ stt = _CountingSTT(delay_s=0.05)++ events = await _release_with_windows_left(stt)++ assert stt.calls >= 3+ assert stt.max_in_flight == 1+ text = _completed(events).raw_text+ assert text.index("alpha") < text.index("bravo") < text.index("charlie")+++# --------------------------------------------------------------------------+# The fallback chain keeps a native alternate safe under concurrent callers+# --------------------------------------------------------------------------+++async def test_fallback_chain_serialises_a_provider_without_the_capability() -> None:+ native = _CountingSTT(delay_s=0.05)+ chain = FallbackSTT(native, alternates=[], build=lambda name: None, primary_name="native")++ assert chain.supports_concurrent_requests is False+ await asyncio.gather(*(chain.transcribe_pcm(b"\x11\x22" * 16_000) for _ in range(3)))++ assert native.calls == 3+ assert native.max_in_flight == 1+++async def test_fallback_chain_lets_a_capable_provider_run_concurrently() -> None:+ cloud = _CountingSTT(delay_s=0.05, concurrent=True)+ chain = FallbackSTT(cloud, alternates=[], build=lambda name: None, primary_name="cloud")++ assert chain.supports_concurrent_requests is True+ await asyncio.gather(*(chain.transcribe_pcm(b"\x11\x22" * 16_000) for _ in range(3)))++ assert cloud.max_in_flight == 3+++# --------------------------------------------------------------------------+# The incremental cut is the one-shot cut+# --------------------------------------------------------------------------+++def test_incremental_windows_equal_the_one_shot_windows() -> None:+ # Speech with quiet dips every ~4 s, so the quietest-point search has+ # somewhere to land and the incremental step must find the SAME spot the+ # one-shot pass does from the finished recording.+ pieces = []+ for _ in range(9):+ pieces.append(b"\x11\x22" * int(16_000 * 3.7))+ pieces.append(b"\x05\x00" * int(16_000 * 0.3))+ pcm = b"".join(pieces)+ window_bytes = 5 * BYTES_PER_SECOND+ overlap_bytes = BYTES_PER_SECOND // 2++ one_shot = quality_windows(pcm, window_bytes=window_bytes, overlap_bytes=overlap_bytes)++ incremental: list[tuple[int, int]] = []+ start = 0+ # Grow the "recording" in half-second steps and cut whenever a full+ # window lies past ``start`` — exactly what the probe does per tick.+ for total in range(BYTES_PER_SECOND // 2, len(pcm) + 1, BYTES_PER_SECOND // 2):+ while total - start > window_bytes:+ scan = pcm[start : start + window_bytes]+ window, start = next_quality_window(+ scan,+ start=start,+ total=total,+ window_bytes=window_bytes,+ overlap_bytes=overlap_bytes,+ )+ incremental.append(window)+ tail = quality_windows(pcm[start:], window_bytes=window_bytes, overlap_bytes=overlap_bytes)+ incremental.extend((start + a, start + b) for a, b in tail)++ assert incremental == one_shot+ assert len(one_shot) >= 6