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.

feat(dictation): run the live preview locally so the transcript keeps the quota

Ruben Lütkecec6b9665819
diff --git a/jarvis/dictation/local_preview.py b/jarvis/dictation/local_preview.py
new file mode 100644
index 0000000000..afb59c9b95
--- /dev/null
+++ b/jarvis/dictation/local_preview.py
@@ -0,0 +1,265 @@
+"""Local engine for the dictation LIVE PREVIEW — the words while you speak.
+
+The preview and the transcript want opposite things. The transcript wants the
+best model available and can afford a round-trip; the preview wants to be on
+screen NOW and is thrown away on the next tick. Sending both to the same cloud
+provider meant the throwaway half was spending the quota the keeping half
+needed — measured at ~40 requests per minute of speech, ~85 % of it preview,
+against a 20 RPM ceiling that Groq applies to its **paid plan too**. That is
+what made a 137 s dictation come back with 367 characters.
+
+Measured on the maintainer's box (RTX 5070 Ti, faster-whisper ``base``,
+int8_float16):
+
+ 1 s tail -> 34 ms 4 s tail -> 63 ms 8 s tail -> 137 ms
+
+against 400-1500 ms plus one rationed request for a cloud round-trip. So the
+preview is not merely cheaper locally, it is an order of magnitude faster —
+and it costs no quota at all, which is what lets the transcript have the whole
+budget. That is the difference between "runs out after 40 seconds" and "as long
+as you care to talk".
+
+Why ``base`` and not the model the transcript uses: a preview is read at a
+glance and replaced a second later, so a rare wrong ending costs nothing, while
+a model that takes 800 ms turns the preview into a lagging distraction. The
+FINAL text is never produced here — it always comes from the configured
+provider, so the words that land in the user's document are the good ones.
+
+Degrades honestly (CLAUDE.md §3): on a host without ``faster_whisper`` — a base
+or headless install — this reports unavailable and the caller falls back to the
+budgeted cloud preview. No GPU is required either; the engine picks CPU and the
+caller simply sees a slower preview.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import threading
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+#: Model for the preview. Small enough to answer in tens of milliseconds, good
+#: enough that the line on screen reads as what was said. Never used for the
+#: text that is actually delivered.
+PREVIEW_MODEL = "base"
+
+#: How long one preview transcription may take before we stop waiting for it.
+#: The preview is worthless once it is stale, and a wedged native engine must
+#: never hold the dictation loop (AP-24: a timeout BOUNDS the wait, it does not
+#: recover the engine — that is what ``_failures``/``reset`` below are for).
+PREVIEW_TIMEOUT_S = 2.0
+
+#: Consecutive failures after which the engine is dropped and rebuilt on next
+#: use. A native engine that has wedged never recovers by being asked again.
+_MAX_FAILURES = 3
+
+
+def faster_whisper_available() -> bool:
+ """Is a local engine importable here? Cheap spec probe, no heavy import."""
+ import importlib.util
+
+ return importlib.util.find_spec("faster_whisper") is not None
+
+
+class LocalPreviewTranscriber:
+ """Lazily-built local engine for preview text. Never raises to the caller.
+
+ One instance owns one engine and serialises access to it with a
+ NON-BLOCKING lock: a second caller arriving while a transcription is in
+ flight is turned away rather than queued (AP-24 — ctranslate2 is not
+ thread-safe, and a queued caller would wedge it permanently). Turning a
+ preview away is free; the next tick asks again.
+ """
+
+ def __init__(self, model_name: str = PREVIEW_MODEL) -> None:
+ self._model_name = model_name
+ self._model: Any = None
+ self._lock = threading.Lock()
+ self._busy = threading.Lock()
+ self._failures = 0
+ self._unavailable = False
+ self._loading = False
+ self._load_failed = False
+
+ @property
+ def available(self) -> bool:
+ """False once this host has proven it cannot serve a local preview."""
+ return not self._unavailable
+
+ @property
+ def ready(self) -> bool:
+ """Whether the engine can answer right now (model built)."""
+ return self._model is not None
+
+ def _load_model(self) -> None:
+ """Build the engine. Runs OFF the transcribe path — see ``transcribe``."""
+ try:
+ from faster_whisper import WhisperModel
+
+ device, compute = self._pick_device()
+ model = WhisperModel(
+ self._model_name, device=device, compute_type=compute
+ )
+ with self._lock:
+ self._model = model
+ log.info(
+ "Dictation preview engine ready: %s on %s (%s).",
+ self._model_name,
+ device,
+ compute,
+ )
+ except Exception as exc: # noqa: BLE001 — a preview must never break dictation
+ self._load_failed = True
+ self._unavailable = True
+ log.info(
+ "Local dictation preview unavailable (%s: %s) — the transcript "
+ "is unaffected; the live line falls back to the provider.",
+ type(exc).__name__,
+ exc,
+ )
+ finally:
+ self._loading = False
+
+ @staticmethod
+ def _pick_device() -> tuple[str, str]:
+ """``(device, compute_type)`` — CUDA when it is genuinely usable.
+
+ Capability probe, never a hardware name (AP-21/AP-25 territory): CUDA
+ being importable and CUDA working are different questions, and the
+ answer here only decides how FAST the preview is. Anything uncertain
+ picks CPU, which always works.
+ """
+ try:
+ import torch
+
+ if torch.cuda.is_available():
+ return "cuda", "int8_float16"
+ except Exception as exc: # noqa: BLE001 — a probe must never decide by raising
+ log.debug("Preview CUDA probe failed (%s); using CPU.", exc)
+ return "cpu", "int8"
+
+ def _transcribe_sync(self, pcm: bytes, language: str | None) -> str:
+ import numpy as np
+
+ samples = np.frombuffer(pcm, dtype=np.int16).astype(np.float32) / 32768.0
+ if samples.size == 0:
+ return ""
+ model = self._model
+ if model is None: # pragma: no cover — transcribe() gates on ready
+ return ""
+ segments, _info = model.transcribe(
+ samples,
+ language=language,
+ beam_size=1, # greedy: the preview trades a little accuracy for latency
+ condition_on_previous_text=False,
+ )
+ return " ".join(seg.text for seg in segments).strip()
+
+ async def transcribe(self, pcm: bytes, language: str | None = None) -> str | None:
+ """Preview text, or ``None`` when this tick has none.
+
+ ``None`` is not an error — it is "no preview right now" (engine busy,
+ too slow, or unavailable). The caller shows the previous line and asks
+ again on the next tick.
+ """
+ if self._unavailable or not pcm:
+ return None
+ if self._model is None:
+ # Building the engine takes seconds — far longer than the timeout a
+ # PREVIEW may hold. Loading it inside the timed call meant the first
+ # ticks of the first dictation all "timed out", and each one counted
+ # as an engine failure, so the local preview reliably disabled
+ # itself before it had ever worked once. Load OFF this path and
+ # answer "nothing yet" meanwhile: a missing preview line for the
+ # first couple of seconds is not a failure of anything.
+ self._start_loading()
+ return None
+ if not self._busy.acquire(blocking=False):
+ # A previous preview is still running. Skipping is correct: a queued
+ # call on a native engine is how it wedges (AP-24).
+ return None
+ try:
+ return await asyncio.wait_for(
+ asyncio.to_thread(self._transcribe_sync, pcm, language),
+ timeout=PREVIEW_TIMEOUT_S,
+ )
+ except TimeoutError:
+ self._note_failure("timed out")
+ return None
+ except Exception as exc: # noqa: BLE001 — a preview must never break dictation
+ self._note_failure(f"{type(exc).__name__}: {exc}")
+ return None
+ finally:
+ self._busy.release()
+
+ def _start_loading(self) -> None:
+ """Kick off a one-shot background load. Cheap and idempotent."""
+ with self._lock:
+ if self._loading or self._model is not None or self._load_failed:
+ return
+ self._loading = True
+ threading.Thread(
+ target=self._load_model, name="dictation-preview-load", daemon=True
+ ).start()
+
+ def _note_failure(self, why: str) -> None:
+ """Count a failure and drop the engine once they persist.
+
+ Rebuilding a FRESH engine is the only way back from a wedged native
+ session — re-asking the same one never recovers it (AP-24). Dropping the
+ model is therefore the whole repair here; the NEXT tick sees no model
+ and starts a background rebuild.
+
+ Turning the local path off for good is deliberately NOT decided here. A
+ transcription failure says "this engine is unwell", not "this host
+ cannot run one" — only a failed BUILD proves that, and ``_load_model``
+ is where it is recorded. Deciding it in both places is how a machine
+ that had one bad segment loses its fast preview permanently.
+ """
+ self._failures += 1
+ log.debug("Dictation preview failed (%s), attempt %d.", why, self._failures)
+ if self._failures < _MAX_FAILURES:
+ return
+ with self._lock:
+ self._model = None
+ self._failures = 0
+ log.info("Dictation preview engine dropped (%s); rebuilding on the next tick.", why)
+
+
+_INSTANCE: LocalPreviewTranscriber | None = None
+_INSTANCE_LOCK = threading.Lock()
+
+
+def local_preview() -> LocalPreviewTranscriber | None:
+ """The shared preview engine, or ``None`` where none can run.
+
+ Shared for the same reason the preview budget is: consecutive dictations
+ should not each pay the model load. Returns ``None`` (rather than an inert
+ object) so the caller's fallback is an explicit branch, not a silent no-op.
+ """
+ global _INSTANCE
+ if not faster_whisper_available():
+ return None
+ with _INSTANCE_LOCK:
+ if _INSTANCE is None:
+ _INSTANCE = LocalPreviewTranscriber()
+ return _INSTANCE if _INSTANCE.available else None
+
+
+def reset_local_preview_for_tests() -> None:
+ """Drop the shared engine — test-isolation hook."""
+ global _INSTANCE
+ with _INSTANCE_LOCK:
+ _INSTANCE = None
+
+
+__all__ = [
+ "PREVIEW_MODEL",
+ "PREVIEW_TIMEOUT_S",
+ "LocalPreviewTranscriber",
+ "faster_whisper_available",
+ "local_preview",
+ "reset_local_preview_for_tests",
+]
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index ae32b9dbd2..f207555bda 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -8975,6 +8975,7 @@ class SpeechPipeline:
async def _probe() -> None:
"""Close finished segments and publish the live transcript."""
nonlocal last_published, language, error_backoff_s
+ from jarvis.dictation.local_preview import local_preview
from jarvis.dictation.preview_budget import preview_budget
from jarvis.dictation.segment import is_silent_segment
@@ -9011,19 +9012,34 @@ class SpeechPipeline:
if segment_bytes and len(tail) > segment_bytes:
tail = tail[-segment_bytes:]
tail_text = ""
- if (
- len(tail) >= min_bytes
- and not is_silent_segment(tail, session_peak=session_peak)
- # The preview is the only budgeted caller. It re-sends
- # the open tail on every tick and throws the answer away
- # on the next one, so at ~40 requests per minute of
- # speech it was spending the provider's per-minute limit
- # on a cosmetic feature — and the segment closes that
- # actually produce the transcript were the ones refused.
- # Skipping a preview costs a slightly staler line on
- # screen; skipping a segment costs the user their words.
- and preview_budget().try_spend()
- ):
+ want_preview = len(tail) >= min_bytes and not is_silent_segment(
+ tail, session_peak=session_peak
+ )
+ # LOCAL FIRST. The preview re-sends the open tail on every
+ # tick and throws the answer away on the next one, so on the
+ # provider it was spending the per-minute limit on a
+ # cosmetic feature — and the segment closes that actually
+ # produce the transcript were the ones refused. Locally it
+ # costs no quota at all and is an order of magnitude faster
+ # (measured on the maintainer's GPU: 63 ms for a 4 s tail,
+ # against 400-1500 ms for a round-trip). The transcript
+ # itself is never produced here.
+ engine = local_preview() if want_preview else None
+ if engine is not None:
+ local_text = await engine.transcribe(
+ tail,
+ language=None if dictation_language == "auto"
+ else dictation_language,
+ )
+ if stop_event.is_set():
+ return
+ if local_text is not None:
+ tail_text = local_text
+ want_preview = False # served without touching the quota
+ # Cloud preview only where no local engine can run (a base or
+ # 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)
if stop_event.is_set():
return
diff --git a/tests/unit/dictation/test_local_preview.py b/tests/unit/dictation/test_local_preview.py
new file mode 100644
index 0000000000..0e53d5810c
--- /dev/null
+++ b/tests/unit/dictation/test_local_preview.py
@@ -0,0 +1,171 @@
+"""The live preview runs locally so the transcript keeps the whole quota.
+
+Root cause these lock (2026-07-29): preview and transcript shared one cloud
+provider, so the throwaway half spent the 20 RPM ceiling — which Groq applies to
+its PAID plan too — and the half carrying the user's words got the 429s.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from jarvis.dictation.local_preview import (
+ LocalPreviewTranscriber,
+ local_preview,
+ reset_local_preview_for_tests,
+)
+
+
[email protected](autouse=True)
+def _isolated():
+ reset_local_preview_for_tests()
+ yield
+ reset_local_preview_for_tests()
+
+
+class _Engine(LocalPreviewTranscriber):
+ """Preview engine with the native model replaced by a scripted stub.
+
+ ``_model`` is pre-set because ``transcribe`` gates on it: an engine that has
+ not finished loading answers "nothing yet" without transcribing anything.
+ """
+
+ def __init__(self, text="hallo welt", delay=0.0, error=None): # i18n-allow: German test fixture
+ super().__init__()
+ self.text, self.delay, self.error = text, delay, error
+ self.calls = 0
+ self._model = object() # pretend the load already completed
+
+ def _transcribe_sync(self, pcm, language):
+ self.calls += 1
+ if self.error is not None:
+ raise self.error
+ if self.delay:
+ import time
+
+ time.sleep(self.delay)
+ return self.text
+
+
+async def test_preview_text_comes_back():
+ engine = _Engine(text="ich moechte ein Feature") # i18n-allow: German test fixture
+ assert await engine.transcribe(b"\x00" * 32000) == "ich moechte ein Feature"
+
+
+async def test_empty_audio_needs_no_engine():
+ engine = _Engine()
+ assert await engine.transcribe(b"") is None
+ assert engine.calls == 0
+
+
+async def test_a_second_caller_is_turned_away_not_queued():
+ """AP-24: a queued call into a native engine is how it wedges permanently.
+
+ Skipping costs one stale preview line; queueing costs the whole dictation.
+ """
+ engine = _Engine(delay=0.25)
+ first = asyncio.create_task(engine.transcribe(b"\x00" * 32000))
+ await asyncio.sleep(0.05)
+ assert await engine.transcribe(b"\x00" * 32000) is None
+ assert await first is not None
+ assert engine.calls == 1
+
+
+async def test_a_slow_preview_is_abandoned_not_awaited():
+ """Stale preview text is worthless; the loop must not wait for it."""
+ import jarvis.dictation.local_preview as mod
+
+ engine = _Engine(delay=0.5)
+ original = mod.PREVIEW_TIMEOUT_S
+ mod.PREVIEW_TIMEOUT_S = 0.05
+ try:
+ assert await engine.transcribe(b"\x00" * 32000) is None
+ finally:
+ mod.PREVIEW_TIMEOUT_S = original
+
+
+async def test_a_failing_preview_never_breaks_the_dictation():
+ engine = _Engine(error=RuntimeError("engine exploded"))
+ assert await engine.transcribe(b"\x00" * 32000) is None
+
+
+async def test_a_failing_engine_is_dropped_so_a_fresh_one_can_be_built():
+ """AP-24: re-asking a wedged native session never recovers it.
+
+ Dropping the model is the repair — the next tick finds none and rebuilds.
+ Crucially the PATH stays available: one bad segment must not cost this host
+ its fast preview forever. Only a failed BUILD proves the host cannot run one.
+ """
+ engine = _Engine(error=RuntimeError("nope"))
+ for _ in range(3):
+ await engine.transcribe(b"\x00" * 32000)
+
+ assert engine.ready is False, "the wedged engine should have been dropped"
+ assert engine.available is True, "a bad segment is not a dead host"
+
+
+async def test_a_failed_build_is_what_disables_the_local_path():
+ """The honest signal: this host cannot construct an engine at all."""
+ engine = LocalPreviewTranscriber()
+ engine._model_name = "a-model-that-does-not-exist-anywhere"
+ engine._load_model()
+
+ assert engine.available is False
+ assert await engine.transcribe(b"\x00" * 32000) is None
+
+
+def test_no_local_engine_means_no_local_preview(monkeypatch):
+ """A base/headless install has no faster-whisper — the caller must branch.
+
+ Returning None rather than an inert object keeps that fallback an explicit
+ decision instead of a preview that silently never appears.
+ """
+ import jarvis.dictation.local_preview as mod
+
+ monkeypatch.setattr(mod, "faster_whisper_available", lambda: False)
+ assert local_preview() is None
+
+
+def test_the_engine_is_shared_across_dictations(monkeypatch):
+ """Consecutive dictations must not each pay the model load."""
+ import jarvis.dictation.local_preview as mod
+
+ monkeypatch.setattr(mod, "faster_whisper_available", lambda: True)
+ assert local_preview() is local_preview()
+
+
+async def test_loading_the_engine_never_counts_as_a_failure():
+ """REGRESSION: the local preview used to disable itself before ever working.
+
+ Building the engine takes seconds, far longer than a preview may be held
+ for. Loading it inside the timed call made every early tick "time out", and
+ each timeout counted as an engine failure — so the path reliably switched
+ itself off during the first dictation. Loading now happens off the
+ transcribe path and an unready engine simply answers "nothing yet".
+ """
+ engine = LocalPreviewTranscriber()
+ started: list[bool] = []
+ engine._start_loading = lambda: started.append(True) # type: ignore[method-assign]
+
+ for _ in range(10):
+ assert await engine.transcribe(b"\x00" * 32000) is None
+
+ assert started, "an unready engine must kick off its background load"
+ assert engine.available is True, "waiting to load is not a failure"
+
+
+def test_the_device_probe_falls_back_to_cpu_when_cuda_is_not_usable(monkeypatch):
+ """CUDA present and CUDA usable are different questions (AP-21/AP-25)."""
+ import builtins
+
+ real_import = builtins.__import__
+
+ def _no_torch(name, *args, **kwargs):
+ if name == "torch":
+ raise ImportError("no torch here")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _no_torch)
+ assert LocalPreviewTranscriber._pick_device() == ("cpu", "int8")