Skip to content

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

fix(wake): language-aware CPU wake routing + auto-provision + UI language/self-test

Harald2e025786dcd0
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index e0f394de4d..fbc704840c 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -303,10 +303,22 @@ class STTConfig(BaseModel):
# cached per ctranslate2 version — ``jarvis.plugins.stt.
# _wake_gpu_inference_verified``), plus a live backstop that drops back to
# base/cpu and persists the bad verdict if the swapped-in GPU model ever
- # wedges. False remains the hard opt-out (never try the GPU). The
- # transcription wake still cannot reach "Hey Google" reliability — that
- # needs a trained neural keyword-spotting model (the ``custom_onnx`` engine).
- wake_high_accuracy: bool = True
+ # wedges. The transcription wake still cannot reach "Hey Google" reliability
+ # — that needs a trained neural keyword-spotting model (``custom_onnx``).
+ #
+ # DEFAULT FLIPPED TO CPU (2026-07-09): the GPU hot-swap is now OFF by
+ # default and this flag is the COMPLETE CPU↔GPU switch for the wake path
+ # (it gates BOTH the plain and the custom-phrase turbo/cuda branch in
+ # build_wake_whisper AND the background hot-swap). Rationale: the GPU wake
+ # relied on two sticky, never-re-probed caches (data/wake_cuda_probe.json,
+ # data/wake_gpu_probe.json) — a single transient first-probe failure latched
+ # the wake to the wedge-prone base/cpu model across EVERY future restart with
+ # no log explaining why ("worked fast, then dead after a reboot"). A
+ # CPU-first wake is the universal, reproducible floor (matches §3's
+ # torch-/GPU-free base). Power users can still opt in with
+ # ``wake_high_accuracy = true`` (the automated inference probe + live backstop
+ # still guard it). The always-on vosk_kws engine is CPU-only regardless.
+ wake_high_accuracy: bool = False
language: str = "auto"
# Vocabulary biasing passed to Whisper's ``prompt`` field — the same
# mechanism dictation tools like a dictation app use to keep proper nouns and
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index a2162168d0..d6b7d472c1 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -667,6 +667,7 @@ def build_wake_whisper(
and model == "base"
and device == "cpu"
and cuda_available
+ and bool(getattr(stt_cfg, "wake_high_accuracy", False))
and _wake_gpu_inference_verified()
):
model, device, compute = "large-v3-turbo", "cuda", "int8_float16"
@@ -681,7 +682,7 @@ def build_wake_whisper(
and model == "base"
and device == "cpu"
and cuda_available
- and bool(getattr(stt_cfg, "wake_high_accuracy", True))
+ and bool(getattr(stt_cfg, "wake_high_accuracy", False))
and _wake_gpu_inference_verified()
):
# CUSTOM WAKE PHRASE on a CUDA box: upgrade to the strong turbo model on
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index fe162b9d9b..0719f1a225 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -47,7 +47,11 @@ from typing import Any
import numpy as np
from jarvis.core.protocols import AudioChunk
-from jarvis.speech.wake_constants import normalize_phrase_for_match, sound_fold
+from jarvis.speech.wake_constants import (
+ normalize_phrase_for_match,
+ phrase_core_for_match,
+ sound_fold,
+)
log = logging.getLogger("jarvis.wake.vosk")
@@ -427,4 +431,49 @@ class VoskKwsProvider:
rec = self._new_grammar_rec()
-__all__ = ["VoskKwsProvider", "sound_confirm"]
+def vosk_model_supports_phrase(model_path: str, phrase: str) -> bool:
+ """True when every core word of ``phrase`` exists in the model lexicon.
+
+ Vosk drops out-of-vocabulary grammar words with a stderr warning and then
+ silently builds a grammar WITHOUT them (live 2026-07-08: 'Hey Billionar'
+ → "Ignoring word missing in vocabulary: 'billionar'" → the phrase could
+ never be heard, and ``SetLogLevel(-1)`` hid the warning). The small models
+ ship no readable word list, so the warning is the only signal — capture it
+ at the OS fd level (portable on Windows and POSIX) around a throwaway
+ recognizer build. NEVER raises: any failure means "cannot prove it's
+ unsupported" → returns True (fail-open, never eat a usable wake word). This
+ is DELIBERATELY off the boot path (it loads the model, ~1.5 s) — call it
+ from a user action (self-test) or a background task, never in ``_run_backend``.
+ """
+ core = phrase_core_for_match(phrase)
+ if not core:
+ return False
+ import contextlib
+ import os
+ import tempfile
+
+ try:
+ from vosk import KaldiRecognizer, Model, SetLogLevel
+ except Exception: # noqa: BLE001 — no vosk → cannot disprove support
+ return True
+ tmp = None
+ old = None
+ try:
+ SetLogLevel(0) # surface the OOV warning the app normally hides
+ tmp = tempfile.TemporaryFile(mode="w+")
+ old = os.dup(2)
+ os.dup2(tmp.fileno(), 2)
+ KaldiRecognizer(Model(model_path), 16_000, json.dumps([phrase.lower(), "[unk]"]))
+ except Exception: # noqa: BLE001 — probe failure must not reject a real word
+ return True
+ finally:
+ if old is not None:
+ with contextlib.suppress(Exception):
+ os.dup2(old, 2)
+ os.close(old)
+ SetLogLevel(-1) # restore the app's quiet default
+ tmp.seek(0)
+ return "missing in vocabulary" not in tmp.read().lower()
+
+
+__all__ = ["VoskKwsProvider", "sound_confirm", "vosk_model_supports_phrase"]
diff --git a/jarvis/speech/wake_phrase.py b/jarvis/speech/wake_phrase.py
index 37d10776d5..142fb65d4c 100644
--- a/jarvis/speech/wake_phrase.py
+++ b/jarvis/speech/wake_phrase.py
@@ -409,16 +409,45 @@ def resolve_wake_plan(
# everywhere engine (design spec 2026-07-05): per-language model, CPU-only,
# no training, no cloud, no GPU; spike-measured 79-100 % recall at
# 1/0/0 % false accepts where the transcription path is machine- and
- # word-dependent. Chosen on "auto" for any phrase, or forced via
- # engine="vosk_kws". Requires the vosk package (base dep) AND a
- # per-language model directory; missing either falls through to the
- # stt_match chain below (graceful, message says why).
+ # word-dependent. Requires the vosk package (base dep) AND a per-language
+ # model directory; missing either falls through to the stt_match chain
+ # below (graceful, message says why).
+ #
+ # LANGUAGE-AWARE (2026-07-09): a Vosk model is acoustically language-SPECIFIC
+ # — an English model cannot hear a German-spoken name even when the word is
+ # in its lexicon (live: 'Hey Ruben' spoken de on the en model free-decoded to
+ # 'hey of whom' and EVERY verify suppressed → a silent dead listener). So
+ # vosk_kws is trusted only when its language provably matches the speaker:
+ # (a) engine explicitly forced, or (b) a CONCRETE language is resolved and a
+ # model for THAT language exists. Under an ambiguous "auto" language we do NOT
+ # gamble on the first-installed model — we prefer the multilingual,
+ # open-vocabulary stt_match path whenever local Whisper is available (it
+ # transcribes ANY word in ANY language). Callers pass a concrete language via
+ # wake_model_fetch.resolve_wake_language(cfg); "auto"/None only survives here
+ # from legacy call sites, and then vosk is a best-effort last resort on a box
+ # with no local Whisper.
+ lang_norm = (language or "auto").strip().lower().split("-")[0]
+ lang_is_concrete = bool(lang_norm) and lang_norm != "auto"
+ vosk_model = None
if phrase and engine_pref in ("auto", "vosk_kws"):
if vosk_available is None:
import importlib.util as _ilu
vosk_available = _ilu.find_spec("vosk") is not None
- vosk_model = resolve_vosk_model_path(language) if vosk_available else None
+ if vosk_available:
+ if engine_pref == "vosk_kws":
+ # Explicit force: honour the user's choice, any installed model.
+ vosk_model = resolve_vosk_model_path(language)
+ elif lang_is_concrete:
+ # auto engine + a concrete language: trust vosk only for a model
+ # in exactly that language (never a mismatched fallback).
+ vosk_model = resolve_vosk_model_path(lang_norm)
+ elif not local_whisper_available:
+ # auto engine + ambiguous language + NO multilingual Whisper:
+ # vosk (first-installed) is the only local option — best effort.
+ vosk_model = resolve_vosk_model_path(language)
+ # else: auto + ambiguous language + Whisper present → fall through to
+ # the multilingual stt_match path below (the universal answer).
if vosk_model is not None and (
engine_pref == "vosk_kws"
or not custom_path
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index efa97154d5..6673d1e180 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -1756,9 +1756,41 @@ class DesktopApp:
from jarvis.core.config import load_config
from jarvis.speech import wake_model_fetch as _wmf
- lang = _wmf.resolve_wake_language(load_config())
- if not _wmf.vosk_model_present(lang):
- await asyncio.to_thread(_wmf.ensure_vosk_model, lang)
+ cfg = load_config()
+ lang = _wmf.resolve_wake_language(cfg)
+ if _wmf.vosk_model_present(lang):
+ return
+ landed = await asyncio.to_thread(_wmf.ensure_vosk_model, lang)
+ if landed is None:
+ return
+ # The matching-language model just landed. Re-resolve the
+ # wake plan and live-switch the running detector to
+ # vosk_kws so the user's word works immediately — no
+ # restart (mirrors the settings PUT live-apply). A
+ # headless/absent pipeline just means it applies on the
+ # next voice start.
+ import importlib.util as _ilu
+
+ from jarvis.core.runtime_refs import get_speech_pipeline
+ from jarvis.speech.wake_phrase import resolve_wake_plan
+
+ pipeline = get_speech_pipeline()
+ if pipeline is not None and hasattr(pipeline, "set_wake_plan"):
+ plan = resolve_wake_plan(
+ cfg.trigger.wake_word,
+ local_whisper_available=(
+ _ilu.find_spec("faster_whisper") is not None
+ ),
+ language=lang,
+ )
+ if plan.engine == "vosk_kws":
+ pipeline.set_wake_plan(plan)
+ from loguru import logger as _wmf_ok
+ _wmf_ok.info(
+ "Wake model for '{}' provisioned off-boot; "
+ "live-switched detector to vosk_kws.",
+ lang,
+ )
except Exception: # noqa: BLE001 — a background probe never crashes boot
from loguru import logger as _wmf_log
_wmf_log.opt(exception=True).debug(
@@ -2290,15 +2322,21 @@ class DesktopApp:
# See docs/local-wakeword/CUSTOM-WAKE-WORD-DESIGN.md.
import importlib.util as _ilu
+ from jarvis.speech.wake_model_fetch import resolve_wake_language
from jarvis.speech.wake_phrase import resolve_wake_plan
_local_whisper_available = _ilu.find_spec("faster_whisper") is not None
+ # CONCRETE wake language (stt.language → ui.language → default), never
+ # raw "auto": a Vosk model is acoustically language-specific, so the
+ # any-word vosk_kws engine must resolve against the language the user
+ # actually speaks — not the first-installed model. The same resolver
+ # drives the model DOWNLOAD (wake_model_fetch) so selection and
+ # provisioning can never disagree.
+ _wake_language = resolve_wake_language(self.cfg)
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,
+ language=_wake_language,
)
from loguru import logger as _wlog
if not wake_plan.wake_available:
@@ -2665,7 +2703,15 @@ class DesktopApp:
# inference, so a custom phrase comes up fast AND stays accurate. No-op
# on a CPU-only host (the build returns base again). Any failure leaves
# the working base/cpu model in place — wake never breaks.
- if _wake_progressive_upgrade:
+ # CPU-first default (2026-07-09): the background turbo/cuda hot-swap
+ # only runs when the user explicitly opted into GPU wake
+ # (``[stt].wake_high_accuracy = true``). With the CPU default the
+ # rebuild below would just return base and no-op, so skip it entirely
+ # — that also avoids the sticky wake_cuda/gpu_probe caches that made a
+ # once-fast GPU wake go permanently deaf after a restart.
+ if _wake_progressive_upgrade and bool(
+ getattr(self.cfg.stt, "wake_high_accuracy", False)
+ ):
_wake_phrase_for_upgrade = wake_phrase
_stt_lang_for_upgrade = stt_language
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 562e35934e..bcc63ac78a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1069,6 +1069,10 @@
"activation_saved": "Aktivierung gespeichert — Neustart nötig, damit sie greift.",
"phrase_label": "Aktivierungsphrase",
"phrase_placeholder": "z. B. Jonas",
+ "language_label": "Sprache der Spracherkennung",
+ "language_hint": "Wähle die Sprache, in der du dein Wake-Word SPRICHST. Das lokale Modell muss dazu passen — ein englisches Modell kann einen deutsch gesprochenen Namen nicht hören; ein Sprach-Mismatch ist die häufigste Ursache für ein Wake-Word, das nie auslöst. \"Auto\" nutzt die Oberflächensprache.",
+ "self_test_button": "Wake-Word testen",
+ "self_test_running": "Prüfe …",
"engine_label": "Erkennungs-Engine",
"sensitivity_label": "Empfindlichkeit",
"sensitivity_floor_note": "Minimum ist 0,5: Darunter wird die Erkennung so streng, dass normale Sprechlautstärke praktisch nie auslöst — das wirkt kaputt statt \"weniger empfindlich\". 0,5 ist der ausbalancierte Standard; höhere Werte lösen leichter aus.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 0d149424c6..b1a4c23445 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1070,6 +1070,10 @@
"activation_saved": "Activation saved — restart to apply.",
"phrase_label": "Wake phrase",
"phrase_placeholder": "e.g. Jonas",
+ "language_label": "Voice recognition language",
+ "language_hint": "Pick the language you SPEAK your wake word in. The local model must match it — an English model cannot hear a German-spoken name, so a mismatch is the #1 cause of a wake word that never fires. \"Auto\" uses the interface language.",
+ "self_test_button": "Test wake word",
+ "self_test_running": "Checking…",
"engine_label": "Detection engine",
"sensitivity_label": "Sensitivity",
"sensitivity_floor_note": "Minimum is 0.5: below the calibrated midpoint the detector becomes so strict that normal speech practically never wakes it — that feels broken, not \"less sensitive\". 0.5 is the balanced default; higher values trigger more easily.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index d9203f6524..8ef4d95305 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1069,6 +1069,10 @@
"activation_saved": "Activación guardada — reinicia para aplicar.",
"phrase_label": "Frase de activación",
"phrase_placeholder": "p. ej. Jonas",
+ "language_label": "Idioma de reconocimiento de voz",
+ "language_hint": "Elige el idioma en el que PRONUNCIAS tu palabra de activación. El modelo local debe coincidir — un modelo en inglés no puede oír un nombre pronunciado en alemán; un desajuste es la causa nº 1 de una palabra de activación que nunca se activa. \"Auto\" usa el idioma de la interfaz.",
+ "self_test_button": "Probar palabra de activación",
+ "self_test_running": "Comprobando …",
"engine_label": "Motor de detección",
"sensitivity_label": "Sensibilidad",
"sensitivity_floor_note": "El mínimo es 0,5: por debajo del punto medio calibrado, la detección se vuelve tan estricta que el habla normal casi nunca la activa — parece rota, no \"menos sensible\". 0,5 es el valor equilibrado por defecto; valores más altos se activan con más facilidad.",
diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
index 4d4b65f341..f324f35bfb 100644
--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
@@ -39,7 +39,27 @@ import { detectKeyboardPlatform } from "@/views/settings/keyboardLayout";
import { deriveAssistantName } from "@/lib/deriveAssistantName";
import { WAKE_ENGINES, WAKE_ENGINE_I18N_KEY } from "@/constants/wakeEngines";
import { useEventStore } from "@/store/events";
-import { useT } from "@/i18n";
+import {
+ useT,
+ useSttLanguage,
+ setSttLanguage,
+ hydrateSttLanguage,
+ type SttLanguage,
+} from "@/i18n";
+
+const WAKE_STT_LANGUAGES: SttLanguage[] = ["auto", "en", "de", "es"];
+
+interface WakeSelfTestResult {
+ ok: boolean;
+ phrase: string;
+ engine: string;
+ language: string;
+ wake_available: boolean;
+ phrase_in_vocab: boolean | null;
+ mic_ok: boolean;
+ message: string;
+ hint: string;
+}
interface SettingRow {
icon: React.ComponentType<{ className?: string }>;
@@ -125,12 +145,23 @@ function WakeWordPanel() {
// wake phrase. Refetch the wake config on success so the hint clears.
const { status: installStatus, install } = useLocalSpeechInstall(refetch);
+ // The voice-recognition language IS the wake language: a Vosk model is
+ // acoustically language-specific, so the model must match the language the
+ // user speaks their wake word in. Reuses the existing STT-language machinery
+ // (same backend field the runtime wake plan resolves against) — surfaced here
+ // so the user can fix the #1 cause of a dead wake word without leaving the
+ // panel.
+ const sttLang = useSttLanguage();
const [phrase, setPhrase] = useState("");
const [engine, setEngine] = useState<string>("auto");
const [sensitivity, setSensitivity] = useState(0.5);
const [customModelPath, setCustomModelPath] = useState("");
const [saving, setSaving] = useState(false);
const [result, setResult] = useState<WakeWordSaveResult | null>(null);
+ const [selfTest, setSelfTest] = useState<{
+ state: "idle" | "running" | "done";
+ data: WakeSelfTestResult | null;
+ }>({ state: "idle", data: null });
// The activation master switch (product rule 2026-07-04): on = always-on wake
// word (needs a local model for the user's word), off = hotkey / push-to-talk.
const [enabled, setEnabled] = useState(false);
@@ -157,6 +188,11 @@ function WakeWordPanel() {
setEnabled(config.enabled ?? false);
}, [config]);
+ // Reflect the backend's persisted STT/wake language on open.
+ useEffect(() => {
+ void hydrateSttLanguage();
+ }, []);
+
async function onToggleActivation(next: boolean) {
setTogglingActivation(true);
setEnabled(next); // optimistic
@@ -254,6 +290,35 @@ function WakeWordPanel() {
}
}
+ // Readiness check for the "Test wake word" button — asks the backend whether
+ // the configured word will actually fire (right-language model armed, word in
+ // vocabulary, mic delivering signal) without a second mic stream. Never throws.
+ async function onSelfTest() {
+ setSelfTest({ state: "running", data: null });
+ try {
+ const res = await fetch("/api/settings/wake-word/self-test", {
+ method: "POST",
+ });
+ const data = (await res.json().catch(() => null)) as WakeSelfTestResult | null;
+ setSelfTest({ state: "done", data });
+ } catch (e) {
+ setSelfTest({
+ state: "done",
+ data: {
+ ok: false,
+ phrase,
+ engine,
+ language: sttLang,
+ wake_available: false,
+ phrase_in_vocab: null,
+ mic_ok: false,
+ message: (e as Error).message,
+ hint: "",
+ },
+ });
+ }
+ }
+
return (
<div className="rounded-lg border border-border bg-card/60 p-4">
<div className="flex items-start gap-3">
@@ -303,6 +368,28 @@ function WakeWordPanel() {
</p>
) : null}
+ {/* Voice-recognition language — the wake model must match the spoken
+ language (the #1 cause of a dead wake word). Bound to the shared
+ STT-language machinery, so it agrees with the runtime wake plan. */}
+ <label className="mt-4 block text-xs font-medium text-muted-foreground">
+ {t("settings_view.wake_word.language_label")}
+ </label>
+ <select
+ value={sttLang}
+ onChange={(e) => void setSttLanguage(e.target.value as SttLanguage)}
+ disabled={loading}
+ className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"
+ >
+ {WAKE_STT_LANGUAGES.map((code) => (
+ <option key={code} value={code}>
+ {t(`languages_view.options.${code}.label`)}
+ </option>
+ ))}
+ </select>
+ <p className="mt-1 text-[11px] leading-snug text-muted-foreground">
+ {t("settings_view.wake_word.language_hint")}
+ </p>
+
{/* Engine select */}
<label className="mt-4 block text-xs font-medium text-muted-foreground">
{t("settings_view.wake_word.engine_label")}
@@ -411,7 +498,7 @@ function WakeWordPanel() {
</div>
)}
- {/* Save button */}
+ {/* Save + Test buttons */}
<div className="mt-4 flex items-center gap-3">
<Button
size="sm"
@@ -422,8 +509,45 @@ function WakeWordPanel() {
? t("settings_view.saving")
: t("settings_view.wake_word.save")}
</Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void onSelfTest()}
+ disabled={selfTest.state === "running" || loading || !trimmedPhrase}
+ >
+ {selfTest.state === "running" ? (
+ <span className="flex items-center gap-2">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t("settings_view.wake_word.self_test_running")}
+ </span>
+ ) : (
+ t("settings_view.wake_word.self_test_button")
+ )}
+ </Button>
</div>
+ {/* Self-test result — honest readiness verdict (engine + language +
+ vocabulary + mic), the fast way to see WHY a word won't wake. */}
+ {selfTest.state === "done" && selfTest.data && (
+ <div
+ className={`mt-3 rounded-md border p-3 text-xs ${
+ selfTest.data.ok
+ ? "border-primary/40 bg-primary/10 text-foreground"
+ : "border-amber-500/40 bg-amber-500/10 text-amber-500"
+ }`}
+ >
+ <p>{selfTest.data.message}</p>
+ {selfTest.data.hint && (
+ <p className="mt-1 text-muted-foreground">{selfTest.data.hint}</p>
+ )}
+ <p className="mt-1 font-mono text-muted-foreground">
+ engine: {selfTest.data.engine} · language: {selfTest.data.language}
+ {selfTest.data.phrase_in_vocab === false ? " · not in vocabulary" : ""}
+ {selfTest.data.mic_ok ? "" : " · mic quiet"}
+ </p>
+ </div>
+ )}
+
{/* Save result */}
{result && (
<div
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 6b0c9ddf48..54ff8955b3 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -576,8 +576,14 @@ 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).
+ # Use the SAME concrete language resolver the runtime wake plan and the model
+ # download use (stt.language → ui.language → default), never raw "auto" — a
+ # Vosk model is acoustically language-specific, so selection and provisioning
+ # must agree on the language.
+ from jarvis.speech.wake_model_fetch import resolve_wake_language
+
_cfg_for_lang = _config(request)
- _stt_lang = getattr(getattr(_cfg_for_lang, "stt", None), "language", None)
+ _wake_lang = resolve_wake_language(_cfg_for_lang)
plan = resolve_wake_plan(
SimpleNamespace(
phrase=body.phrase,
@@ -587,8 +593,7 @@ async def put_wake_word(body: WakeWordBody, request: Request) -> dict[str, objec
fuzzy_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,
+ language=_wake_lang,
)
# Best-effort in-memory cfg update so a later cfg read agrees pre-restart.
@@ -720,6 +725,95 @@ async def download_wake_model(request: Request) -> dict[str, object]:
}
[email protected]("/wake-word/self-test")
+async def wake_word_self_test(request: Request) -> dict[str, object]:
+ """Readiness check for the configured wake word — the "Test wake word" button.
+
+ Answers, honestly and without a second mic stream (which would fight the
+ running pipeline), the three questions that decide whether a spoken wake will
+ actually fire: (1) is the right-LANGUAGE local model armed, (2) is the word in
+ that model's vocabulary (the silent out-of-vocabulary drop, live 'Hey
+ Billionar'), and (3) is the mic delivering signal. Each is a reused building
+ block (``resolve_wake_plan`` preview, ``vosk_model_supports_phrase``,
+ ``measure_mic_dbfs``), so this route can never disagree with the runtime.
+ Never 500s. A green result plus a language-matched model is a real guarantee
+ the word will wake — the acoustic mismatch that a wrong-language model causes
+ is exactly what (1) surfaces.
+ """
+ from jarvis.speech.diagnose import measure_mic_dbfs
+ from jarvis.speech.wake_constants import resolve_vosk_model_path
+ from jarvis.speech.wake_model_fetch import resolve_wake_language
+ from jarvis.speech.wake_phrase import resolve_wake_plan
+
+ cfg = _config(request)
+ ww = getattr(cfg.trigger, "wake_word", None)
+ phrase = str(getattr(ww, "phrase", "") or "").strip()
+ language = resolve_wake_language(cfg)
+ plan = resolve_wake_plan(
+ ww,
+ local_whisper_available=_local_whisper_available(),
+ language=language,
+ )
+
+ # Vocabulary check only makes sense for the grammar (vosk_kws) engine.
+ phrase_in_vocab: bool | None = None
+ if plan.engine == "vosk_kws":
+ model_path = resolve_vosk_model_path(language)
+ if model_path:
+ try:
+ from jarvis.plugins.wake.vosk_kws_provider import (
+ vosk_model_supports_phrase,
+ )
+
+ phrase_in_vocab = await asyncio.to_thread(
+ vosk_model_supports_phrase, model_path, phrase
+ )
+ except Exception: # noqa: BLE001 — never fail the check on a probe hiccup
+ phrase_in_vocab = None
+
+ try:
+ max_dbfs = await measure_mic_dbfs(duration_s=2.0)
+ except Exception: # noqa: BLE001 — treat a failed measurement as no device
+ max_dbfs = -120.0
+ mic_ok = max_dbfs > -40.0
+ no_device = max_dbfs <= -119.9
+
+ # Human-readable verdict + the single most useful next step.
+ ok = bool(plan.wake_available) and phrase_in_vocab is not False and mic_ok
+ if not phrase:
+ message, hint = "No wake word set.", "Type a wake phrase first."
+ elif not plan.wake_available:
+ message, hint = plan.message, "Download the local model or use the hotkey."
+ elif phrase_in_vocab is False:
+ message = f"'{phrase}' is not in the {language} model's vocabulary."
+ hint = "Pick a real word of your language, or use a different phrase."
+ elif no_device:
+ message, hint = "No microphone detected.", "Connect/enable a mic."
+ elif not mic_ok:
+ message, hint = "Mic signal is very quiet.", "Speak louder or raise input gain."
+ else:
+ message = (
+ f"Ready: '{phrase}' on engine '{plan.engine}' "
+ f"(language '{language}'). Say it to wake."
+ )
+ hint = ""
+
+ return {
+ "ok": ok,
+ "phrase": phrase,
+ "engine": plan.engine,
+ "language": language,
+ "wake_available": bool(plan.wake_available),
+ "degraded": bool(plan.degraded),
+ "phrase_in_vocab": phrase_in_vocab,
+ "max_dbfs": max_dbfs,
+ "mic_ok": mic_ok,
+ "no_device": no_device,
+ "message": message,
+ "hint": hint,
+ }
+
+
@router.get("/wake-word/mic-level")
async def wake_mic_level() -> dict[str, object]:
"""Live mic dBFS for the onboarding wake step (Task 7: mic + spoken-word
diff --git a/tests/unit/speech/test_wake_language_aware.py b/tests/unit/speech/test_wake_language_aware.py
new file mode 100644
index 0000000000..2ee5557d60
--- /dev/null
+++ b/tests/unit/speech/test_wake_language_aware.py
@@ -0,0 +1,211 @@
+"""Language-aware wake routing: the fix for the cross-language deaf-wake class.
+
+A Vosk model is acoustically language-SPECIFIC — an English model cannot hear a
+German-spoken name even when the word is in its lexicon (live 2026-07-09:
+'Hey Ruben' spoken de on the en model free-decoded to 'hey of whom' and every
+verify suppressed). So ``resolve_wake_plan`` must trust vosk_kws ONLY when its
+language provably matches the speaker, and prefer the multilingual
+open-vocabulary stt_match path under an ambiguous "auto" language when local
+Whisper is available. These tests pin that contract so the regression cannot
+silently return.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.speech.wake_phrase import resolve_wake_plan
+
+
+def _cfg(phrase: str = "Hey Ruben", 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 de_model(tmp_path, monkeypatch) -> Path:
+ """Only a GERMAN vosk model on disk (mirrors the user's real box)."""
+ 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 en_model(tmp_path, monkeypatch) -> Path:
+ """Only an ENGLISH vosk model on disk."""
+ monkeypatch.setenv("JARVIS__MEMORY__DATA_DIR", str(tmp_path))
+ model = tmp_path / "wake_models" / "vosk" / "en" / "vosk-model-small-en-us-0.15"
+ (model / "am").mkdir(parents=True)
+ return model
+
+
+# --------------------------------------------------------------------------
+# The core regression: ambiguous language must NOT gamble on a mismatched model
+# --------------------------------------------------------------------------
+
+
[email protected]("language", ["auto", None])
+def test_ambiguous_language_with_whisper_prefers_multilingual_stt(en_model, language):
+ # engine=auto + language ambiguous + local Whisper present: the first-installed
+ # (en) model might not match the speaker, so DO NOT gamble on it — route to the
+ # multilingual open-vocabulary stt_match path instead.
+ plan = resolve_wake_plan(
+ _cfg(),
+ local_whisper_available=True,
+ language=language,
+ vosk_available=True,
+ )
+ assert plan.engine == "stt_match"
+ assert plan.wake_available is True
+
+
[email protected]("language", ["auto", None])
+def test_ambiguous_language_without_whisper_falls_back_to_vosk_best_effort(en_model, language):
+ # No multilingual Whisper to fall back on → vosk (first-installed) is the only
+ # local option, so use it as an honest best effort rather than going deaf.
+ plan = resolve_wake_plan(
+ _cfg(),
+ local_whisper_available=False,
+ language=language,
+ vosk_available=True,
+ )
+ assert plan.engine == "vosk_kws"
+
+
+def test_concrete_matching_language_uses_fast_vosk(de_model):
+ # A German speaker with the German model installed gets the fast CPU vosk path.
+ 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(de_model)
+
+
+def test_concrete_mismatched_language_avoids_wrong_vosk_model(de_model):
+ # The 'Hey Ruben' bug in miniature: the user's resolved language is English but
+ # ONLY a German model is on disk. resolve_vosk_model_path("en") → None, so we
+ # must NOT use the German model — route to multilingual stt_match instead.
+ plan = resolve_wake_plan(
+ _cfg(),
+ local_whisper_available=True,
+ language="en",
+ vosk_available=True,
+ )
+ assert plan.engine == "stt_match"
+
+
+def test_explicit_vosk_engine_still_honours_first_installed(en_model):
+ # An explicit engine="vosk_kws" is a user override — honour it against whatever
+ # model is installed even under an ambiguous language (no gamble guard applies).
+ plan = resolve_wake_plan(
+ _cfg(engine="vosk_kws"),
+ local_whisper_available=True,
+ language="auto",
+ vosk_available=True,
+ )
+ assert plan.engine == "vosk_kws"
+
+
+def test_mismatched_language_no_whisper_is_honest_wake_off(de_model):
+ # English speaker, only a German model, and no local Whisper: there is no
+ # honest way to hear the English word → wake OFF, never a silent dead listener.
+ plan = resolve_wake_plan(
+ _cfg(),
+ local_whisper_available=False,
+ language="en",
+ vosk_available=True,
+ )
+ assert plan.engine == "none"
+ assert plan.wake_available is False
+
+
+# --------------------------------------------------------------------------
+# resolve_wake_language cascade (stt → ui → default) — one SoT everywhere
+# --------------------------------------------------------------------------
+
+
+def test_resolve_wake_language_cascade():
+ from jarvis.speech.wake_model_fetch import resolve_wake_language
+
+ # stt.language concrete wins
+ assert resolve_wake_language(
+ SimpleNamespace(stt=SimpleNamespace(language="de"), ui=SimpleNamespace(language="en"))
+ ) == "de"
+ # stt "auto" → fall to ui.language
+ assert resolve_wake_language(
+ SimpleNamespace(stt=SimpleNamespace(language="auto"), ui=SimpleNamespace(language="es"))
+ ) == "es"
+ # nothing concrete → default 'en'
+ assert resolve_wake_language(
+ SimpleNamespace(stt=SimpleNamespace(language="auto"), ui=SimpleNamespace(language="auto"))
+ ) == "en"
+
+
+# --------------------------------------------------------------------------
+# OOV guard: deterministic branches (a real model check needs a downloaded model)
+# --------------------------------------------------------------------------
+
+
+def test_oov_guard_empty_phrase_is_unsupported():
+ from jarvis.plugins.wake.vosk_kws_provider import vosk_model_supports_phrase
+
+ assert vosk_model_supports_phrase("/nonexistent/model", "") is False
+
+
+def test_oov_guard_fails_open_on_bad_model_path():
+ # A probe that cannot even load the model must NEVER reject a real word.
+ from jarvis.plugins.wake.vosk_kws_provider import vosk_model_supports_phrase
+
+ assert vosk_model_supports_phrase("/definitely/not/a/model", "Hey Ruben") is True
+
+
+# --------------------------------------------------------------------------
+# CPU-first default: the GPU wake hot-swap is OFF unless explicitly opted in
+# --------------------------------------------------------------------------
+
+
+def test_wake_high_accuracy_defaults_to_cpu():
+ # Guards the 2026-07-09 CPU-first flip: the sticky GPU probe caches made a
+ # once-fast wake go permanently deaf after a restart, so GPU wake is opt-in.
+ from jarvis.core.config import STTConfig
+
+ assert STTConfig().wake_high_accuracy is False
+
+
+# --------------------------------------------------------------------------
+# Anti-drift: the STT/wake language list must agree Python ↔ TS (BUG-008 class)
+# --------------------------------------------------------------------------
+
+
+def test_stt_language_list_parity_python_ts():
+ # The wake language selector reuses the STT-language machinery. If the Python
+ # accepted set (settings_routes._STT_LANGUAGES) and the TS SttLanguage union
+ # drift, the Settings dropdown offers a value the backend rejects (or vice
+ # versa). Set-equality (order-independent) so a re-ordering never false-fails.
+ import re
+
+ from jarvis.ui.web.settings_routes import _STT_LANGUAGES
+
+ ts_path = (
+ Path(__file__).resolve().parents[3]
+ / "jarvis" / "ui" / "web" / "frontend" / "src" / "i18n" / "index.ts"
+ )
+ text = ts_path.read_text(encoding="utf-8")
+ m = re.search(r"export type SttLanguage\s*=\s*([^;]+);", text)
+ assert m, "SttLanguage type union not found in i18n/index.ts"
+ ts_langs = set(re.findall(r"[\"']([a-z]+)[\"']", m.group(1)))
+ assert ts_langs == set(_STT_LANGUAGES), (
+ f"TS {ts_langs} != Python {set(_STT_LANGUAGES)} — keep the STT language "
+ "list in lockstep (settings_routes._STT_LANGUAGES ↔ i18n SttLanguage)."
+ )