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(boot): stop the boot storm from starving the vosk wake-model load

Ruben Lütke9c378f5301ac
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index 92b351b027..64a4531140 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -470,6 +470,9 @@ class VoskKwsProvider:
self._target_peak = float(target_peak)
self._max_gain = float(max_gain)
self._models: dict[str, Any] = {}
+ # Set once ``start()`` has attempted every model load — the honest
+ # "warm" floor even when a broken model directory never loads.
+ self._load_attempted = False
# Pre-warmed ONE-SHOT verify recognizers, keyed (model_path, kind).
# Why: a fresh KaldiRecognizer's FIRST decode pays ~400ms lazy init
# on top of ~100ms construction (measured 2026-07-11: fresh verify
@@ -636,6 +639,25 @@ class VoskKwsProvider:
self._kick_replenish()
return recs
+ @property
+ def is_warm(self) -> bool:
+ """True once every configured model directory has finished loading.
+
+ Consumed by the desktop wake-model priority gate: the heavy backend
+ boot storm (brain/MCP/mission init) is held until the ACTIVE wake
+ engine is warm so the model load runs uncontended. Gating on the
+ utterance STT instead let the storm start mid-load and stretched a
+ few-second Vosk model load to 30+ s (live forensic 2026-07-17).
+
+ A broken model directory must not wedge the gate: once ``start()``
+ has ATTEMPTED every load, warm is honest-true even if a load failed
+ (detection continues on the working models; the gate's job — an
+ uncontended load window — is over either way).
+ """
+ if self._load_attempted:
+ return True
+ return all(path in self._models for path in self._model_paths)
+
async def start(self) -> None:
"""Pre-load every model and FILL the prewarmed recognizer stock.
@@ -644,13 +666,22 @@ class VoskKwsProvider:
first-decode init), and unlike the throwaways they are kept and
consumed by the first real detect/verify. Fail-closed: errors must
never break boot — takers fall back to cold builds.
+
+ The per-language models load CONCURRENTLY: each is an independent
+ Kaldi object (no shared engine, AP-24-safe) and the load is mostly
+ native disk/CPU work, so overlapping them cuts multi-language boot
+ from the sum of the loads to the slowest one (live forensic
+ 2026-07-17: en 34 s + de 24 s sequential under a boot storm).
"""
- for path in self._model_paths:
+ async def _load_one(path: str) -> None:
try:
await asyncio.to_thread(self._ensure_model, path)
except Exception as exc: # noqa: BLE001 — a broken model must not
# brick the working ones; _fresh_recs skips it too.
log.warning("vosk-kws: model %s failed to load (%s).", path, exc)
+
+ await asyncio.gather(*(_load_one(path) for path in self._model_paths))
+ self._load_attempted = True
await asyncio.to_thread(self._replenish_stock)
async def stop(self) -> None:
@@ -667,6 +698,7 @@ class VoskKwsProvider:
with self._stock_lock:
self._rec_stock.clear()
self._models.clear()
+ self._load_attempted = False
self._ring.clear()
self._ring_len = 0
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 1981b83663..cd2a6e9fb9 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -2907,6 +2907,18 @@ class DesktopApp:
# immediately if there is no local wake model (e.g. the OWW path), so
# the backend never waits needlessly.
def _wake_model_is_loaded() -> bool:
+ # Prefer the ACTIVE wake detector's own warm signal. The
+ # any-word vosk_kws engine loads one Kaldi model per installed
+ # language inside ``wake.start()`` — the STT-based probes below
+ # know nothing about it, so the gate used to release while
+ # those loads were still running and the heavy backend storm
+ # stretched a few-second load to 30+ s per model (live
+ # forensic 2026-07-17: en 34 s + de 24 s, voice ready at ~2 min).
+ detector_warm = getattr(
+ getattr(pipeline, "_wake", None), "is_warm", None
+ )
+ if detector_warm is not None:
+ return bool(detector_warm)
ww = getattr(pipeline, "_whisper_wake", None)
base_stt = getattr(ww, "_stt", None) if ww is not None else stt
if base_stt is None:
diff --git a/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx b/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx
index 7a709881bb..f286b13fde 100644
--- a/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx
@@ -16,9 +16,41 @@ describe("AuthGate", () => {
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
+ vi.useRealTimers();
window.__JARVIS_TOKEN = undefined;
});
+ it("shows an honest starting state while the backend is still warming", async () => {
+ vi.useFakeTimers();
+ // The serve-first bootstrap HOLDS /api/config during warm-up — model that
+ // with a never-resolving promise; only /api/health answers (warming: true).
+ const held = new Promise<Response>(() => {});
+ const fetchMock = vi.fn((url: unknown) => {
+ if (url === "/api/health") {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ ok: true, warming: true }),
+ } as unknown as Response);
+ }
+ return held;
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ render(<AuthGate><div>Application</div></AuthGate>);
+ expect(screen.getByText("Checking access…")).toBeTruthy();
+
+ await act(async () => {
+ vi.advanceTimersByTime(1100);
+ });
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(screen.getByText("Starting up…")).toBeTruthy();
+ expect(screen.queryByText("Application")).toBeNull();
+ });
+
it("renders the application when the session cookie is authorized", async () => {
const fetchMock = vi.fn().mockResolvedValue(response(200));
vi.stubGlobal("fetch", fetchMock);
diff --git a/jarvis/ui/web/frontend/src/components/AuthGate.tsx b/jarvis/ui/web/frontend/src/components/AuthGate.tsx
index 13c478d2f6..81104e66f9 100644
--- a/jarvis/ui/web/frontend/src/components/AuthGate.tsx
+++ b/jarvis/ui/web/frontend/src/components/AuthGate.tsx
@@ -49,10 +49,42 @@ export function AuthGate({ children }: AuthGateProps) {
const t = useT();
const started = useRef(false);
const [state, setState] = useState<GateState>("checking");
+ const [backendWarming, setBackendWarming] = useState(false);
const [controlKey, setControlKey] = useState("");
const [submitting, setSubmitting] = useState(false);
const [errorKey, setErrorKey] = useState<string | null>(null);
+ // While the access probe is pending, poll the (always instantly answered)
+ // health endpoint. During a cold boot the serve-first bootstrap HOLDS every
+ // /api/* request until the real backend registers — which can take a while —
+ // so without this the gate shows "Checking access…" for the entire warm-up
+ // and the boot looks stuck on an access check that is actually fine. Health
+ // answers `warming: true` from the first millisecond, letting the gate show
+ // an honest "starting up" instead. Polling starts after a beat so the normal
+ // already-warm path (config answers in milliseconds) never pays a request.
+ useEffect(() => {
+ if (state !== "checking") return;
+ let cancelled = false;
+ const probe = async () => {
+ try {
+ const res = await fetch("/api/health", {
+ cache: "no-store",
+ credentials: "same-origin",
+ });
+ if (!res.ok || cancelled) return;
+ const body = (await res.json()) as { warming?: boolean };
+ if (!cancelled) setBackendWarming(body?.warming === true);
+ } catch {
+ // Offline/unreachable — the /api/config probe owns that outcome.
+ }
+ };
+ const timer = window.setInterval(() => void probe(), 1000);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ };
+ }, [state]);
+
useEffect(() => {
if (started.current) return;
started.current = true;
@@ -124,9 +156,15 @@ export function AuthGate({ children }: AuthGateProps) {
if (state === "checking") {
return (
<main className="flex min-h-screen items-center justify-center bg-background text-foreground">
- <span className="text-sm text-muted-foreground" role="status">
- {t("auth_gate.checking")}
- </span>
+ <div className="flex flex-col items-center gap-4">
+ <div
+ aria-hidden="true"
+ className="h-9 w-9 animate-spin rounded-full border-[3px] border-primary/20 border-t-primary"
+ />
+ <span className="text-sm text-muted-foreground" role="status">
+ {t(backendWarming ? "auth_gate.starting" : "auth_gate.checking")}
+ </span>
+ </div>
</main>
);
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 167e4aeab3..30aa360844 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1,6 +1,7 @@
{
"auth_gate": {
"checking": "Zugriff wird geprüft…",
+ "starting": "Wird gestartet…",
"title": "Personal Jarvis entsperren",
"subtitle": "Gib den Control Key dieser Jarvis-Instanz ein.",
"control_key": "Control Key",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 907f7c8221..70250d7b6b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1,6 +1,7 @@
{
"auth_gate": {
"checking": "Checking access…",
+ "starting": "Starting up…",
"title": "Unlock Personal Jarvis",
"subtitle": "Enter the Control Key of this Jarvis instance.",
"control_key": "Control Key",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 5930e1b2f2..e6529ca132 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1,6 +1,7 @@
{
"auth_gate": {
"checking": "Comprobando el acceso…",
+ "starting": "Iniciando…",
"title": "Desbloquear Personal Jarvis",
"subtitle": "Introduce la clave de control de esta instancia de Jarvis.",
"control_key": "Clave de control",
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index ab126b8573..5d36196239 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -517,7 +517,7 @@ class WebServer:
if self._voice_ready:
return
logger.warning(
- "Voice-ready watchdog fired after %.0fs — the speech pipeline never "
+ "Voice-ready watchdog fired after {:.0f}s — the speech pipeline never "
"signalled ready (a construction crash or a wedged warm-up load). "
"Force-releasing the UI from 'starting up'; voice may be offline until "
"restart.",
diff --git a/scripts/measure_desktop_boot.py b/scripts/measure_desktop_boot.py
index be74bd5fbf..80e32e57be 100644
--- a/scripts/measure_desktop_boot.py
+++ b/scripts/measure_desktop_boot.py
@@ -188,6 +188,25 @@ def run_one(python: str, timeout: float, mode: str = "legacy", voice: bool = Fal
if "<!doctype html" in body or "<div id=" in body or "<html" in body:
result["wall_ms"] = (time.perf_counter() - t_spawn) * 1000.0
health_ok.set()
+ # A real desktop window acknowledges its first paint
+ # (POST /api/ui/shell-painted after two animation
+ # frames), which releases the backend's heavy-init
+ # gate. This GUI-free harness has no window, so
+ # WITHOUT the ack every run silently pays the full
+ # 12 s paint-timeout fallback — inflating every TTU
+ # anchor and false-failing the boot-budget gate.
+ # Ack right after the shell HTML is served: the
+ # closest honest stand-in for the window's paint.
+ try:
+ req = urllib.request.Request(
+ f"http://127.0.0.1:{port}/api/ui/shell-painted",
+ data=b"",
+ method="POST",
+ )
+ with urllib.request.urlopen(req, timeout=2.0): # noqa: S310
+ pass
+ except Exception: # noqa: BLE001 — ack is best-effort
+ pass
return
except Exception: # noqa: BLE001
pass
diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.py
index 354bbf1874..1a59713b41 100644
--- a/tests/unit/plugins/wake/test_vosk_kws_provider.py
+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py
@@ -235,6 +235,29 @@ async def _run_detect(provider: VoskKwsProvider, chunks: list[AudioChunk]) -> li
return fired
+# --- warm-up / start ------------------------------------------------------------
+
+
+async def test_start_loads_all_models_concurrently_and_reports_warm(fake_vosk) -> None:
+ """``is_warm`` is the desktop wake-model priority gate's signal: it must be
+ False until ``start()`` has loaded (or at least attempted) EVERY configured
+ per-language model, and True afterwards — gating the heavy backend on the
+ utterance STT instead let the boot storm start mid-load and stretched a
+ few-second Vosk load to 30+ s per model (live forensic 2026-07-17)."""
+ provider = VoskKwsProvider(
+ phrase="Hey Nova",
+ model_path="models/en",
+ model_paths=("models/en", "models/de"),
+ )
+ assert provider.is_warm is False
+ await provider.start()
+ assert set(fake_vosk["models"]) == {"models/en", "models/de"}
+ assert provider.is_warm is True
+ # A detector swap tears warm state down with the models.
+ await provider.stop()
+ assert provider.is_warm is False
+
+
# --- detection loop -------------------------------------------------------------