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(stt): add NVIDIA Nemotron 3.5 as a second on-device voice input

Ruben Lütke730959ec9020
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index bb7894f371..d3a752454d 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -149,7 +149,9 @@ _ON_DEVICE_ATTR = "runs_on_device"
#: does not declare the attribute above. A NAME list is what AP-21 warns about,
#: so it is asked only for our OWN plugins (whose behaviour we know without
#: importing them) and never used to judge a stranger's.
-_SHIPPED_ON_DEVICE_PROVIDERS: frozenset[str] = frozenset({"faster-whisper"})
+_SHIPPED_ON_DEVICE_PROVIDERS: frozenset[str] = frozenset(
+ {"faster-whisper", "nemotron-local"}
+)
@lru_cache(maxsize=32)
@@ -399,6 +401,17 @@ def build_stt_from_config(stt_cfg: Any) -> Any:
kwargs["endpoint"] = ep.base_url.rstrip("/") + "/audio/transcriptions"
if ep.credential:
kwargs["api_key"] = ep.credential
+ # An on-device recognizer gets only the options that mean something to
+ # it. ``prompt`` (decoder bias) and ``timeout_s`` (per-REQUEST ceiling)
+ # are shaped for a cloud call; passing them to a local engine hits the
+ # TypeError retry below, which works but logs a misleading "this plugin
+ # is out of date" warning about a plugin that is perfectly current.
+ # Capability-gated via the plugin's own declaration, not its name
+ # (AP-21). The user's STT dictionary still applies to these providers
+ # through its post-transcription corrections.
+ if provider_runs_on_device(provider_name):
+ for cloud_only in ("prompt", "timeout_s"):
+ kwargs.pop(cloud_only, None)
if not _stt_has_credential(provider_name, kwargs):
logger.warning(
"STT provider {!r} has no usable credential; falling back to the "
diff --git a/jarvis/plugins/stt/nemotron_local.py b/jarvis/plugins/stt/nemotron_local.py
new file mode 100644
index 0000000000..5838a9547a
--- /dev/null
+++ b/jarvis/plugins/stt/nemotron_local.py
@@ -0,0 +1,270 @@
+"""On-device streaming STT: NVIDIA Nemotron 3.5 through sherpa-onnx.
+
+The second local voice-input option next to Whisper, and a genuinely different
+trade rather than a second flavour of the same one:
+
+* **It streams.** A cache-aware FastConformer transducer consumes audio in
+ fixed chunks while the person is still speaking, instead of waiting for the
+ utterance to end and then transcribing it in one pass.
+* **It runs on a CPU.** ONNX Runtime, int8-quantised, ~690 MB — no torch, no
+ CUDA, no NVIDIA hardware despite the model's origin. That matters far more
+ than raw benchmark position: the baseline install is a machine with no GPU.
+* **It is multilingual** (40 locales, German among them). The English-only
+ Nemotron sibling was deliberately NOT used: fed German speech it does not
+ fail, it phonetically mangles it into English words — the same trap the
+ Distil-Whisper checkpoints carry, and a silent wrong answer is worse than an
+ honest failure because it flows straight to the brain.
+
+Structural provider (duck-typed against ``STTProvider``, no inheritance). Both
+the engine and the model are optional and absent on a base install, so every
+heavy import is lazy and a missing piece produces one honest error rather than
+a stack trace three layers down.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import AsyncIterator
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+
+from jarvis.audio.capture import pcm_bytes_to_np
+from jarvis.core.protocols import AudioChunk, Transcript
+
+log = logging.getLogger(__name__)
+
+#: The per-call ``language`` value that REQUESTS detection. Spelled out here
+#: (as in every other STT plugin) because plugins may not import from jarvis.*.
+AUTO_LANGUAGE = "auto"
+
+#: Silence appended before decoding. A streaming transducer emits its last
+#: words only once enough trailing context has arrived; without this padding the
+#: final syllable of an utterance is routinely cut off.
+_TAIL_SILENCE_S = 0.5
+
+#: Silence PREPENDED before the utterance — the less obvious half, and a real
+#: defect without it. A cache-aware encoder starts with an empty context, so the
+#: first chunk is decoded with nothing behind it and the opening word is lost.
+#: Measured on the model's own German sample — "Alles hat ein Ende, nur die # i18n-allow: quoted test-audio transcript, the evidence for this constant
+#: Wurst hat zwei": 0.0 s dropped the opening word entirely, 0.3 s produced a
+#: mangled version of it, and from 0.6 s the sentence came back complete
+#: (measured 2026-07-29). 0.8 s keeps a margin; at ~9x
+#: realtime on a CPU the extra silence costs under 100 ms. In a voice assistant
+#: the first word is usually the command, so losing it is not cosmetic.
+_LEAD_SILENCE_S = 0.8
+
+#: int16 full scale — the divisor that maps PCM to the [-1, 1] floats the
+#: feature extractor is configured for (``normalize_samples`` default).
+_INT16_FULL_SCALE = 32768.0
+
+
+class NemotronLocalSTT:
+ """Local streaming speech-to-text via sherpa-onnx (keyless, on-device)."""
+
+ name = "nemotron-local"
+ # The privacy declaration the rest of the app keys on: nothing this
+ # recognizer hears leaves the machine. The dictation polish pass reads it to
+ # decide whether transcripts may be sent to a cloud model at all, so getting
+ # it wrong in the "cloud" direction would upload text from someone who chose
+ # a local recognizer precisely to prevent that.
+ runs_on_device = True
+ # The model streams natively; this flag describes the CALLER-facing contract,
+ # and today the pipeline hands us complete VAD-segmented utterances. Turning
+ # it on would promise incremental partials through ``stream_transcribe``,
+ # which is a separate piece of pipeline work — claiming it before it exists
+ # would be the dead-config lie this repo keeps auditing for.
+ supports_streaming = False
+
+ def __init__(
+ self,
+ *,
+ language: str | None = None,
+ model_dir: str | Path | None = None,
+ num_threads: int = 2,
+ provider: str = "cpu",
+ ) -> None:
+ self._language = (language or "").strip() or None
+ self._model_dir = Path(model_dir) if model_dir else None
+ self._num_threads = max(1, int(num_threads))
+ self._provider = provider or "cpu"
+ self._recognizer: Any | None = None
+ # One decode at a time per instance. sherpa-onnx supports concurrent
+ # streams by design (it ships a websocket server), but this instance is
+ # a single shared object on the voice path and serialising its use costs
+ # nothing here — a Jarvis turn decodes one utterance at a time — while
+ # removing a whole class of native-engine race (AP-24).
+ self._decode_lock = asyncio.Lock()
+
+ # -- construction -------------------------------------------------------
+ def _resolve_model_files(self) -> dict[str, Path]:
+ from jarvis.speech.local_models import NEMOTRON_MODEL_ID
+ from jarvis.speech.sherpa_models import model_paths
+
+ if self._model_dir is not None:
+ names = (
+ "encoder.int8.onnx",
+ "decoder.int8.onnx",
+ "joiner.int8.onnx",
+ "tokens.txt",
+ )
+ return {name: self._model_dir / name for name in names}
+ return model_paths(NEMOTRON_MODEL_ID)
+
+ def _ensure_model(self) -> None:
+ """Build the recognizer on first use. Raises one honest error if it cannot.
+
+ Deliberately NOT done in ``__init__``: constructing a provider must stay
+ cheap and side-effect free (AP-26), and the factory builds one during
+ startup where a 690 MB model load has no business being.
+ """
+ if self._recognizer is not None:
+ return
+ try:
+ import sherpa_onnx # noqa: PLC0415 — optional engine, lazy on purpose
+ except ImportError as exc:
+ raise RuntimeError(
+ "The local speech runtime (sherpa-onnx) is not installed, so "
+ "Nemotron cannot transcribe. Install it from the API-Keys view, "
+ "or switch voice input to a provider you have a key for."
+ ) from exc
+
+ files = self._resolve_model_files()
+ missing = [name for name, path in files.items() if not path.is_file()]
+ if missing:
+ raise RuntimeError(
+ "The Nemotron model files are not on this machine yet "
+ f"(missing: {', '.join(sorted(missing))}). Download them from "
+ "the API-Keys view."
+ )
+
+ log.info(
+ "Loading local Nemotron model (%s, %d threads) from %s",
+ self._provider,
+ self._num_threads,
+ files["tokens.txt"].parent,
+ )
+ self._recognizer = sherpa_onnx.OnlineRecognizer.from_transducer(
+ tokens=str(files["tokens.txt"]),
+ encoder=str(files["encoder.int8.onnx"]),
+ decoder=str(files["decoder.int8.onnx"]),
+ joiner=str(files["joiner.int8.onnx"]),
+ num_threads=self._num_threads,
+ provider=self._provider,
+ # The transducer family this bundle belongs to. Without it the
+ # runtime guesses from the graph, and a wrong guess fails at load
+ # rather than quietly — but stating it keeps the failure impossible.
+ model_type="nemo_transducer",
+ decoding_method="greedy_search",
+ )
+
+ # -- transcription ------------------------------------------------------
+ async def transcribe(self, audio: AsyncIterator[AudioChunk]) -> Transcript:
+ """Collect the whole utterance, then decode it in one pass."""
+ pieces: list[np.ndarray] = []
+ sample_rate = 16_000
+ async for chunk in audio:
+ pieces.append(pcm_bytes_to_np(chunk.pcm))
+ sample_rate = chunk.sample_rate
+ if not pieces:
+ return Transcript(text="", language="unknown", confidence=0.0)
+ return await self._decode(np.concatenate(pieces), sample_rate, None)
+
+ async def transcribe_pcm(
+ self,
+ pcm_bytes: bytes,
+ sample_rate: int = 16_000,
+ language: str | None = None,
+ ) -> Transcript:
+ """Direct path for VAD output: int16 PCM bytes -> transcript."""
+ return await self._decode(
+ pcm_bytes_to_np(pcm_bytes), sample_rate, language
+ )
+
+ async def stream_transcribe(
+ self, audio: AsyncIterator[AudioChunk]
+ ) -> AsyncIterator[Transcript]:
+ """One final transcript, matching ``supports_streaming = False``.
+
+ The protocol requires the method; yielding exactly one element is the
+ documented non-streaming shape. It does not pretend to emit partials.
+ """
+ yield await self.transcribe(audio)
+
+ def _language_for(self, per_call: str | None) -> str | None:
+ """The language for ONE call; ``None`` means "let the model detect".
+
+ ``"auto"`` is an explicit request to DETECT and therefore clears the
+ configured pin for this call — treating it as "no argument given" is
+ what once let dictation inherit a German pin and write German speech in
+ English.
+ """
+ if per_call is None or not str(per_call).strip():
+ return self._language
+ value = str(per_call).strip()
+ return None if value.lower() == AUTO_LANGUAGE else value
+
+ async def _decode(
+ self, samples: np.ndarray, sample_rate: int, per_call_language: str | None
+ ) -> Transcript:
+ if samples.size == 0:
+ return Transcript(text="", language="unknown", confidence=0.0)
+ language = self._language_for(per_call_language)
+ async with self._decode_lock:
+ return await asyncio.to_thread(
+ self._decode_blocking, samples, sample_rate, language
+ )
+
+ def _decode_blocking(
+ self, samples: np.ndarray, sample_rate: int, language: str | None
+ ) -> Transcript:
+ self._ensure_model()
+ recognizer = self._recognizer
+ assert recognizer is not None # _ensure_model raises otherwise
+
+ audio = np.asarray(samples, dtype=np.float32)
+ # pcm_bytes_to_np hands back int16-scaled values; the feature extractor
+ # is configured for [-1, 1]. Scaling by a peak check rather than blindly
+ # keeps a caller that already normalised from being divided twice.
+ if np.max(np.abs(audio)) > 1.0:
+ audio = audio / _INT16_FULL_SCALE
+
+ stream = recognizer.create_stream()
+ if language:
+ # Per-stream language pin (the multilingual encoder's prompt input).
+ # Best-effort: an engine build without the option must not take the
+ # turn down — it simply auto-detects, which is the documented
+ # default behaviour anyway.
+ try:
+ stream.set_option("language", language)
+ except Exception as exc: # noqa: BLE001
+ log.debug(
+ "Nemotron language pin %r not applied (%s); auto-detecting.",
+ language,
+ exc,
+ )
+ stream.accept_waveform(
+ sample_rate, np.zeros(int(sample_rate * _LEAD_SILENCE_S), dtype=np.float32)
+ )
+ stream.accept_waveform(sample_rate, audio)
+ stream.accept_waveform(
+ sample_rate, np.zeros(int(sample_rate * _TAIL_SILENCE_S), dtype=np.float32)
+ )
+ stream.input_finished()
+ while recognizer.is_ready(stream):
+ recognizer.decode_stream(stream)
+ result = recognizer.get_result(stream)
+ text = (result or "").strip()
+ return Transcript(
+ text=text,
+ language=language or "auto",
+ # The transducer exposes no calibrated per-utterance probability;
+ # inventing one would put a fabricated number in front of every
+ # downstream confidence check.
+ confidence=1.0 if text else 0.0,
+ )
+
+ async def aclose(self) -> None:
+ """Release the recognizer so a switched-away provider frees its memory."""
+ self._recognizer = None
diff --git a/jarvis/speech/local_models.py b/jarvis/speech/local_models.py
index 405f7c9f63..7fddac3030 100644
--- a/jarvis/speech/local_models.py
+++ b/jarvis/speech/local_models.py
@@ -277,8 +277,13 @@ class LocalProvider:
#: in pyproject.toml can be checked against one another instead of drifting
#: apart in two files that never meet.
pip_package: str
+ #: Model repository the bundle is fetched from. ``None`` for Whisper, whose
+ #: engine manages its own cache.
+ hf_repo: str | None = None
#: Files that must exist inside a sherpa bundle for it to count as complete.
- #: Empty for Whisper, whose weights live in the HuggingFace cache.
+ #: This ONE tuple is both the download list and the completeness check, so a
+ #: bundle can never be declared ready against a shorter list than the one
+ #: that was fetched. Empty for Whisper.
required_files: tuple[str, ...] = ()
@@ -295,6 +300,25 @@ WHISPER_VOICE_MODEL = "large-v3"
#: (CLAUDE.md section 3), which is why it can be installed from inside the app.
FASTER_WHISPER_PACKAGE = "faster-whisper>=1.0"
+#: pip requirement for the ONNX-Runtime speech stack (Apache-2.0, torch-free,
+#: wheels for Windows/macOS/Linux). The FLOOR IS LOAD-BEARING: multilingual
+#: Nemotron needs the ``prompt_index`` encoder input that landed in 1.13.3
+#: (PR #3671, released 2026-06-15). An older wheel loads the same files and
+#: then transcribes every language as English — a silent wrong answer, which is
+#: worse than a refusal, so the version is pinned rather than hoped for.
+SHERPA_ONNX_PACKAGE = "sherpa-onnx>=1.13.3"
+
+#: The multilingual Nemotron 3.5 streaming bundle, int8-quantised at a 560 ms
+#: chunk. Choices worth stating: MULTILINGUAL (the ``-en-`` sibling would
+#: mangle German into English words, the same trap the English-only Whisper
+#: checkpoints carry), int8 (about a third of the size, and this must run on a
+#: machine with no GPU), and 560 ms (the middle of the offered 80–1120 ms
+#: chunk sizes: low enough to feel live, long enough that accuracy holds).
+NEMOTRON_MODEL_ID = "nemotron-3.5-asr-streaming-0.6b-560ms-int8"
+NEMOTRON_HF_REPO = (
+ "csukuangfj2/sherpa-onnx-nemotron-3.5-asr-streaming-0.6b-560ms-int8-2026-06-11"
+)
+
LOCAL_PROVIDERS: tuple[LocalProvider, ...] = (
LocalProvider(
provider_id="faster-whisper",
@@ -305,6 +329,22 @@ LOCAL_PROVIDERS: tuple[LocalProvider, ...] = (
download_size="about 3 GB",
pip_package=FASTER_WHISPER_PACKAGE,
),
+ LocalProvider(
+ provider_id="nemotron-local",
+ tier="stt",
+ runtime="sherpa-onnx",
+ model_id=NEMOTRON_MODEL_ID,
+ model_label="Nemotron 3.5 (streaming)",
+ download_size="about 690 MB",
+ pip_package=SHERPA_ONNX_PACKAGE,
+ hf_repo=NEMOTRON_HF_REPO,
+ required_files=(
+ "encoder.int8.onnx",
+ "decoder.int8.onnx",
+ "joiner.int8.onnx",
+ "tokens.txt",
+ ),
+ ),
)
diff --git a/jarvis/speech/sherpa_models.py b/jarvis/speech/sherpa_models.py
new file mode 100644
index 0000000000..a00aae76ba
--- /dev/null
+++ b/jarvis/speech/sherpa_models.py
@@ -0,0 +1,136 @@
+"""Download of the ONNX model bundles the local sherpa-onnx providers run.
+
+Unlike Whisper — whose weights live in the HuggingFace cache that
+``faster_whisper`` manages itself — a sherpa-onnx model is a handful of loose
+files (encoder / decoder / joiner / tokens, or a voice + its tokens) that the
+recognizer is handed by path. So this module owns their whole lifecycle: where
+they land, how they get there, and what "complete" means.
+
+Two properties matter more than speed here:
+
+* **Atomic.** Files are written into a temporary directory next to the target
+ and moved into place only once every one of them arrived. A half-finished
+ download must never be visible under the model's real name, because the
+ readiness probe would then see a directory full of files and call the
+ provider ready — and the failure would surface as a native crash mid-sentence
+ instead of an honest "download it again".
+* **Resumable by simply re-running.** A failed attempt leaves nothing behind,
+ so pressing the button again is always the correct fix. There is no partial
+ state a user could get stuck in.
+
+The files are fetched from the model repository over plain HTTPS rather than
+through ``huggingface_hub``: the base install has no HF client of its own (that
+package arrives with the optional Whisper engine), and a local TTS voice must
+not drag a downloader dependency into an install that only wants to speak.
+"""
+from __future__ import annotations
+
+import logging
+import shutil
+import tempfile
+from collections.abc import Callable
+from pathlib import Path
+
+from jarvis.speech.local_models import sherpa_model_dir
+
+log = logging.getLogger("jarvis.speech.sherpa_models")
+
+#: Direct file endpoint of a HuggingFace repo. ``resolve/main`` serves the raw
+#: bytes (and redirects to the CDN), which is exactly what a plain HTTP client
+#: needs — no API token, no client library.
+_HF_FILE_URL = "https://huggingface.co/{repo}/resolve/main/{path}"
+
+#: Chunk size for the streamed write. A 650 MB encoder must never be held in
+#: memory on a machine that might be a small VPS or an old laptop.
+_CHUNK_BYTES = 1 << 20
+
+
+def _download_file(url: str, target: Path, *, timeout_s: float = 60.0) -> None:
+ """Stream one file to *target*, raising with a usable message on failure."""
+ import httpx
+
+ with httpx.stream(
+ "GET", url, follow_redirects=True, timeout=timeout_s
+ ) as response:
+ response.raise_for_status()
+ with target.open("wb") as fh:
+ for chunk in response.iter_bytes(_CHUNK_BYTES):
+ fh.write(chunk)
+
+
+def download_sherpa_model(
+ model_id: str,
+ *,
+ data_dir: str | None = None,
+ progress: Callable[[str], None] | None = None,
+) -> Path:
+ """Fetch the bundle for *model_id* and return its directory.
+
+ Raises ``LookupError`` for an unknown model (a catalog/caller mismatch, not
+ a network problem) and lets transport errors propagate — the caller turns
+ them into the retryable state the user sees.
+ """
+ entry = get_local_provider_for_model(model_id)
+ if entry is None or not entry.hf_repo or not entry.required_files:
+ raise LookupError(
+ f"No downloadable model bundle is registered for '{model_id}'."
+ )
+
+ target_dir = sherpa_model_dir(model_id, data_dir=data_dir)
+ if target_dir.is_dir() and all(
+ (target_dir / name).is_file() for name in entry.required_files
+ ):
+ log.info("Local model %s is already complete at %s.", model_id, target_dir)
+ return target_dir
+
+ target_dir.parent.mkdir(parents=True, exist_ok=True)
+ # Staged in a sibling directory so the final move is a rename on the SAME
+ # filesystem — an atomic operation, unlike a cross-device copy that could be
+ # interrupted halfway.
+ staging = Path(tempfile.mkdtemp(prefix=f".{model_id}-", dir=target_dir.parent))
+ try:
+ for index, name in enumerate(entry.required_files, start=1):
+ if progress is not None:
+ progress(f"Downloading {name} ({index}/{len(entry.required_files)})…")
+ log.info("Fetching %s for local model %s", name, model_id)
+ _download_file(
+ _HF_FILE_URL.format(repo=entry.hf_repo, path=name), staging / name
+ )
+ # Replace any incomplete previous attempt, then move the finished set in.
+ if target_dir.exists():
+ shutil.rmtree(target_dir, ignore_errors=True)
+ staging.replace(target_dir)
+ finally:
+ shutil.rmtree(staging, ignore_errors=True)
+ log.info("Local model %s ready at %s", model_id, target_dir)
+ return target_dir
+
+
+def get_local_provider_for_model(model_id: str):
+ """The catalog entry whose ``model_id`` is *model_id*, or None.
+
+ The download route knows a model id; the catalog is keyed by provider id.
+ This is the one place that bridges the two, so no caller has to keep a
+ second mapping of its own.
+ """
+ from jarvis.speech.local_models import LOCAL_PROVIDERS
+
+ for entry in LOCAL_PROVIDERS:
+ if entry.model_id == model_id:
+ return entry
+ return None
+
+
+def model_paths(model_id: str, *, data_dir: str | None = None) -> dict[str, Path]:
+ """Absolute paths of a bundle's files, keyed by their filename.
+
+ Providers ask for this instead of composing paths themselves, so the
+ directory layout stays a fact of this module alone.
+ """
+ entry = get_local_provider_for_model(model_id)
+ directory = sherpa_model_dir(model_id, data_dir=data_dir)
+ names = entry.required_files if entry is not None else ()
+ return {name: directory / name for name in names}
+
+
+__all__ = ["download_sherpa_model", "model_paths"]
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 835bf41cf4..fff51e9d54 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -683,6 +683,23 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
"graphics card, which is the trade for keeping everything local."
),
),
+ ProviderSpec(
+ id="nemotron-local",
+ label="Nemotron (on this machine)",
+ tier="stt",
+ auth_mode="none",
+ secret_keys=(),
+ dashboard_url=None,
+ signup_url=None,
+ credential_help=(
+ "The faster on-device option: NVIDIA's Nemotron 3.5 streaming "
+ "model, also fully local and keyless. It covers 40 languages "
+ "including German, needs a ~690 MB download instead of 3 GB, and "
+ "transcribes several times faster than real time on a plain CPU — "
+ "no graphics card required. Pick Whisper instead if you want the "
+ "highest accuracy and have the hardware for it."
+ ),
+ ),
# ── Dictation polish ──────────────────────────────────────────────────
# Derived from POLISH_FAMILIES above, in that tuple's order (Groq first —
# it is the recommended pick because its key is usually already there).
diff --git a/pyproject.toml b/pyproject.toml
index 2c180a2500..94d4f1cd19 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -460,6 +460,9 @@ openwakeword = "jarvis.plugins.wake.openwakeword_provider:OpenWakeWordProvider"
# separate question answered by jarvis.speech.local_models (engine installed +
# checkpoint downloaded), never assumed from the entry-point's presence.
faster-whisper = "jarvis.plugins.stt.fwhisper:FasterWhisperProvider"
+# Local streaming transcription (NVIDIA Nemotron 3.5 via sherpa-onnx / ONNX
+# Runtime). Multilingual and CPU-only; same readiness rule as above.
+nemotron-local = "jarvis.plugins.stt.nemotron_local:NemotronLocalSTT"
groq-api = "jarvis.plugins.stt.groq_api:GroqWhisperAPI"
# OpenRouter cloud transcription — reuses the shared openrouter_api_key.
openrouter-stt = "jarvis.plugins.stt.openrouter_stt:OpenRouterSTT"
diff --git a/tests/unit/plugins/stt/test_nemotron_local.py b/tests/unit/plugins/stt/test_nemotron_local.py
new file mode 100644
index 0000000000..7bb633e5c4
--- /dev/null
+++ b/tests/unit/plugins/stt/test_nemotron_local.py
@@ -0,0 +1,213 @@
+"""Guards for the on-device Nemotron recognizer.
+
+Three of these pin properties that were found by MEASURING the model rather than
+by reading its docs, and that a refactor would silently undo:
+
+* the leading silence that stops the streaming encoder from eating the first
+ word (verified against the model's own German sample: without it, the
+ opening word was missing from the transcript entirely);
+* the privacy declaration the dictation polish floor keys on;
+* honest, actionable errors when the engine or the weights are absent, instead
+ of a native stack trace from three layers down.
+"""
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pytest
+
+from jarvis.plugins.stt import nemotron_local
+from jarvis.plugins.stt.nemotron_local import NemotronLocalSTT
+
+
+class _FakeStream:
+ """Records what the provider feeds the recognizer."""
+
+ def __init__(self) -> None:
+ self.chunks: list[np.ndarray] = []
+ self.options: dict[str, str] = {}
+ self.finished = False
+
+ def set_option(self, key: str, value: str) -> None:
+ self.options[key] = value
+
+ def accept_waveform(self, sample_rate: int, samples: np.ndarray) -> None:
+ self.chunks.append(np.asarray(samples))
+
+ def input_finished(self) -> None:
+ self.finished = True
+
+
+class _FakeRecognizer:
+ def __init__(self, text: str = "hello there") -> None:
+ self.text = text
+ self.stream = _FakeStream()
+ self._decodes = 0
+
+ def create_stream(self) -> _FakeStream:
+ return self.stream
+
+ def is_ready(self, stream: _FakeStream) -> bool:
+ self._decodes += 1
+ return self._decodes <= 1
+
+ def decode_stream(self, stream: _FakeStream) -> None:
+ pass
+
+ def get_result(self, stream: _FakeStream) -> str:
+ return self.text
+
+
+def _provider_with(recognizer: Any, **kwargs: Any) -> NemotronLocalSTT:
+ provider = NemotronLocalSTT(**kwargs)
+ provider._recognizer = recognizer # skip the real 690 MB model load
+ return provider
+
+
+def _pcm(seconds: float, sample_rate: int = 16_000) -> bytes:
+ """A quiet but non-empty int16 buffer of the requested length."""
+ return (np.ones(int(sample_rate * seconds), dtype=np.int16) * 100).tobytes()
+
+
+def test_leading_silence_is_prepended_so_the_first_word_survives() -> None:
+ """The regression: a cache-aware encoder with no context drops word one.
+
+ Measured on the model's own German sample: 0.0 s of lead-in lost the
+ opening word, 0.6 s brought it back. In a voice assistant the first word is
+ usually the command, so this padding is load-bearing, not a nicety.
+ """
+ recognizer = _FakeRecognizer()
+ provider = _provider_with(recognizer)
+
+ asyncio.run(provider.transcribe_pcm(_pcm(1.0), 16_000))
+
+ chunks = recognizer.stream.chunks
+ assert len(chunks) == 3, "expected lead silence, audio, tail silence"
+ lead, audio, tail = chunks
+ assert lead.size >= int(16_000 * 0.6), (
+ "The leading silence must be long enough to prime the encoder; below "
+ "~0.6 s the opening word comes back mangled or missing."
+ )
+ assert np.all(lead == 0.0)
+ assert np.all(tail == 0.0)
+ assert audio.size == 16_000
+
+
+def test_int16_input_is_scaled_into_the_range_the_features_expect() -> None:
+ """Feeding int16-scaled values straight in would mis-normalise the features."""
+ recognizer = _FakeRecognizer()
+ provider = _provider_with(recognizer)
+
+ asyncio.run(provider.transcribe_pcm(_pcm(0.5), 16_000))
+
+ audio = recognizer.stream.chunks[1]
+ assert np.max(np.abs(audio)) <= 1.0
+
+
+def test_configured_language_is_pinned_per_stream() -> None:
+ recognizer = _FakeRecognizer()
+ provider = _provider_with(recognizer, language="de")
+
+ asyncio.run(provider.transcribe_pcm(_pcm(0.3), 16_000))
+
+ assert recognizer.stream.options.get("language") == "de"
+
+
+def test_auto_clears_the_configured_pin_for_that_call() -> None:
+ """"auto" is a request to DETECT, not "no opinion given".
+
+ Treating it as the latter is what once let a German pin leak into an
+ auto-detect path and write German speech as English.
+ """
+ recognizer = _FakeRecognizer()
+ provider = _provider_with(recognizer, language="de")
+
+ result = asyncio.run(provider.transcribe_pcm(_pcm(0.3), 16_000, language="auto"))
+
+ assert "language" not in recognizer.stream.options
+ assert result.language == "auto"
+
+
+def test_a_language_pin_the_engine_rejects_does_not_kill_the_turn() -> None:
+ """An older engine build must degrade to auto-detect, not lose the utterance."""
+
+ class _RefusingStream(_FakeStream):
+ def set_option(self, key: str, value: str) -> None:
+ raise RuntimeError("option not supported by this build")
+
+ recognizer = _FakeRecognizer()
+ recognizer.stream = _RefusingStream()
+ provider = _provider_with(recognizer, language="de")
+
+ result = asyncio.run(provider.transcribe_pcm(_pcm(0.3), 16_000))
+
+ assert result.text == "hello there"
+
+
+def test_empty_audio_returns_an_empty_transcript_not_an_error() -> None:
+ provider = _provider_with(_FakeRecognizer())
+
+ result = asyncio.run(provider.transcribe_pcm(b"", 16_000))
+
+ assert result.text == ""
+ assert result.confidence == 0.0
+
+
+def test_missing_model_files_raise_one_actionable_error(tmp_path: Path) -> None:
+ """Not a native crash: the message must say what to do about it."""
+ pytest.importorskip("sherpa_onnx")
+ provider = NemotronLocalSTT(model_dir=tmp_path)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ asyncio.run(provider.transcribe_pcm(_pcm(0.3), 16_000))
+
+ message = str(excinfo.value)
+ assert "not on this machine" in message
+ assert "API-Keys view" in message
+
+
+def test_missing_engine_raises_one_actionable_error(monkeypatch) -> None:
+ """A base install has no sherpa-onnx; the failure must name the fix."""
+ import builtins
+
+ real_import = builtins.__import__
+
+ def _no_sherpa(name: str, *args: Any, **kwargs: Any) -> Any:
+ if name == "sherpa_onnx":
+ raise ImportError("No module named 'sherpa_onnx'")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _no_sherpa)
+ provider = NemotronLocalSTT()
+
+ with pytest.raises(RuntimeError) as excinfo:
+ asyncio.run(provider.transcribe_pcm(_pcm(0.3), 16_000))
+
+ assert "not installed" in str(excinfo.value)
+
+
+def test_declares_that_it_runs_on_device() -> None:
+ """The privacy floor reads this; a wrong answer uploads a local user's text."""
+ from jarvis.plugins.stt import provider_runs_on_device
+
+ assert NemotronLocalSTT.runs_on_device is True
+ assert provider_runs_on_device("nemotron-local") is True
+
+
+def test_construction_loads_no_model(monkeypatch) -> None:
+ """Building the provider must stay cheap — the 690 MB load waits (AP-26).
+
+ The STT factory constructs a provider during startup, where a model load
+ has no business being; the weights arrive on first use instead.
+ """
+ def _explode(*args: Any, **kwargs: Any) -> Any:
+ raise AssertionError("the model must not be loaded during construction")
+
+ monkeypatch.setattr(nemotron_local.NemotronLocalSTT, "_ensure_model", _explode)
+
+ provider = NemotronLocalSTT(language="de")
+
+ assert provider._recognizer is None