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(voice): wake word responds without waiting out the 7-24s warm-up

Ruben Lütke1f0dad5fa837
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 969b487a1a..bcb8efb6a6 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -124,6 +124,35 @@ if TYPE_CHECKING:
log = logging.getLogger("jarvis.speech.pipeline")
+
+async def _gather_timed(
+ named_thunks: list[tuple[str, Callable[[], Awaitable[Any]]]],
+) -> tuple[dict[str, float], list[Any]]:
+ """Run named async thunks concurrently and time each one individually.
+
+ Returns ``(timings_ms, results)`` where ``timings_ms[name]`` is the
+ per-thunk wall-clock in milliseconds (recorded even if the thunk raises) and
+ ``results`` mirrors ``asyncio.gather(..., return_exceptions=True)`` order:
+ each entry is the thunk's return value or its captured exception. Used to
+ expose which Phase-A loader dominates warm-up (the gather otherwise hides
+ per-loader cost behind its slowest member).
+ """
+ timings: dict[str, float] = {}
+
+ async def _run(name: str, thunk: Callable[[], Awaitable[Any]]) -> Any:
+ t0 = time.monotonic()
+ try:
+ return await thunk()
+ finally:
+ timings[name] = (time.monotonic() - t0) * 1000.0
+
+ results = await asyncio.gather(
+ *(_run(name, thunk) for name, thunk in named_thunks),
+ return_exceptions=True,
+ )
+ return timings, list(results)
+
+
# Long-dictation accumulation guardrails. When the VAD force-cuts a long
# continuous utterance (reason in FORCED_CUT_REASONS), the pipeline buffers
# the PCM fragments and only finalizes at a natural endpoint. These caps stop
@@ -1389,6 +1418,11 @@ class SpeechPipeline:
# path so voice can declare ready early. Kept on the instance so tests
# (and a graceful shutdown) can await it.
self._warmup_background_task: asyncio.Task | None = None
+ # Deferred wake-non-critical loaders (VAD/STT/TTS) run off the
+ # wake-ready path so "Hey Jarvis" responds without waiting out the
+ # 7-24 s starved warm-up (see ``_warmup_phase_a``). Kept on the instance
+ # so a graceful shutdown can cancel + await it.
+ self._deferred_warmup_task: asyncio.Task | None = None
# ContinuationBuffer (Spec docs/superpowers/specs/
# 2026-05-25-incomplete-prompt-completion-design.md): coalesces a
@@ -3108,26 +3142,28 @@ class SpeechPipeline:
log.warning("VoiceBootStatus(ready=%s) publish failed: %s", ready, exc)
async def _cancel_warmup_background(self) -> None:
- """Cancel + await the Phase-B confirmation-audio task on shutdown.
+ """Cancel + await the fire-and-forget warm-up tasks on shutdown.
- Phase B (ACK + task-ack pre-render) runs fire-and-forget off the
- critical path. When ``run()`` is cancelled (the normal desktop-shutdown
- path) it must be cancelled and awaited, otherwise it is orphaned: under
+ Two background tasks run off the wake-critical path: Phase B (the ACK +
+ task-ack confirmation-audio pre-render) and the deferred VAD/STT/TTS
+ loaders. When ``run()`` is cancelled (the normal desktop-shutdown path)
+ both must be cancelled and awaited, otherwise they are orphaned: under
``pythonw.exe`` there is no stderr to surface the "Task exception was
never retrieved" warning, and a late TTS render could write stale PCM
into ``_ack_pcm`` / ``_task_ack_pcm`` after a live TTS-provider switch
already cleared them. Guarded so shutdown never raises.
"""
- task = self._warmup_background_task
- if task is None:
- return
- if not task.done():
- task.cancel()
- try:
- await task
- except (asyncio.CancelledError, Exception): # noqa: BLE001 — shutdown swallow
- pass
- self._warmup_background_task = None
+ for attr in ("_warmup_background_task", "_deferred_warmup_task"):
+ task = getattr(self, attr, None)
+ if task is None:
+ continue
+ if not task.done():
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001 — shutdown swallow
+ pass
+ setattr(self, attr, None)
async def _warmup(self) -> None:
log.info("Warm-up: Whisper / Silero / Wake-Word / TTS …")
@@ -3161,14 +3197,69 @@ class SpeechPipeline:
log.info("Warm-up Phase A complete — confirmation audio rendering in background.")
async def _warmup_phase_a(self) -> None:
- """Run the critical, mutually-independent loaders concurrently.
-
- Audio-device stabilization is a BUG-014 guard (settle the PortAudio
- table before any stream opens); its logic is unchanged, only run inside
- the concurrent group. The synchronous model/client loaders are pushed
- to worker threads so the gather is genuinely parallel — each touches
- only its own idempotent ``_ensure_*`` state, so there is no shared-state
- race between the tasks.
+ """Bring up ONLY the wake-critical listening path, then return.
+
+ The wake loop is started the moment this returns, so it must block on
+ the absolute minimum: the audio-device table settling (BUG-014 guard)
+ and the OpenWakeWord model starting. That is everything the wake path
+ needs to hear "Hey Jarvis" and spawn the orb.
+
+ The heavy VAD / STT / TTS-client loads are deliberately NOT here. Each
+ of them lazy-imports a large C-extension (onnxruntime for the wake model
+ and Silero-VAD, ctranslate2 for local Whisper); run concurrently inside
+ the boot storm they serialize on the Python import lock and starve to
+ 7-24 s (measured: ``wake-start=14187, vad-load=12672``). Because the wake
+ loop used to start only after the WHOLE warm-up finished, gating it on
+ those loads left the wake word dead for that entire window — the
+ "~10 s delay / nothing spawns" regression. They are only needed AFTER a
+ wake and are lazy-safe (each object re-ensures its model on first use),
+ so they move to a background deferred task (``_warmup_deferred_loaders``)
+ that never gates wake readiness.
+ """
+ async def _start_wake() -> None:
+ if self._openwakeword_enabled:
+ await self._wake.start()
+
+ # return_exceptions=True (inside _gather_timed): a slow/failing loader
+ # must not abort the other. The per-loader timing exposes which one
+ # dominates the wake-critical warm-up (boot-perf forensic).
+ timings, results = await _gather_timed(
+ [
+ ("audio-stabilize", self._stabilize_audio_devices),
+ ("wake-start", _start_wake),
+ ]
+ )
+ self._warmup_phase_a_timings = timings
+ log.info(
+ "Warm-up Phase A (wake-critical) per-loader (ms): %s",
+ ", ".join(
+ f"{name}={timings[name]:.0f}"
+ for name in sorted(timings, key=lambda n: -timings[n])
+ ),
+ )
+ for name, res in zip(("audio-stabilize", "wake-start"), results, strict=True):
+ if isinstance(res, Exception):
+ log.warning("Warm-up Phase A task '%s' failed: %s", name, res)
+
+ # Heavy model loads move off the wake-ready path — fire-and-forget so a
+ # wake can fire (and the orb spawn) while they are still loading. A wake
+ # that arrives first simply triggers a one-off lazy load on the VAD/STT
+ # object instead of waiting out the whole warm-up. Cancelled on shutdown
+ # via ``_cancel_warmup_background``.
+ self._deferred_warmup_task = asyncio.create_task(
+ self._warmup_deferred_loaders(), name="warmup-deferred-loaders"
+ )
+
+ async def _warmup_deferred_loaders(self) -> None:
+ """Background pre-load of VAD + STT + TTS client — never gates wake
+ readiness (see ``_warmup_phase_a``).
+
+ VAD is the soonest thing needed after a wake (utterance endpointing), so
+ it is loaded first; the local-Whisper STT (if any) and the TTS client
+ follow. Each load is isolated (``return_exceptions=True``) so one
+ slow/failing load never breaks the others, and every object's
+ ``_ensure_*`` is idempotent — a concurrent lazy load on first use is a
+ harmless no-op once this has run.
"""
async def _load_vad() -> None:
await asyncio.to_thread(self._vad._ensure_model)
@@ -3178,32 +3269,28 @@ class SpeechPipeline:
if self._stt is not None:
await asyncio.to_thread(self._stt._ensure_model)
- async def _start_wake() -> None:
- if self._openwakeword_enabled:
- await self._wake.start()
-
async def _init_tts() -> None:
await asyncio.to_thread(self._tts._ensure_client)
- # return_exceptions=True: one slow/failing loader must not abort the
- # others. Each coroutine already isolates its own failure where a soft
- # failure is tolerable; here we additionally log any hard exception
- # without breaking the remaining critical path.
- results = await asyncio.gather(
- self._stabilize_audio_devices(),
- _load_vad(),
- _load_stt(),
- _start_wake(),
- _init_tts(),
- return_exceptions=True,
+ timings, results = await _gather_timed(
+ [
+ ("vad-load", _load_vad),
+ ("stt-load", _load_stt),
+ ("tts-init", _init_tts),
+ ]
+ )
+ log.info(
+ "Warm-up deferred loaders (ms): %s",
+ ", ".join(
+ f"{name}={timings[name]:.0f}"
+ for name in sorted(timings, key=lambda n: -timings[n])
+ ),
)
for name, res in zip(
- ("audio-stabilize", "vad-load", "stt-load", "wake-start", "tts-init"),
- results,
- strict=True,
+ ("vad-load", "stt-load", "tts-init"), results, strict=True
):
if isinstance(res, Exception):
- log.warning("Warm-up Phase A task '%s' failed: %s", name, res)
+ log.warning("Warm-up deferred loader '%s' failed: %s", name, res)
async def _warmup_phase_b(self) -> None:
"""Background pre-render of confirmation audio (never blocks ready).
diff --git a/jarvis/speech/wake_verifier.py b/jarvis/speech/wake_verifier.py
index fc60360ed8..c125220c2c 100644
--- a/jarvis/speech/wake_verifier.py
+++ b/jarvis/speech/wake_verifier.py
@@ -35,6 +35,15 @@ WAKE_PREFIX_PATTERN = DEFAULT_PATTERN
# activation.
_WAKE_VERIFY_RETRIES = 1
_WAKE_VERIFY_BACKOFF_S = 0.3
+# Hard cap on a single wake-verify STT round-trip. The cloud STT client itself
+# carries a 30 s request timeout meant for full utterance transcription — far
+# too long for a wake gate that sits IN FRONT of the orb spawn. A verify that
+# takes more than a couple of seconds is useless: the user already said
+# "Hey Jarvis" and is waiting for a reaction NOW. A hung/overloaded Groq must
+# therefore be cut off here and treated like a transient error (retry, then
+# fail-closed suppress) instead of freezing the wake path for the full client
+# timeout — that freeze was the "~10 second delay after the wake word" forensic.
+_WAKE_VERIFY_TIMEOUT_S = 2.5
class _SupportsTranscribePCM(Protocol):
@@ -91,8 +100,11 @@ async def verify_wake_with_stt(
last_exc: Exception | None = None
for attempt in range(_WAKE_VERIFY_RETRIES + 1):
try:
- transcript = await stt.transcribe_pcm(
- pcm_bytes, sample_rate=sample_rate, language=language
+ transcript = await asyncio.wait_for(
+ stt.transcribe_pcm(
+ pcm_bytes, sample_rate=sample_rate, language=language
+ ),
+ timeout=_WAKE_VERIFY_TIMEOUT_S,
)
last_exc = None
break
diff --git a/tests/unit/speech/test_wake_verifier.py b/tests/unit/speech/test_wake_verifier.py
index 1d6b23b648..9b9e506e07 100644
--- a/tests/unit/speech/test_wake_verifier.py
+++ b/tests/unit/speech/test_wake_verifier.py
@@ -14,6 +14,8 @@ verification path.
"""
from __future__ import annotations
+import asyncio
+import time
from dataclasses import dataclass
import pytest
@@ -197,3 +199,49 @@ async def test_verify_passes_through_language_override() -> None:
await verify_wake_with_stt(stt, PCM_2S_16K, language="en")
assert stt.calls == [(len(PCM_2S_16K), 16_000, "en")]
+
+
+# ---------------------------------------------------------------------------
+# Timeout cap — a wake-verify must never block the wake path for the full cloud
+# STT client timeout (Groq default 30 s). A verify that takes seconds is
+# useless: the user said "Hey Jarvis" and is waiting for the orb to spawn NOW.
+# A hung/slow STT round-trip is capped and treated like a transient error
+# (retry then fail-closed suppress), so the listener re-arms instead of freezing
+# for 10-30 s before any reaction (the exact "~10 second delay after the wake
+# word" forensic).
+# ---------------------------------------------------------------------------
+
+
+class _HangingSTT:
+ """STT whose transcribe_pcm hangs far longer than the wake-verify cap."""
+
+ def __init__(self, hang_s: float = 1.0) -> None:
+ self._hang_s = hang_s
+ self.calls = 0
+
+ async def transcribe_pcm(self, pcm_bytes, sample_rate=16_000, language=None):
+ self.calls += 1
+ await asyncio.sleep(self._hang_s)
+ return _FakeTranscript(text="Hey Jarvis")
+
+
+async def test_verify_caps_a_hung_stt_call(monkeypatch) -> None:
+ """A hung cloud STT round-trip is cut off by the wake-verify timeout cap
+ instead of blocking the wake path for seconds. On timeout the hit is
+ suppressed (fail-closed), exactly like a persistent STT error."""
+ import jarvis.speech.wake_verifier as wv
+
+ monkeypatch.setattr(wv, "_WAKE_VERIFY_BACKOFF_S", 0.0, raising=False)
+ monkeypatch.setattr(wv, "_WAKE_VERIFY_TIMEOUT_S", 0.05, raising=False)
+ monkeypatch.setattr(wv, "_WAKE_VERIFY_RETRIES", 0, raising=False)
+
+ stt = _HangingSTT(hang_s=1.0)
+ t0 = time.monotonic()
+ matched, _ = await verify_wake_with_stt(stt, PCM_2S_16K)
+ elapsed = time.monotonic() - t0
+
+ assert matched is False, "a capped (hung) verify must fail closed, not match"
+ assert elapsed < 0.5, (
+ f"wake-verify blocked {elapsed:.2f}s — the timeout cap did not fire"
+ )
+ assert stt.calls >= 1
diff --git a/tests/unit/speech/test_warmup_two_phase.py b/tests/unit/speech/test_warmup_two_phase.py
index 3a3c045842..5ea6612601 100644
--- a/tests/unit/speech/test_warmup_two_phase.py
+++ b/tests/unit/speech/test_warmup_two_phase.py
@@ -141,19 +141,83 @@ async def test_emits_ready_false_then_true(monkeypatch) -> None:
@pytest.mark.asyncio
-async def test_phase_a_runs_critical_loaders(monkeypatch) -> None:
- """Phase A must load VAD, init the TTS client, start OpenWakeWord, and
- re-resolve the output device (BUG-014 guard)."""
+async def test_phase_a_runs_wake_critical_loaders(monkeypatch) -> None:
+ """Phase A must do exactly the wake-critical work: start OpenWakeWord and
+ re-resolve the output device (BUG-014 guard). The heavy VAD/TTS loads are
+ NOT in Phase A anymore — they are deferred — so they must NOT have run by
+ the time the wake path is ready."""
pipe = _new_pipe(monkeypatch, bus=FakeBus())
await pipe._warmup()
- assert pipe._vad.ensure_calls >= 1
- assert pipe._tts.ensure_calls >= 1
assert pipe._wake.started is True
assert pipe._player.set_device_calls == ["auto-headset"]
+async def test_deferred_loaders_eventually_load_vad_and_tts(monkeypatch) -> None:
+ """VAD + TTS are not skipped — they load via the background deferred task so
+ they are ready by the first post-wake turn, just off the wake-ready path."""
+ pipe = _new_pipe(monkeypatch, bus=FakeBus())
+
+ await pipe._warmup()
+ dbg = pipe._deferred_warmup_task
+ assert dbg is not None, "deferred VAD/STT/TTS load must run as a background task"
+ await dbg
+
+ assert pipe._vad.ensure_calls >= 1
+ assert pipe._tts.ensure_calls >= 1
+
+
+async def test_phase_a_does_not_block_on_heavy_loads(monkeypatch) -> None:
+ """The wake-critical path (audio-stabilize + OpenWakeWord start) must reach
+ ready WITHOUT waiting on the heavy VAD/STT/TTS model loads.
+
+ Forensic (2026-06-22): those loads each lazy-import a big C-extension
+ (onnxruntime for the wake model + Silero, ctranslate2 for Whisper). Run
+ concurrently inside the boot storm they serialize on the Python import lock
+ and get starved to 7-24 s (measured: ``wake-start=14187, vad-load=12672``).
+ Because the wake loop was started only AFTER the whole warm-up finished,
+ "Hey Jarvis" was dead for that entire window. VAD/STT/TTS are only needed
+ AFTER a wake (and load lazily on first use), so they must move off the
+ ready path into a background task and never gate wake readiness.
+ """
+ import threading
+
+ pipe = _new_pipe(monkeypatch, bus=FakeBus())
+
+ vad_release = threading.Event()
+
+ class _BlockingVad:
+ def __init__(self) -> None:
+ self.ensure_calls = 0
+
+ def _ensure_model(self) -> None:
+ # Synchronous load (runs in a worker thread via asyncio.to_thread);
+ # block until the test releases it, modelling a starved model load.
+ vad_release.wait(5.0)
+ self.ensure_calls += 1
+
+ pipe._vad = _BlockingVad()
+
+ # Phase A must COMPLETE (wake model started) even though the VAD load is
+ # still blocked. Without the decoupling this awaits the blocked load and the
+ # wait_for trips → the regression is reproduced.
+ await asyncio.wait_for(pipe._warmup_phase_a(), timeout=3.0)
+
+ assert pipe._wake.started is True, "wake model must be started by Phase A"
+ assert pipe._vad.ensure_calls == 0, "the heavy VAD load must NOT block Phase A"
+
+ # The load is not skipped — it runs as a background (deferred) task that the
+ # release lets finish.
+ dbg = getattr(pipe, "_deferred_warmup_task", None)
+ assert dbg is not None, "VAD/STT/TTS must load via a background deferred task"
+ vad_release.set()
+ await asyncio.wait_for(dbg, timeout=3.0)
+ assert pipe._vad.ensure_calls >= 1, "the deferred VAD load must eventually run"
+
+
@pytest.mark.asyncio
async def test_ready_signaled_before_background_render_finishes(monkeypatch) -> None:
"""The ready=True signal must be emitted BEFORE the confirmation-audio