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): verify local speech readiness and contain failed workers

rubenluetke10-beep9a492cb93e29
diff --git a/docs/reports/local-realtime-diagnosis-2026-10-02.md b/docs/reports/local-realtime-diagnosis-2026-10-02.md
new file mode 100644
index 0000000000..798eadb9af
--- /dev/null
+++ b/docs/reports/local-realtime-diagnosis-2026-10-02.md
@@ -0,0 +1,132 @@
+# Local realtime diagnosis and reliability repair
+
+Date: 2026-10-02. Scope: local speech only; GPT-Live providers, their model
+selection, delegation, authentication and transport are unchanged.
+
+## What failed
+
+The checkout contains two different local voice implementations. Their names
+make it easy to select the wrong one:
+
+- `local-realtime`: the older managed `speech-to-speech` server, combining
+ Parakeet, an Ollama language model and Qwen3/Pocket speech synthesis behind
+ an OpenAI-compatible WebSocket.
+- `local-voice`: the newer Jarvis-owned engine from ADR-0037. One isolated
+ child process loads CPU speech models, calls the local Ollama model directly,
+ and exchanges framed audio/control messages with the app over pipes.
+
+Neither implementation is a single end-to-end speech model. The second already
+has an in-app setup that downloads its dependencies and selects an installed
+language model according to the machine class. A user does not need to manage
+three separate servers or use GPT-Live to operate it.
+
+Observed in the existing local logs:
+
+- At 19:27 and 19:28, calls to the old server were refused because it was still
+ starting. Switching to `local-voice` also produced loading refusals, including
+ two reports of 0% progress more than a minute apart.
+- At 19:30:56, the old Qwen3 path logged 34.70 seconds of generation for
+ 3.40 seconds of speech. Its response accounting recorded 0.00 seconds of
+ delivered audio. The log establishes slow generation and failed delivery
+ accounting; it does not establish what was audible at the speakers.
+- The old server repeatedly reported an unready pool and recovery deferrals.
+ Later status reads showed the new engine ready while GPT-Live subscription
+ was selected. A ready engine is not evidence that a call used that engine.
+- The machine initially had roughly 13 GB of its 16 GB GPU memory occupied,
+ with the old GPU speech server and an Ollama model both resident. Memory
+ pressure and contention are plausible contributors, not an isolated causal
+ measurement. The old server was gone by the later cleanup check; stop requests
+ reported no owned server. No unrelated process was terminated.
+
+The old log cannot uniquely identify why the new engine reported 0% on those
+particular calls. Code inspection did establish the lifecycle defects below.
+
+## Repair implemented
+
+1. **Readiness now requires actual inference.** Worker startup synthesizes and
+ re-transcribes a short phrase in each configured language, then requires a
+ nonempty answer from the local language model. Failed synthesis, recognition
+ or reasoning cannot publish `ready`. This checks the software audio path,
+ not the physical microphone, speakers or wake word.
+2. **Startup failures release their resources.** A failed/cancelled handshake,
+ incompatible worker protocol or broken output pipe closes the worker and
+ its log. Concurrent cleanup callers join one cleanup task; cancellation
+ does not abandon it. Replacing settings also cancels an unfinished start.
+3. **Loading cannot remain pending forever.** The adapter limits loading to
+ 180 seconds after handshake and shuts down a stalled worker. It identifies
+ the loading stage and offers a fresh-process retry through the self-test.
+ A failed readiness test also releases its unusable worker before retry.
+4. **Live audio and control messages preserve wire order.** Previously they
+ passed through separate queues/tasks, allowing `response.done` or an
+ interruption to overtake previously received audio. The live adapter now
+ consumes one ordered stream. Existing measurement clients retain their
+ separate-queue interface.
+5. **Status is more truthful.** The initial handshake is shown as starting.
+ Loading refusals no longer repeatedly promise an unmeasured 15-second ETA.
+ Stored self-tests become stale after changes to languages, voice options
+ or the local model-server address, as well as model/voice/version changes.
+
+This repairs the installed engine path. It does not remove the legacy provider
+or automatically switch the user's active provider. Removing the old stack
+remains gated by the remaining ADR-0037 acceptance work.
+
+## Can one downloaded model replace the cascade?
+
+Current publisher documentation was checked, rather than treating text-language
+support, speech recognition and speech output as interchangeable:
+
+| Model | Relevant publisher support | Fit for the default German desktop path |
+| --- | --- | --- |
+| [LFM2.5-Audio 1.5B](https://huggingface.co/LiquidAI/LFM2.5-Audio-1.5B) | End-to-end audio/text; English; GGUF CPU inference; LFM Open License | Small and attractive for an English experiment. No supported German voice or demonstrated Jarvis tool contract. |
+| [PersonaPlex 7B](https://huggingface.co/nvidia/personaplex-7b-v1) | Full-duplex speech; English; gated model-license acceptance | Interesting natural conversation, but unsuitable as a zero-setup German default. |
+| [MiniCPM-o 4.5](https://huggingface.co/openbmb/MiniCPM-o-4_5) | 9B; full-duplex; official speech conversation in English and Chinese; local quantized deployment | Multilingual text/vision does not establish German speech output. Not qualified for this default. |
+| [Qwen3-Omni](https://github.com/QwenLM/Qwen3-Omni) | German speech input/output; 30B-A3B Thinker/Talker | A candidate for a larger-machine experimental backend, not a verified 16 GB default. The published BF16 memory table is for video workloads and must not be misreported as an audio-only minimum. Quantized end-to-end desktop deployment still needs measurement. |
+
+The practical default is one Jarvis-managed local voice package, with a local
+reasoning model, CPU speech components, and hardware-dependent model selection.
+This is one setup action, but honestly remains a cascade internally. A native
+audio-model backend should be added only after proving the required spoken
+languages, cold/warm latency, interrupt behavior, tool results, cancellation,
+memory limits and installation on each supported platform. Spoken text that
+looks like JSON must never be interpreted as an authorized action.
+
+## Verification in this session
+
+Real measurements used the installed engine environment, existing model files,
+`qwen3.5:4b`, Pocket TTS and the changed production provider adapter. Speech
+input was synthetic German streamed in 20 ms frames. No cloud model was used.
+
+| Check | Observed result |
+| --- | --- |
+| German arithmetic question from audio | Correct transcription and spoken answer; 218,446 PCM bytes; clean turn completion |
+| Final transcript to first audio, conversational run | 318 ms; this excludes speech capture and endpoint detection |
+| Cold startup including de/en speech proof | 31.93 s in that run |
+| Explicit request to use an arithmetic tool | Exactly one `add_numbers(a=2, b=3)` through the actual `ToolExecutor`; correct spoken result; 76,722 PCM bytes |
+| Tool-run startup and response latency | 37.14 s startup; 18.30 s final-transcript-to-audio under concurrent machine load: functionally successful, too slow for a realtime performance claim |
+| Bare arithmetic question with a tool available | Model answered directly; not counted as tool-execution proof. Explicit action wording was used for the tool test. |
+| Worker shutdown | Probe-owned workers closed after every run |
+| Focused tests | 122 voice-engine tests, 37 local-route/live tests, 27 provider-contract/voice-confirmation tests passed; 2 optional contract cases skipped |
+| Desktop cold-boot guard | Window 1,795 ms; voice usability 9,088 ms; app interaction 10,907 ms; all within existing budgets |
+| Static checks | Ruff passed for changed Python files |
+
+The voice-engine tests cover failed/cancelled handshake cleanup, protocol
+mismatch, pipe failure, ordered audio/completion, startup timeout, readiness
+failure/retry, settings replacement and stale self-test evidence. The adjacent
+tests retain the existing tool-confirmation and shared provider contracts.
+
+## Remaining qualification
+
+- A real microphone-to-speaker conversation, wake word and acoustic echo/
+ interruption acceptance have not been measured in this session.
+- The slow tool result needs an isolated latency investigation before claiming
+ consistently fast local tool conversations. One fast reply is not a latency
+ distribution or a long-session reliability proof.
+- Fresh installation was not repeated; this run reused the installed models
+ and environment. macOS, Linux and weaker hardware were not run in this
+ session. The existing CPU-only tool-quality caveat in the rebuild plan stays.
+- The legacy-provider migration, 500-turn soak and physical offline acceptance
+ from the rebuild plan remain open. A new single-model speech backend has not
+ been claimed or enabled by this repair.
+
+Related: [ADR-0037](../adr/0037-jarvis-owned-local-voice-engine.md) and
+[the local voice rebuild plan](../local-live-voice-rebuild.md).
diff --git a/jarvis/plugins/realtime/local_voice.py b/jarvis/plugins/realtime/local_voice.py
index 023db64285..69c5c51851 100644
--- a/jarvis/plugins/realtime/local_voice.py
+++ b/jarvis/plugins/realtime/local_voice.py
@@ -29,9 +29,6 @@ _OUTPUT_RATE = 24_000
_READY_TIMEOUT_S = 180.0
_SELFTEST_TIMEOUT_S = 120.0
_RESTART_BACKOFF_S = (1.0, 5.0, 30.0)
-#: Core load from a warm disk (plan section 7: core ready <= 15 s); scales the
-#: "about N s" a refused call hears while the engine loads.
-_WARM_LOAD_S = 15.0
#: Measured default for every machine class with an accelerator (plan 12.3).
DEFAULT_LLM = "qwen3.5:4b"
#: Core models the engine cannot start without (``jarvis.voice_engine.models``).
@@ -51,12 +48,12 @@ _REFUSALS: dict[str, dict[str, str]] = {
"Ajustes.", # i18n-allow
},
"loading": {
- "en": "Local voice is still loading ({percent} %). Please try again in about "
- "{eta} seconds.",
- "de": "Die lokale Stimme lädt noch ({percent} %). Versuch es in " # i18n-allow
- "etwa {eta} Sekunden noch einmal.", # i18n-allow
- "es": "La voz local aún se está cargando ({percent} %). Vuelve a " # i18n-allow
- "intentarlo en unos {eta} segundos.", # i18n-allow
+ "en": "Local voice is still loading ({percent} %). The Local voice card "
+ "in Settings shows its progress.",
+ "de": "Die lokale Stimme lädt noch ({percent} %). Die Karte Lokale " # i18n-allow
+ "Stimme in den Einstellungen zeigt den Fortschritt.", # i18n-allow
+ "es": "La voz local aún se está cargando ({percent} %). La tarjeta " # i18n-allow
+ "Voz local de los Ajustes muestra el progreso.", # i18n-allow
},
"failed": {
"en": "Local voice could not start. The Local voice card in Settings shows why.",
@@ -277,6 +274,8 @@ class _Engine:
self._next_slot = 1
self._failures = 0
self._starting: asyncio.Task[None] | None = None
+ self._launching: asyncio.Task[Any] | None = None
+ self._load_watchdog: asyncio.Task[None] | None = None
self._selftests: list[asyncio.Future[dict[str, Any]]] = []
async def ensure_started(self) -> None:
@@ -293,14 +292,40 @@ class _Engine:
extra=_worker_extra_env(home),
)
stderr = home / "worker.log"
- client = EngineClient(settings.python, env=env, stderr_path=stderr)
- self.phase, self.stage, self.reason = "starting", "process", ""
+ client = EngineClient(settings.python, env=env, stderr_path=stderr, ordered=True)
+ self.phase, self.stage, self.reason, self.progress = "starting", "process", "", 0.0
self._ready.clear()
- await client.start()
+ self._launching = asyncio.current_task()
+ try:
+ await client.start()
+ await client.send(settings.configure_message())
+ except BaseException as exc:
+ await client.close()
+ self.phase = "stopped" if isinstance(exc, asyncio.CancelledError) else "failed"
+ self.reason = f"The local voice engine did not start: {exc}"
+ self._ready.set()
+ raise
+ finally:
+ self._launching = None
self._client = client
self._router = asyncio.get_running_loop().create_task(self._route_messages(client))
- self._audio_router = asyncio.get_running_loop().create_task(self._route_audio(client))
- await client.send(settings.configure_message())
+ self._load_watchdog = asyncio.get_running_loop().create_task(
+ self._watch_loading(client))
+
+ async def _watch_loading(self, client: Any) -> None:
+ """A stalled native load is terminal; retry starts a fresh process."""
+ try:
+ await asyncio.wait_for(self._ready.wait(), _READY_TIMEOUT_S)
+ except TimeoutError:
+ if self._client is not client:
+ return
+ stage = self.stage or "process"
+ await self.stop()
+ self.phase = "failed"
+ self.reason = (f"The local voice timed out while loading {stage}. "
+ "Run the self-test on the Local voice card to retry.")
+ log.warning("%s", self.reason)
+ self._ready.set()
def start_soon(self) -> None:
"""Start the worker in the background; a caller never waits for it."""
@@ -311,7 +336,7 @@ class _Engine:
async def _start_logged(self) -> None:
try:
await self.ensure_started()
- except (OSError, RuntimeError, TimeoutError) as exc:
+ except (OSError, RuntimeError, TimeoutError, ValueError) as exc:
log.warning("local voice engine did not start: %s", exc)
self.phase = "failed"
self.reason = f"The local voice engine did not start: {exc}"
@@ -346,6 +371,11 @@ class _Engine:
async def _route_messages(self, client: Any) -> None:
while True:
message = await client.messages.get()
+ if not isinstance(message, dict):
+ session = self._slots.get(message.slot)
+ if session is not None:
+ session._deliver_audio(message.pcm)
+ continue
kind = message.get("type")
if kind == "_exited":
await self._on_exit()
@@ -365,6 +395,12 @@ class _Engine:
if self.phase in ("ready", "failed"):
self._failures = 0 if self.phase == "ready" else self._failures
self._ready.set()
+ if self.phase == "failed":
+ # Retrying a failed self-test must create fresh native
+ # engines, not reuse the same unusable loaded process.
+ self._client = None
+ await client.close()
+ return
continue
session = self._sessions.get(str(message.get("session", "")))
if session is not None:
@@ -385,7 +421,12 @@ class _Engine:
session._deliver({"type": "_engine_exited"})
self._sessions.clear()
self._slots.clear()
- self._client = None
+ client, self._client = self._client, None
+ for task in (self._audio_router, self._load_watchdog):
+ if task is not None:
+ task.cancel()
+ if client is not None:
+ await client.close()
self._failures += 1
self.phase = "failed" if self._failures >= len(_RESTART_BACKOFF_S) else "stopped"
self.reason = self.reason or "The local voice engine stopped."
@@ -427,10 +468,18 @@ class _Engine:
self._slots.pop(session.slot, None)
async def stop(self) -> None:
+ current = asyncio.current_task()
+ for task in (self._starting, self._launching, self._load_watchdog):
+ if task is not None and task is not current and not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
client, self._client = self._client, None
for task in (self._router, self._audio_router):
if task is not None:
task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
if client is not None:
await client.close()
self.phase = "stopped"
@@ -591,7 +640,7 @@ class LocalVoiceProvider:
previous = cls._engine
if previous is None or previous.settings != settings:
cls._engine = _Engine(settings)
- if previous is not None and previous._client is not None:
+ if previous is not None:
# Changed settings (a new voice or model) start a new worker;
# the old one must not linger with its models loaded.
try:
@@ -634,7 +683,7 @@ class LocalVoiceProvider:
async def can_open_duplex_session(self) -> bool:
"""Answer at once from the worker's state; never wait for it to load.
- A call during warm-up hears why and roughly how long within a second
+ A call during warm-up hears why and where to see progress within a second
(plan section 4.9); the start itself runs in the background.
"""
settings = self._settings or EngineSettings.from_config(None)
@@ -652,9 +701,8 @@ class LocalVoiceProvider:
log.warning("local voice refused a call: %s", engine.reason or "engine failed")
self.duplex_unavailable_reason = refusal("failed", self.language)
else:
- eta_s = max(1, round((1.0 - engine.progress) * _WARM_LOAD_S))
self.duplex_unavailable_reason = refusal(
- "loading", self.language, percent=int(engine.progress * 100), eta=eta_s
+ "loading", self.language, percent=int(engine.progress * 100)
)
return False
diff --git a/jarvis/realtime/local_voice_setup.py b/jarvis/realtime/local_voice_setup.py
index 1a8ca847ce..072f9833e5 100644
--- a/jarvis/realtime/local_voice_setup.py
+++ b/jarvis/realtime/local_voice_setup.py
@@ -487,13 +487,16 @@ def _run_setup(deps: SetupDeps) -> None:
# ---------------------------------------------------------------- self-test
-def selftest_fingerprint(settings: Any) -> dict[str, str]:
+def selftest_fingerprint(settings: Any) -> dict[str, Any]:
"""What a self-test result is bound to; any change makes it stale (plan 4.10)."""
return {
"engine_version": engine_version(),
"requirements_sha256": requirements_sha256(),
"llm_model": str(getattr(settings, "llm_model", "")),
"tts": str(getattr(settings, "tts", "")),
+ "languages": list(getattr(settings, "languages", [])),
+ "tts_options": dict(getattr(settings, "tts_options", {})),
+ "llm_base_url": str(getattr(settings, "llm_base_url", "")),
}
@@ -579,6 +582,8 @@ def _live_state(engine: Any) -> tuple[str, str, float, str]:
if engine._client is None: # noqa: SLF001 - the adapter's own state, read-only
if engine.phase == "failed":
return "failed", "", 0.0, engine.reason
+ if engine.phase == "starting":
+ return "starting", engine.stage or "process", engine.progress, ""
return "stopped", "", 0.0, ""
if engine.phase == "ready":
return "ready", "", 1.0, ""
diff --git a/jarvis/voice_engine/client.py b/jarvis/voice_engine/client.py
index 3e44f50f49..ad856009f7 100644
--- a/jarvis/voice_engine/client.py
+++ b/jarvis/voice_engine/client.py
@@ -49,13 +49,17 @@ def worker_env(*, package_root: Path | None = None, home: Path | None = None,
class EngineClient:
def __init__(self, python: str, *, env: dict[str, str] | None = None,
- stderr_path: Path | None = None) -> None:
+ stderr_path: Path | None = None, ordered: bool = False) -> None:
self._python = python
self._env = env or worker_env()
self._stderr_path = stderr_path
+ # Live playback must see audio before the following response.done or
+ # interruption. The bench can still consume separate queues.
+ self._ordered = ordered
self._process: asyncio.subprocess.Process | None = None
self._reader_task: asyncio.Task[None] | None = None
- self.messages: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
+ self._close_task: asyncio.Task[int | None] | None = None
+ self.messages: asyncio.Queue[p.Frame] = asyncio.Queue()
self.audio_frames: asyncio.Queue[p.AudioFrame] = asyncio.Queue()
self._stderr_handle: Any = None
self._write_lock = asyncio.Lock()
@@ -65,17 +69,27 @@ class EngineClient:
return self._process.pid if self._process is not None else None
async def start(self, timeout_s: float = 30.0) -> dict[str, Any]:
+ self._close_task = None
if self._stderr_path is not None:
self._stderr_path.parent.mkdir(parents=True, exist_ok=True)
self._stderr_handle = self._stderr_path.open("ab")
- self._process = await asyncio.create_subprocess_exec(
- self._python, "-m", "jarvis.voice_engine.worker",
- stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
- stderr=self._stderr_handle or asyncio.subprocess.DEVNULL,
- env=self._env, creationflags=_NO_WINDOW,
- )
- self._reader_task = asyncio.get_running_loop().create_task(self._read())
- return await self.wait_for(lambda m: m["type"] == p.HELLO, timeout_s)
+ try:
+ self._process = await asyncio.create_subprocess_exec(
+ self._python, "-m", "jarvis.voice_engine.worker",
+ stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
+ stderr=self._stderr_handle or asyncio.subprocess.DEVNULL,
+ env=self._env, creationflags=_NO_WINDOW,
+ )
+ self._reader_task = asyncio.get_running_loop().create_task(self._read())
+ hello = await self.wait_for(lambda m: m["type"] == p.HELLO, timeout_s)
+ if hello.get("protocol") != p.PROTOCOL_VERSION:
+ raise p.ProtocolError("the voice engine uses an incompatible protocol")
+ return hello
+ except BaseException:
+ # Includes cancellation: a failed handshake must not leave a
+ # worker holding models or an open log handle behind.
+ await self.close()
+ raise
async def _read(self) -> None:
assert self._process is not None and self._process.stdout is not None
@@ -86,11 +100,11 @@ class EngineClient:
if not data:
break
for frame in reader.feed(data):
- if isinstance(frame, p.AudioFrame):
+ if isinstance(frame, p.AudioFrame) and not self._ordered:
self.audio_frames.put_nowait(frame)
else:
self.messages.put_nowait(frame)
- except p.ProtocolError as exc:
+ except (p.ProtocolError, OSError) as exc:
# A corrupt stream cannot be resynchronised; stop the worker so the
# caller sees an exit instead of waiting on a silent pipe.
log.error("voice engine sent an invalid frame: %s", exc)
@@ -118,17 +132,30 @@ class EngineClient:
async with asyncio.timeout(timeout_s):
while True:
message = await self.messages.get()
+ if not isinstance(message, dict):
+ continue
if message["type"] == EXITED:
raise RuntimeError("the voice engine exited")
if predicate(message):
return message
async def close(self, timeout_s: float = 5.0) -> int | None:
+ # A provider switch may cancel the router while it is reaping an
+ # exited/failed worker. All callers join one uncancellable cleanup.
+ if self._close_task is None:
+ self._close_task = asyncio.create_task(self._close(timeout_s))
+ return await asyncio.shield(self._close_task)
+
+ async def _close(self, timeout_s: float) -> int | None:
process = self._process
if process is None:
+ if self._stderr_handle is not None:
+ self._stderr_handle.close()
+ self._stderr_handle = None
return None
- with contextlib.suppress(RuntimeError, ConnectionError, OSError):
- await self.send({"type": p.SHUTDOWN})
+ with contextlib.suppress(RuntimeError, ConnectionError, OSError, TimeoutError):
+ async with asyncio.timeout(min(timeout_s, 1.0)):
+ await self.send({"type": p.SHUTDOWN})
if process.stdin is not None:
with contextlib.suppress(ConnectionError, OSError):
process.stdin.close()
@@ -139,7 +166,11 @@ class EngineClient:
code = await process.wait()
if self._reader_task is not None:
self._reader_task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await self._reader_task
+ self._reader_task = None
if self._stderr_handle is not None:
self._stderr_handle.close()
+ self._stderr_handle = None
self._process = None
return code
diff --git a/jarvis/voice_engine/runtime.py b/jarvis/voice_engine/runtime.py
index 95edec4996..fbc54f109d 100644
--- a/jarvis/voice_engine/runtime.py
+++ b/jarvis/voice_engine/runtime.py
@@ -119,7 +119,7 @@ def build_models(config: RuntimeConfig, progress: Progress) -> tuple[EngineModel
models = EngineModels(
vad_factory=lambda: SileroVad(vad_path), turn=turn, stt=stt, tts_for=tts_for, llm=llm
)
- progress("ready", 1.0)
+ progress("loaded", 0.9)
return models, {"load_s": timings, "voices": voice_kind, "llm": config.llm_model,
"errors": errors}
diff --git a/jarvis/voice_engine/worker.py b/jarvis/voice_engine/worker.py
index 60139ddbbb..bab705d300 100644
--- a/jarvis/voice_engine/worker.py
+++ b/jarvis/voice_engine/worker.py
@@ -218,7 +218,11 @@ class Worker:
return True
async def _configure(self, message: dict[str, Any]) -> None:
- from jarvis.voice_engine.runtime import RuntimeConfig, build_models # noqa: PLC0415
+ from jarvis.voice_engine.runtime import ( # noqa: PLC0415
+ RuntimeConfig,
+ build_models,
+ selftest,
+ )
loop = asyncio.get_running_loop()
config = RuntimeConfig.from_message(message)
@@ -229,6 +233,15 @@ class Worker:
self._state("loading", "start", 0.0)
try:
models, described = await asyncio.to_thread(build_models, config, progress)
+ self._state("loading", "selftest", 0.95)
+ report = await asyncio.to_thread(selftest, models, config.languages)
+ described["selftest"] = report
+ if not report.get("ok"):
+ log.warning("voice engine readiness self-test failed: %s", report)
+ self._state("failed", reason="The local voice loaded but its speech "
+ "self-test failed. Run setup again on the Local voice card.",
+ detail=described)
+ return
except Exception as exc:
log.exception("loading the voice engine failed")
self._state("failed", reason=f"The local voice could not load: {exc}")
diff --git a/tests/unit/voice_engine/test_client_lifecycle.py b/tests/unit/voice_engine/test_client_lifecycle.py
new file mode 100644
index 0000000000..089755bfcc
--- /dev/null
+++ b/tests/unit/voice_engine/test_client_lifecycle.py
@@ -0,0 +1,156 @@
+"""Failed starts release workers; live audio keeps its order on the wire."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from jarvis.voice_engine import protocol as p
+from jarvis.voice_engine.client import EngineClient
+
+
+class Pipe:
+ def __init__(self) -> None:
+ self.closed = False
+
+ def write(self, data: bytes) -> None:
+ pass # The fake worker never responds to shutdown: exercise forced cleanup.
+
+ async def drain(self) -> None:
+ pass
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class Process:
+ def __init__(self, wire: bytes = b"") -> None:
+ self.stdin = Pipe()
+ self.stdout = asyncio.StreamReader()
+ self.stdout.feed_data(wire)
+ self.returncode = None
+ self.pid = 123
+ self.killed = False
+ self.exited = asyncio.Event()
+
+ def kill(self) -> None:
+ self.killed = True
+ self.returncode = -1
+ self.stdout.feed_eof()
+ self.exited.set()
+
+ async def wait(self) -> int:
+ await self.exited.wait()
+ return self.returncode
+
+
+def install_process(monkeypatch: pytest.MonkeyPatch, process: Process) -> None:
+ async def spawn(*args, **kwargs):
+ return process
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
+
+
+async def test_handshake_timeout_and_cancellation_release_process_and_log(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ for cancel in (False, True):
+ process = Process()
+ install_process(monkeypatch, process)
+ client = EngineClient("fake", stderr_path=tmp_path / "worker.log")
+ original_close = client.close
+
+ async def close(original_close=original_close):
+ return await original_close(timeout_s=0.01)
+
+ monkeypatch.setattr(client, "close", close)
+ task = asyncio.create_task(client.start(timeout_s=0.02))
+ await asyncio.sleep(0)
+ if cancel:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError if cancel else TimeoutError):
+ await task
+ assert process.killed and process.stdin.closed
+ assert client._process is None and client._stderr_handle is None
+ assert client._reader_task is None
+
+
+async def test_spawn_error_closes_log(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ async def spawn(*args, **kwargs):
+ raise FileNotFoundError("missing interpreter")
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
+ client = EngineClient("missing", stderr_path=tmp_path / "worker.log")
+ with pytest.raises(FileNotFoundError):
+ await client.start()
+ assert client._stderr_handle is None
+
+
+async def test_live_frames_preserve_audio_completion_and_interrupt_order(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ done = {"type": "response.done", "session": "s"}
+ interrupted = {"type": "interrupted", "session": "s"}
+ process = Process(
+ p.encode_json({"type": "hello", "protocol": p.PROTOCOL_VERSION})
+ + p.encode_audio(1, 1, b"\x01\x00") + p.encode_json(done)
+ + p.encode_audio(1, 2, b"\x02\x00") + p.encode_json(interrupted))
+ install_process(monkeypatch, process)
+ client = EngineClient("fake", ordered=True)
+ try:
+ await client.start()
+ received = [await asyncio.wait_for(client.messages.get(), 1) for _ in range(4)]
+ assert received == [p.AudioFrame(1, 1, b"\x01\x00"), done,
+ p.AudioFrame(1, 2, b"\x02\x00"), interrupted]
+ assert client.audio_frames.empty()
+ finally:
+ await client.close(timeout_s=0.01)
+
+
+async def test_incompatible_worker_is_not_accepted(monkeypatch: pytest.MonkeyPatch) -> None:
+ process = Process(p.encode_json({"type": "hello", "protocol": 999}))
+ install_process(monkeypatch, process)
+ client = EngineClient("fake")
+ original_close = client.close
+
+ async def close():
+ return await original_close(timeout_s=0.01)
+
+ monkeypatch.setattr(client, "close", close)
+ with pytest.raises(p.ProtocolError, match="incompatible"):
+ await client.start()
+ assert process.killed and client._process is None
+
+
+async def test_broken_output_pipe_ends_the_worker(monkeypatch: pytest.MonkeyPatch) -> None:
+ process = Process()
+ process.stdout.set_exception(OSError("broken pipe"))
+ install_process(monkeypatch, process)
+ client = EngineClient("fake")
+ with pytest.raises(RuntimeError, match="exited"):
+ await client.start()
+ assert process.killed and client._process is None
+
+
+async def test_cancelling_one_closer_does_not_cancel_worker_cleanup(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ process = Process(p.encode_json({"type": "hello", "protocol": p.PROTOCOL_VERSION}))
+ install_process(monkeypatch, process)
+ client = EngineClient("fake")
+ await client.start()
+ closer = asyncio.create_task(client.close(timeout_s=0.02))
+ await asyncio.sleep(0)
+ closer.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await closer
+ await asyncio.wait_for(client.close(), 1)
+ assert process.killed and client._process is None and client._reader_task is None
diff --git a/tests/unit/voice_engine/test_local_voice_adapter.py b/tests/unit/voice_engine/test_local_voice_adapter.py
index 19ea7aa588..d263564cae 100644
--- a/tests/unit/voice_engine/test_local_voice_adapter.py
+++ b/tests/unit/voice_engine/test_local_voice_adapter.py
@@ -31,6 +31,7 @@ class FakeClient:
audio: list[tuple[int, int, bytes]] = field(default_factory=list)
messages: asyncio.Queue[dict[str, Any]] = field(default_factory=asyncio.Queue)
audio_frames: asyncio.Queue[AudioFrame] = field(default_factory=asyncio.Queue)
+ closed: bool = False
async def send(self, message: dict[str, Any]) -> None:
self.sent.append(message)
@@ -39,6 +40,7 @@ class FakeClient:
self.audio.append((slot, seq, pcm))
async def close(self) -> int:
+ self.closed = True
return 0
@@ -150,7 +152,8 @@ async def test_a_loading_engine_refuses_fast_with_its_progress() -> None:
try:
assert await provider.can_open_duplex_session() is False
assert "20 %" in provider.duplex_unavailable_reason
- assert "about 12 seconds" in provider.duplex_unavailable_reason
+ assert "progress" in provider.duplex_unavailable_reason
+ assert "seconds" not in provider.duplex_unavailable_reason
finally:
LocalVoiceProvider._engine = None
@@ -214,7 +217,8 @@ async def test_an_installed_engine_starts_in_the_background_and_answers_at_once(
assert await provider.can_open_duplex_session() is False
assert starts == [1] # joined, not started twice
assert "40 %" in provider.duplex_unavailable_reason
- assert "about 9 seconds" in provider.duplex_unavailable_reason
+ assert "progress" in provider.duplex_unavailable_reason
+ assert "seconds" not in provider.duplex_unavailable_reason
finally:
gate.set()
LocalVoiceProvider._engine = None
@@ -326,3 +330,97 @@ def test_the_model_comes_from_the_card_then_setup_then_the_default(tmp_path: Pat
assert EngineSettings.from_config(cfg).llm_model == "qwen3.5:2b"
typed = JarvisConfig(voice_engine=VoiceEngineConfig(tts="nonsense", languages=[]))
assert (typed.voice_engine.tts, typed.voice_engine.languages) == ("pocket", ["de", "en"])
+
+
+async def test_ordered_audio_reaches_the_session_before_turn_complete() -> None:
+ engine, client = await _running_engine()
+ session = await engine.open(LocalVoiceProvider(_settings()), SimpleNamespace(language="en"))
+ client.messages.put_nowait(AudioFrame(session.slot, 1, b"\x01\x00"))
+ client.messages.put_nowait({"type": "response.done", "session": session.session_id})
+ try:
+ events = session.receive()
+ assert (await asyncio.wait_for(anext(events), 1)).type == "audio_delta"
+ assert (await asyncio.wait_for(anext(events), 1)).type == "turn_complete"
+ finally:
+ await session.close()
+ await engine.stop()
+
+
+async def test_stalled_loading_is_failed_and_releases_the_worker(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis.plugins.realtime import local_voice
+
+ monkeypatch.setattr(local_voice, "_READY_TIMEOUT_S", 0.01)
+ engine = _Engine(_settings())
+ client = FakeClient()
+ engine._client = client
+ engine.phase, engine.stage = "loading", "tts:en"
+ engine._load_watchdog = asyncio.create_task(engine._watch_loading(client))
+ await asyncio.wait_for(engine._load_watchdog, 1)
+ assert engine.phase == "failed" and "tts:en" in engine.reason
+ assert engine._client is None and client.closed
+ assert not await engine.wait_ready(0.01)
+ engine.reset_failures()
+ assert engine.phase == "stopped"
+
+
+async def test_failed_readiness_releases_worker_so_retry_can_start_fresh() -> None:
+ engine = _Engine(_settings())
+ client = FakeClient()
+ engine._client = client
+ router = asyncio.create_task(engine._route_messages(client))
+ client.messages.put_nowait({"type": "state", "phase": "failed", "reason": "No speech"})
+ await asyncio.wait_for(router, 1)
+ assert engine.phase == "failed" and engine.reason == "No speech"
+ assert client.closed and engine._client is None
+ engine.reset_failures()
+ assert engine.phase == "stopped"
+
+
+async def test_stop_cancels_start_before_it_can_leave_a_worker_behind() -> None:
+ engine = _Engine(_settings())
+ entered = asyncio.Event()
+ cancelled = asyncio.Event()
+
+ async def start():
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ cancelled.set()
+
+ engine.ensure_started = start
+ engine.start_soon()
+ await entered.wait()
+ await engine.stop()
+ assert cancelled.is_set() and engine._starting.done()
+ assert engine.phase == "stopped"
+
+
+async def test_stop_also_cancels_a_direct_prespawn_handshake(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis.voice_engine import client as client_module
+
+ entered = asyncio.Event()
+ client = FakeClient()
+
+ async def start():
+ entered.set()
+ await asyncio.Event().wait()
+
+ client.start = start
+ monkeypatch.setattr(client_module, "EngineClient", lambda *args, **kwargs: client)
+ settings = EngineSettings(python="fake", home=str(tmp_path), package_root=None)
+ engine = _Engine(settings)
+ launch = asyncio.create_task(engine.ensure_started())
+ await entered.wait()
+ await engine.stop()
+ assert launch.cancelled() and client.closed
+ assert engine._client is None and engine.phase == "stopped"
diff --git a/tests/unit/voice_engine/test_local_voice_setup.py b/tests/unit/voice_engine/test_local_voice_setup.py
index da987f2233..cb5d8b0646 100644
--- a/tests/unit/voice_engine/test_local_voice_setup.py
+++ b/tests/unit/voice_engine/test_local_voice_setup.py
@@ -231,3 +231,22 @@ def test_a_stored_selftest_goes_stale_when_the_model_changes(_isolated_home: Pat
assert moved["stale"] is True
raw = json.loads((_isolated_home / "selftest.json").read_text(encoding="utf-8"))
assert raw["fingerprint"]["engine_version"] == setup.engine_version()
+
+
[email protected]("field,value", [
+ ("languages", ["en"]), ("tts_options", {"voice": "other"}),
+ ("llm_base_url", "http://127.0.0.1:11435"),
+])
+def test_changed_speech_or_server_settings_invalidate_a_selftest(
+ _isolated_home: Path, field: str, value,
+) -> None:
+ settings = SimpleNamespace(llm_model="qwen3.5:4b", tts="pocket", languages=["de", "en"],
+ tts_options={}, llm_base_url="http://127.0.0.1:11434")
+ setup.save_selftest(_isolated_home, {"ok": True}, settings)
+ setattr(settings, field, value)
+ assert setup.load_selftest(_isolated_home, settings)["stale"] is True
+
+
+def test_process_handshake_is_visible_as_starting() -> None:
+ engine = SimpleNamespace(_client=None, phase="starting", stage="process", progress=0.0)
+ assert setup._live_state(engine) == ("starting", "process", 0.0, "")
diff --git a/tests/unit/voice_engine/test_worker_readiness.py b/tests/unit/voice_engine/test_worker_readiness.py
new file mode 100644
index 0000000000..442373c61b
--- /dev/null
+++ b/tests/unit/voice_engine/test_worker_readiness.py
@@ -0,0 +1,45 @@
+"""A successfully loaded model is not yet a proven voice."""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.voice_engine import protocol as p
+from jarvis.voice_engine import runtime
+from jarvis.voice_engine.worker import Worker
+
+
+class Transport:
+ def __init__(self) -> None:
+ self.messages = []
+
+ def send(self, data: bytes) -> None:
+ self.messages.extend(p.FrameReader().feed(data))
+
+
[email protected]("verdict", ["pass", "fail", "raise"])
+async def test_ready_requires_a_real_speech_and_llm_selftest(
+ verdict: str, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ models = object()
+
+ def build(config, progress):
+ return models, {"voices": {"en": "piper"}}
+
+ def selftest(actual, languages):
+ assert actual is models and languages == ["en"]
+ if verdict == "raise":
+ raise RuntimeError("empty voice output")
+ return {"ok": verdict == "pass"}
+
+ monkeypatch.setattr(runtime, "build_models", build)
+ monkeypatch.setattr(runtime, "selftest", selftest)
+ transport = Transport()
+ worker = Worker(transport)
+ await worker._configure({"type": "configure", "languages": ["en"]})
+ states = [m for m in transport.messages if m["type"] == "state"]
+ assert states[-2]["stage"] == "selftest"
+ assert states[-1]["phase"] == ("ready" if verdict == "pass" else "failed")
+ assert (worker._models is models) == (verdict == "pass")
+ assert ("ready" in [m["phase"] for m in states]) == (verdict == "pass")