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(wake): any-word Vosk grammar KWS engine - one identical detector on every OS
Ruben Lütkef16874237e62
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex c8f485cf94..11d4612fd4 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1768,6 +1768,21 @@ class SpeechPipeline:"enable the wake word.",self._wake_phrase_label,)+ elif engine == "vosk_kws":+ # Any-word Vosk grammar KWS (design spec 2026-07-05) — same+ # detector on every OS; the phrase is pure configuration, so a+ # live wake-word change is just a new provider instance.+ from jarvis.plugins.wake.vosk_kws_provider import VoskKwsProvider++ self._wake = VoskKwsProvider(+ phrase=plan.phrase,+ model_path=getattr(plan, "vosk_model_path", None) or "",+ keyword=plan.oww_keyword,+ )+ self._openwakeword_enabled = True+ if self._whisper_wake is not None and self._wake_matcher is not None:+ self._whisper_wake._pattern = self._wake_matcher # noqa: SLF001+ self._whisper_wake_enabled = Falseelif engine in ("openwakeword", "custom_onnx"):self._wake = OpenWakeWordProvider(keywords=(plan.oww_keyword,),diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 49264a4b73..0118877aa3 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2179,6 +2179,9 @@ class DesktopApp:wake_plan = resolve_wake_plan(self.cfg.trigger.wake_word,local_whisper_available=_local_whisper_available,+ # Selects the per-language Vosk model for the any-word+ # vosk_kws engine; "auto" falls back to the first installed.+ language=self.cfg.stt.language,)from loguru import logger as _wlogif not wake_plan.wake_available:diff --git a/jarvis/ui/web/frontend/src/constants/wakeEngines.ts b/jarvis/ui/web/frontend/src/constants/wakeEngines.tsindex 2f603fc472..b4a57a2d98 100644--- a/jarvis/ui/web/frontend/src/constants/wakeEngines.ts+++ b/jarvis/ui/web/frontend/src/constants/wakeEngines.ts@@ -9,7 +9,13 @@// See docs/local-wakeword/CUSTOM-WAKE-WORD-DESIGN.md and// docs/anti-drift-three-layer.md.-export const WAKE_ENGINES = ["auto", "openwakeword", "stt_match", "custom_onnx"] as const;+export const WAKE_ENGINES = [+ "auto",+ "openwakeword",+ "vosk_kws",+ "stt_match",+ "custom_onnx",+] as const;export type WakeEngine = (typeof WAKE_ENGINES)[number];@@ -18,6 +24,7 @@ export type WakeEngine = (typeof WAKE_ENGINES)[number];export const WAKE_ENGINE_I18N_KEY: Record<WakeEngine, string> = {auto: "settings_view.wake_word.engine_options.auto",openwakeword: "settings_view.wake_word.engine_options.openwakeword",+ vosk_kws: "settings_view.wake_word.engine_options.vosk_kws",stt_match: "settings_view.wake_word.engine_options.stt_match",custom_onnx: "settings_view.wake_word.engine_options.custom_onnx",};diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 636a6e264d..f58ace7ab2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1039,6 +1039,7 @@"engine_options": {"auto": "Automatisch (empfohlen)","openwakeword": "openWakeWord (eingebaute Phrasen)",+ "vosk_kws": "Keyword-Spotting (beliebige Phrase, überall gleich)","stt_match": "STT-Abgleich (beliebige Phrase, braucht lokales Whisper)","custom_onnx": "Eigenes ONNX-Modell"},diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex caefe7eebc..00c9fc3b49 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1040,6 +1040,7 @@"engine_options": {"auto": "Auto (recommended)","openwakeword": "openWakeWord (built-in phrases)",+ "vosk_kws": "Keyword spotting (any phrase, same on every device)","stt_match": "STT match (any phrase, needs local Whisper)","custom_onnx": "Custom ONNX model"},diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex f0409d558e..24e9990659 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1039,6 +1039,7 @@"engine_options": {"auto": "Automático (recomendado)","openwakeword": "openWakeWord (frases integradas)",+ "vosk_kws": "Detección de palabras clave (cualquier frase, igual en todos los equipos)","stt_match": "Coincidencia STT (cualquier frase, requiere Whisper local)","custom_onnx": "Modelo ONNX personalizado"},diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 38cc98f174..4450eed925 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -486,6 +486,8 @@ async def put_wake_word(body: WakeWordBody, request: Request) -> dict[str, objec# Preview the resolved plan so the UI can tell the user immediately whether# the chosen phrase will work as-is or degrade (e.g. no local Whisper).+ _cfg_for_lang = _config(request)+ _stt_lang = getattr(getattr(_cfg_for_lang, "stt", None), "language", None)plan = resolve_wake_plan(SimpleNamespace(phrase=body.phrase,@@ -495,6 +497,8 @@ async def put_wake_word(body: WakeWordBody, request: Request) -> dict[str, objecfuzzy_match_ratio=body.fuzzy_match_ratio,),local_whisper_available=_local_whisper_available(),+ # Per-language Vosk model lookup for the any-word vosk_kws engine.+ language=_stt_lang,)# Best-effort in-memory cfg update so a later cfg read agrees pre-restart.diff --git a/pyproject.toml b/pyproject.tomlindex 8c824c605f..ca8702a512 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -38,6 +38,13 @@ dependencies = [# proven. Both are lazy-imported in openwakeword_provider.py."openwakeword>=0.6","onnxruntime>=1.17", # CPU-only; pinned explicitly though openwakeword pulls it+ # Any-word wake keyword spotting (vosk_kws engine, design spec 2026-07-05):+ # Vosk is Apache-2.0, torch-free, ~7 MB wheel with bundled libvosk, official+ # CPU wheels for win/mac/manylinux x86+ARM — the identical-on-every-OS+ # detector for a freely chosen wake phrase. The per-language model (~45 MB)+ # is fetched once at setup into data/wake_models/vosk/<lang>/, NOT bundled.+ # Lazy-imported in vosk_kws_provider.py; base `import jarvis` stays clean.+ "vosk>=0.3.45",# Local VAD (silero-vad, which pulls torch), webrtcvad, the Porcupine wake# engine (pvporcupine) and the local-Whisper arbitrary-phrase path stay in the# [local-voice] extra per the cloud-first doctrine (CLAUDE.md): the defaultdiff --git a/requirements.in b/requirements.inindex 0a02d5d76f..b3600581c1 100644--- a/requirements.in+++ b/requirements.in@@ -47,6 +47,10 @@ scipy>=1.14# are). See pyproject.toml note.openwakeword>=0.6onnxruntime>=1.17+# Any-word wake keyword spotting (vosk_kws engine, 2026-07-05): torch-free,+# Apache-2.0, universal CPU wheels; per-language model fetched at setup, not+# bundled. See pyproject.toml note.+vosk>=0.3.45# Local VAD (silero-vad → torch), webrtcvad-wheels and the Porcupine wake engine# (pvporcupine) are NOT base deps: they live in the pyproject.toml [local-voice]# extra per the cloud-first doctrine (CLAUDE.md §3). torch must never land in thediff --git a/requirements.txt b/requirements.txtindex 76044eb20b..32850f7876 100644--- a/requirements.txt+++ b/requirements.txt@@ -263,6 +263,7 @@ cffi==2.0.0 \# brotlicffi# cryptography# sounddevice+ # voskcharset-normalizer==3.4.7 \--hash=sha256:007d05ec7321d12a40227aae9e2bc6dca73f3cb21058999a1df9e193555a9dcc \--hash=sha256:03853ed82eeebbce3c2abfdbc98c96dc205f32a79627688ac9a27370ea61a49c \@@ -1704,6 +1705,7 @@ requests==2.34.2 \# google-auth# google-genai# openwakeword+ # voskrich==15.0.0 \--hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \--hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36@@ -2010,6 +2012,9 @@ sounddevice==0.5.5 \--hash=sha256:3861901ddd8230d2e0e8ae62ac320cdd4c688d81df89da036dcb812f757bb3e6 \--hash=sha256:cfc6b2c49fb7f555591c78cb8ecf48d6a637fd5b6e1db5fec6ed9365d64b3519# via -r requirements.in+srt==3.5.3 \+ --hash=sha256:4884315043a4f0740fd1f878ed6caa376ac06d70e135f306a6dc44632eed0cc0+ # via vosksse-starlette==3.4.5 \--hash=sha256:83072538bc211a2f68b7b0422226c4af3e9b62e106e07034664b832ca019842a \--hash=sha256:e71bad53323f65573c3864a6c3bd0c1eb6e5f092b2e48082b0c35927d19ca296@@ -2059,6 +2064,7 @@ tqdm==4.68.3 \# via# openai# openwakeword+ # vosktyper==0.26.8 \--hash=sha256:3512ca79ac5c11113414b36e80281b872884477722440691c89d1112e321a49c \--hash=sha256:c244a6bd558886fe3f8780efb6bdd28bb9aff005a94eedebaa5cb32926fe2f7e@@ -2152,6 +2158,12 @@ uvloop==0.22.1 ; platform_python_implementation != 'PyPy' and sys_platform != 'c--hash=sha256:ef6f0d4cc8a9fa1f6a910230cd53545d9a14479311e87e3cb225495952eb672c \--hash=sha256:fe94b4564e865d968414598eea1a6de60adba0c040ba4ed05ac1300de402cd42# via uvicorn+vosk==0.3.45 \+ --hash=sha256:25e025093c4399d7278f543568ed8cc5460ac3a4bf48c23673ace1e25d26619f \+ --hash=sha256:4221f83287eefe5abbe54fc6f1da5774e9e3ffcbbdca1705a466b341093b072e \+ --hash=sha256:54efb47dd890e544e9e20f0316413acec7f8680d04ec095c6140ab4e70262704 \+ --hash=sha256:6994ddc68556c7e5730c3b6f6bad13320e3519b13ce3ed2aa25a86724e7c10ac+ # via -r requirements.inwatchdog==6.0.0 \--hash=sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a \--hash=sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2 \@@ -2360,6 +2372,7 @@ websockets==16.0 \# elevenlabs# google-genai# uvicorn+ # voskwin32-setctime==1.2.0 ; sys_platform == 'win32' \--hash=sha256:95d644c4e708aba81dc3704a116d8cbc974d70b3bdb8be1d150e36be6e9d1390 \--hash=sha256:ae1fdf948f5640aae05c511ade119313fb6a30d7eabe25fef9764dca5873c4c0diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.pynew file mode 100644index 0000000000..a4d3c5bc98--- /dev/null+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py@@ -0,0 +1,199 @@+"""The any-word Vosk grammar KWS provider: confirm contract, gates, firing.++CI has no vosk model (and often no vosk wheel), so a fake ``vosk`` module is+injected into ``sys.modules``; the provider's lazy in-method imports pick it+up. What is pinned here:++- ``sound_confirm`` is PERMISSIVE (AP-27): a sound-close mis-hearing ("hey+ room" for "Hey Ruben") passes, unrelated speech ("vielen dank") and an+ empty free transcript are rejected. # i18n-allow: German utterance under test+- A grammar partial hit fires the keyword only after the free-decode confirm.+- Near-silent candidates are rejected on raw ENERGY (never transcript).+- A confirm infrastructure error fails OPEN (never eats a real wake).+- The wake detector yields the canonical keyword, never transcript text.+"""+from __future__ import annotations++import asyncio+import json+import sys+import types+from collections.abc import AsyncIterator++import numpy as np+import pytest++from jarvis.core.protocols import AudioChunk+from jarvis.plugins.wake.vosk_kws_provider import VoskKwsProvider, sound_confirm++# --- sound_confirm ------------------------------------------------------------+++def test_sound_confirm_accepts_sound_close_mishearing() -> None:+ assert sound_confirm("hey room", "Hey Ruben") is True+ assert sound_confirm("hey ruben", "Hey Ruben") is True+++def test_sound_confirm_rejects_unrelated_speech() -> None:+ assert sound_confirm("vielen dank", "Hey Ruben") is False # i18n-allow: utterance under test+++def test_sound_confirm_rejects_empty_free_transcript() -> None:+ # The free ear heard NOTHING — the grammar hit was noise, not speech.+ assert sound_confirm("", "Hey Ruben") is False+++def test_sound_confirm_finds_phrase_inside_longer_speech() -> None:+ # i18n-allow: German utterance under test+ assert sound_confirm("ich sagte hey ruben gerade eben", "Hey Ruben") is True+++# --- fake vosk runtime ----------------------------------------------------------+++class _FakeRecognizer:+ """Scriptable KaldiRecognizer stand-in.++ Grammar mode (grammar arg passed): after ``fire_after`` chunks the partial+ contains the phrase. Free mode (no grammar): FinalResult returns+ ``free_text`` — the knob the confirm-path tests turn.+ """++ def __init__(self, model, rate, grammar=None): # noqa: ANN001+ self._model = model+ self._grammar = grammar+ self._chunks = 0++ def SetWords(self, flag): # noqa: ANN001, N802+ pass++ def AcceptWaveform(self, pcm): # noqa: ANN001, N802+ self._chunks += 1+ return False # partial path only — finals are exercised via partials++ def PartialResult(self): # noqa: N802+ if self._grammar is not None and self._chunks >= self._model.fire_after:+ return json.dumps({"partial": self._model.phrase.lower()})+ return json.dumps({"partial": ""})++ def Result(self): # noqa: N802+ return json.dumps({"text": ""})++ def FinalResult(self): # noqa: N802+ return json.dumps({"text": self._model.free_text})+++class _FakeModel:+ def __init__(self, path): # noqa: ANN001+ self.path = path+ self.phrase = "hey nova"+ self.free_text = "hey nova"+ self.fire_after = 3+++def fake_vosk(monkeypatch):+ mod = types.ModuleType("vosk")+ state = {"model": None}++ def _model_factory(path): # noqa: ANN001+ state["model"] = _FakeModel(path)+ return state["model"]++ mod.Model = _model_factory+ mod.KaldiRecognizer = _FakeRecognizer+ mod.SetLogLevel = lambda *_a: None+ monkeypatch.setitem(sys.modules, "vosk", mod)+ return state+++def _chunk(value: int = 6000, n: int = 1600) -> AudioChunk:+ arr = np.full(n, value, dtype=np.int16)+ return AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0)+++def _silent_chunk(n: int = 1600) -> AudioChunk:+ return AudioChunk(pcm=b"\x00\x00" * n, sample_rate=16000, timestamp_ns=0)+++async def _run_detect(provider: VoskKwsProvider, chunks: list[AudioChunk]) -> list[str]:+ async def _iter() -> AsyncIterator[AudioChunk]:+ for c in chunks:+ yield c++ fired: list[str] = []++ async def _drive() -> None:+ async for kw in provider.detect(_iter()):+ fired.append(kw)++ await asyncio.wait_for(_drive(), timeout=5.0)+ return fired+++# --- detection loop -------------------------------------------------------------+++async def test_partial_hit_with_confirm_fires_the_keyword(fake_vosk) -> None:+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova")+ fired = await _run_detect(p, [_chunk() for _ in range(6)])+ assert fired == ["nova"]+ assert p.stats()["fired"] == 1+++async def test_confirm_rejection_suppresses_the_fire(fake_vosk) -> None:+ # The free ear hears unrelated speech — grammar pulled noise onto the phrase.+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova")+ fake_vosk_model_free_text = "das ist etwas ganz anderes" # i18n-allow: utterance under test+ # model instance is created lazily inside detect; patch via the factory state+ fired: list[str] = []++ async def _late_set() -> None:+ # wait until the model exists, then set its free text before the hit+ for _ in range(50):+ if fake_vosk["model"] is not None:+ fake_vosk["model"].free_text = fake_vosk_model_free_text+ return+ await asyncio.sleep(0.01)++ async def _drive() -> None:+ async def _iter() -> AsyncIterator[AudioChunk]:+ for _ in range(6):+ await asyncio.sleep(0.005)+ yield _chunk()++ async for kw in p.detect(_iter()):+ fired.append(kw)++ await asyncio.wait_for(asyncio.gather(_late_set(), _drive()), timeout=5.0)+ assert fired == []+ assert p.stats()["suppressed_confirm"] >= 1+++async def test_near_silent_candidate_is_gated_on_energy(fake_vosk) -> None:+ # AP-27: silence suppression happens on raw RMS at the match site — even+ # though the fake grammar "hears" the phrase, an all-zero window must gate.+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova")+ fired = await _run_detect(p, [_silent_chunk() for _ in range(6)])+ assert fired == []+ assert p.stats()["gated_rms"] >= 1+++def test_confirm_infrastructure_error_fails_open(fake_vosk, monkeypatch) -> None:+ # A broken confirm must never eat a real wake (mirrors the echo-confirm+ # contract on the stt_match path): _free_confirm returns True on ANY+ # infrastructure exception.+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova")++ def _boom():+ raise RuntimeError("confirm infra down")++ monkeypatch.setattr(p, "_ensure_model", _boom)+ assert p._free_confirm(np.full(1600, 0.2, dtype=np.float32)) is True+++async def test_cooldown_suppresses_immediate_refire(fake_vosk) -> None:+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova", cooldown_s=60.0)+ fired = await _run_detect(p, [_chunk() for _ in range(14)])+ assert fired == ["nova"] # second grammar hit lands inside the cooldown+ assert p.stats()["suppressed_cooldown"] >= 1diff --git a/tests/unit/speech/test_wake_custom_model.py b/tests/unit/speech/test_wake_custom_model.pyindex 42cdeb9a4e..3dbae9d6d1 100644--- a/tests/unit/speech/test_wake_custom_model.py+++ b/tests/unit/speech/test_wake_custom_model.py@@ -13,6 +13,18 @@ from __future__ import annotationsfrom types import SimpleNamespace+import pytest++[email protected](autouse=True)+def _no_vosk_model(monkeypatch):+ """Isolate from any per-install Vosk model: this module pins the custom_onnx+ vs stt_match/none chain. The vosk_kws chain has its own suite in+ test_wake_plan_vosk.py."""+ import jarvis.speech.wake_phrase as wp++ monkeypatch.setattr(wp, "resolve_vosk_model_path", lambda *_: None)+def _cfg(model_path: str,diff --git a/tests/unit/speech/test_wake_dead_state.py b/tests/unit/speech/test_wake_dead_state.pyindex b6b2b01fcc..2a2e4bd6fa 100644--- a/tests/unit/speech/test_wake_dead_state.py+++ b/tests/unit/speech/test_wake_dead_state.py@@ -21,10 +21,22 @@ from __future__ import annotationsimport asynciofrom types import SimpleNamespace+import pytest+from jarvis.speech.pipeline import PipelineState, SpeechPipelinefrom jarvis.speech.wake_phrase import resolve_wake_plan[email protected](autouse=True)+def _no_vosk_model(monkeypatch):+ """Isolate from any per-install Vosk model: this module pins the+ stt_match/none dead-state contracts. vosk_kws has its own suite in+ test_wake_plan_vosk.py."""+ import jarvis.speech.wake_phrase as wp++ monkeypatch.setattr(wp, "resolve_vosk_model_path", lambda *_: None)++def _cfg(**kw: object) -> SimpleNamespace:base = dict(phrase="Neko",diff --git a/tests/unit/speech/test_wake_live_apply.py b/tests/unit/speech/test_wake_live_apply.pyindex 49cd9426a7..188eeb0cf8 100644--- a/tests/unit/speech/test_wake_live_apply.py+++ b/tests/unit/speech/test_wake_live_apply.py@@ -21,6 +21,14 @@ from jarvis.speech.pipeline import SpeechPipelinefrom jarvis.speech.wake_phrase import resolve_wake_plan[email protected](autouse=True)+def _no_vosk_model(monkeypatch):+ """Isolate from any per-install Vosk model: this module pins the+ stt_match/openwakeword live-apply contracts. vosk_kws has its own suite+ in test_wake_plan_vosk.py."""+ monkeypatch.setattr(wp, "resolve_vosk_model_path", lambda *_: None)++@dataclassclass _FakeTTS:name: str = "fake-tts"diff --git a/tests/unit/speech/test_wake_phrase.py b/tests/unit/speech/test_wake_phrase.pyindex 738a6885a5..6ece57e235 100644--- a/tests/unit/speech/test_wake_phrase.py+++ b/tests/unit/speech/test_wake_phrase.py@@ -23,12 +23,23 @@ from jarvis.speech.wake_phrase import (sensitivity_to_threshold,)+[email protected](autouse=True)+def _no_vosk_model(monkeypatch):+ """Isolate from any per-install Vosk model: this module pins the NON-vosk+ resolution chain (stt_match / none). The vosk_kws chain has its own+ dedicated suite in test_wake_plan_vosk.py."""+ monkeypatch.setattr(wp, "resolve_vosk_model_path", lambda *_: None)++# --------------------------------------------------------------------------# WAKE_ENGINES single source of truth# ---------------------------------------------------------------------------def test_wake_engines_are_the_four_canonical_engines() -> None:- assert wc.WAKE_ENGINES == ("auto", "openwakeword", "stt_match", "custom_onnx")+def test_wake_engines_are_the_five_canonical_engines() -> None:+ assert wc.WAKE_ENGINES == (+ "auto", "openwakeword", "vosk_kws", "stt_match", "custom_onnx"+ )def test_default_wake_phrase_is_empty() -> None:diff --git a/tests/unit/speech/test_wake_plan_vosk.py b/tests/unit/speech/test_wake_plan_vosk.pynew file mode 100644index 0000000000..76c97f380c--- /dev/null+++ b/tests/unit/speech/test_wake_plan_vosk.py@@ -0,0 +1,127 @@+"""resolve_wake_plan: the any-word vosk_kws engine slots into the chain.++Chain contract (design spec 2026-07-05): custom_onnx (matching file) →+pretrained OWW (known phrase) → **vosk_kws (any phrase, per-language model)**+→ stt_match (fallback) → none/hotkey. vosk_kws must never require local+Whisper, and a missing vosk package or model falls through gracefully.+"""+from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.speech.wake_constants import resolve_vosk_model_path+from jarvis.speech.wake_phrase import resolve_wake_plan+++def _cfg(phrase: str = "Hey Nova", engine: str = "auto", custom: str = "") -> SimpleNamespace:+ return SimpleNamespace(+ phrase=phrase,+ engine=engine,+ custom_model_path=custom,+ sensitivity=0.5,+ fuzzy_match_ratio=0.8,+ )+++def vosk_model_dir(tmp_path, monkeypatch) -> Path:+ """A minimal on-disk layout resolve_vosk_model_path accepts (am/ subdir)."""+ monkeypatch.setenv("JARVIS__MEMORY__DATA_DIR", str(tmp_path))+ model = tmp_path / "wake_models" / "vosk" / "de" / "vosk-model-small-de-0.15"+ (model / "am").mkdir(parents=True)+ return model+++def test_resolve_vosk_model_path_finds_language_and_auto(vosk_model_dir) -> None:+ assert resolve_vosk_model_path("de") == str(vosk_model_dir)+ assert resolve_vosk_model_path("de-DE") == str(vosk_model_dir)+ # auto/None fall back to the first installed language folder+ assert resolve_vosk_model_path("auto") == str(vosk_model_dir)+ assert resolve_vosk_model_path(None) == str(vosk_model_dir)+ # a language without a model resolves to nothing+ assert resolve_vosk_model_path("es") is None+++def test_auto_picks_vosk_for_arbitrary_phrase(vosk_model_dir) -> None:+ plan = resolve_wake_plan(+ _cfg(), local_whisper_available=True, language="de", vosk_available=True+ )+ assert plan.engine == "vosk_kws"+ assert plan.vosk_model_path == str(vosk_model_dir)+ assert plan.needs_local_whisper is False+ assert plan.wake_available is True+ assert plan.verify_prefix is False # the provider's own confirm handles it+++def test_known_pretrained_phrase_keeps_openwakeword(vosk_model_dir) -> None:+ # "Hey Jarvis" has a bundled instant OWW model — vosk must not hijack it.+ plan = resolve_wake_plan(+ _cfg(phrase="Hey Jarvis"),+ local_whisper_available=True,+ language="de",+ vosk_available=True,+ )+ assert plan.engine == "openwakeword"+++def test_explicit_vosk_engine_forces_vosk(vosk_model_dir) -> None:+ plan = resolve_wake_plan(+ _cfg(phrase="Hey Jarvis", engine="vosk_kws"),+ local_whisper_available=True,+ language="de",+ vosk_available=True,+ )+ assert plan.engine == "vosk_kws"+++def test_no_vosk_package_falls_back_to_stt_match(vosk_model_dir) -> None:+ plan = resolve_wake_plan(+ _cfg(), local_whisper_available=True, language="de", vosk_available=False+ )+ assert plan.engine == "stt_match"+++def test_no_model_for_language_falls_back_to_stt_match(vosk_model_dir) -> None:+ plan = resolve_wake_plan(+ _cfg(), local_whisper_available=True, language="es", vosk_available=True+ )+ assert plan.engine == "stt_match"+++def test_stale_custom_model_resolves_to_vosk(vosk_model_dir, tmp_path) -> None:+ # A leftover hey_nico.onnx must not keep the NEW phrase on the weak path.+ stale = tmp_path / "hey_nico.onnx"+ stale.write_bytes(b"onnx")+ plan = resolve_wake_plan(+ _cfg(custom=str(stale)),+ local_whisper_available=True,+ language="de",+ vosk_available=True,+ )+ assert plan.engine == "vosk_kws"+++def test_matching_custom_model_still_wins(vosk_model_dir, tmp_path) -> None:+ own = tmp_path / "hey_nova.onnx"+ own.write_bytes(b"onnx")+ plan = resolve_wake_plan(+ _cfg(custom=str(own)),+ local_whisper_available=True,+ language="de",+ vosk_available=True,+ )+ assert plan.engine == "custom_onnx"+++def test_no_vosk_no_whisper_is_honest_wake_off(vosk_model_dir) -> None:+ plan = resolve_wake_plan(+ _cfg(),+ local_whisper_available=False,+ language="es", # no model for es in the fixture+ vosk_available=True,+ )+ assert plan.engine == "none"+ assert plan.wake_available is False