Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(voice): play the ack preamble during the think gap, never after the answer
Ruben Lütke3c3750266514
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.pyindex b1cbcd1f41..d717a634b4 100644--- a/jarvis/audio/player.py+++ b/jarvis/audio/player.py@@ -11,7 +11,7 @@ from __future__ import annotationsimport asyncioimport loggingimport time-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Callablefrom typing import TYPE_CHECKING, Anyimport numpy as np@@ -583,9 +583,20 @@ class AudioPlayer:except Exception: # noqa: BLE001pass- async def play_chunks(self, chunks: AsyncIterator[AudioChunk]) -> None:+ async def play_chunks(+ self,+ chunks: AsyncIterator[AudioChunk],+ *,+ should_play: Callable[[], bool] | None = None,+ ) -> None:"""Stream TTS chunks into a persistent WASAPI OutputStream.+ ``should_play`` is an optional staleness predicate evaluated ONCE right+ after the play lock is acquired (and before any audio is written). When+ it returns False the playback is dropped silently — the ack preamble+ uses this so it is never voiced once the main answer has started+ speaking (2026-06-20 'preamble after the answer' defense-in-depth).+History — what went wrong before:* First version: ``sd.play(blocking=True)`` **per chunk** — each20 ms fragment tore down and rebuilt the WASAPI stream completely.@@ -623,7 +634,40 @@ class AudioPlayer:# visible to the watchdog).self.last_write_ns = 0self.frames_written = 0+ # Lazy lock acquisition (2026-06-20 'preamble spoken AFTER the answer'):+ # pull the first NON-EMPTY chunk BEFORE taking the play lock. The+ # streaming answer's play task is created at turn-start and, on a long+ # tool turn, blocks for seconds waiting for its first audio chunk while+ # the brain runs the tool. Grabbing the lock up front held the device+ # idle for that whole gap, so a concurrently-published ack preamble+ # blocked behind the still-silent answer and was voiced AFTER it. Pulling+ # the first chunk first means the lock is held ONLY for real playback —+ # the preamble can play during the gap. ``last_write_ns`` stays 0 through+ # this pre-lock wait, preserving the BUG-032 "no first frame yet"+ # watchdog invariant.+ chunk_aiter = chunks.__aiter__()+ first_chunk: AudioChunk | None = None+ while True:+ try:+ candidate = await chunk_aiter.__anext__()+ except StopAsyncIteration:+ return # producer yielded nothing — nothing to play+ if candidate.pcm:+ first_chunk = candidate+ break++ async def _from_first() -> AsyncIterator[AudioChunk]:+ if first_chunk is not None:+ yield first_chunk+ async for _c in chunk_aiter:+ yield _c+async with self._get_play_lock():+ # Staleness gate: re-check at the last moment before any audio is+ # written. A preamble whose synthesis / lock-wait was overtaken by+ # the main answer is dropped here rather than queued behind it.+ if should_play is not None and not should_play():+ returndef _ensure_stream(needed_rate: int) -> tuple[sd.OutputStream, int]:# Reuse the persistent OutputStream across sentence-by-sentence# play_chunks() calls — closing+reopening per sentence is what@@ -689,7 +733,7 @@ class AudioPlayer:# NOTE: no finally-close — the stream stays open across play_chunks# calls and is only torn down by stop() (barge-in) or by the next# _ensure_stream call that observes a sample-rate mismatch.- async for chunk in chunks:+ async for chunk in _from_first():if not chunk.pcm:continueif pending_rate is not None and chunk.sample_rate != pending_rate:diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex f7fa839919..969b487a1a 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -2367,6 +2367,25 @@ class SpeechPipeline:event.text[:80],)return+ # A preamble ("I'm about to think about this") is only coherent BEFORE+ # the answer is voiced. If the turn is already JARVIS_SPEAKING by the+ # time it reaches the handler, the answer (or another readback) is being+ # spoken right now, so the preamble is stale → drop it instead of+ # queueing it behind the answer on the shared player (live bug+ # 2026-06-20: the ack "Ich schaue mir jetzt …" played AFTER the tool+ # result). The floor guard above only covers the USER holding the floor;+ # this covers Jarvis already speaking. The remaining race — the answer+ # starting DURING the preamble's synthesis / play-lock wait — is caught+ # by the should_play predicate handed to play_chunks below.+ if is_preamble and (+ getattr(self, "_turn_state", TurnTakingState.IDLE)+ is TurnTakingState.JARVIS_SPEAKING+ ):+ log.info(+ "Preamble dropped — Jarvis already speaking the answer: %r",+ event.text[:80],+ )+ returnif event.priority == "interrupt":# Arm the quiet window BEFORE TTS so a synchronous publish of a# preamble immediately afterwards sees the up-to-date timestamp.@@ -2435,7 +2454,27 @@ class SpeechPipeline:chunks = self._tts.synthesize(scrubbed.cleaned, language_code=lang_code)except TypeError:chunks = self._tts.synthesize(scrubbed.cleaned)- await self._player.play_chunks(chunks)+ if is_preamble:+ # Staleness gate evaluated by the player right before it writes+ # audio: if the answer has started speaking by the time the+ # preamble's synthesis + play-lock wait completes, drop it so it+ # is never voiced after the answer (2026-06-20 misorder fix).+ # TypeError fallback mirrors the synthesize() compat shim above:+ # an older player / test fake without the should_play kwarg still+ # plays (the synchronous JARVIS_SPEAKING guard already covers the+ # already-speaking case; only the in-flight race is then uncovered).+ try:+ await self._player.play_chunks(+ chunks,+ should_play=lambda: (+ getattr(self, "_turn_state", TurnTakingState.IDLE)+ is not TurnTakingState.JARVIS_SPEAKING+ ),+ )+ except TypeError:+ await self._player.play_chunks(chunks)+ else:+ await self._player.play_chunks(chunks)except Exception as exc: # noqa: BLE001log.warning("Announcement-Speak fehlgeschlagen: %s", exc)finally:diff --git a/tests/unit/audio/test_player_lock.py b/tests/unit/audio/test_player_lock.pyindex dc57d9163b..f64fd8d4ad 100644--- a/tests/unit/audio/test_player_lock.py+++ b/tests/unit/audio/test_player_lock.py@@ -161,3 +161,104 @@ async def test_real_play_chunks_holds_lock_while_streaming(monkeypatch) -> None:# serial execution.assert enter_count >= 2assert enter_count == exit_count+++async def _gated_chunk(+ gate: asyncio.Event, pcm: bytes+) -> AsyncIterator[AudioChunk]:+ """A producer that yields NOTHING until ``gate`` is set — mimics the+ streaming answer whose brain is still thinking / running a tool, so its+ ``_merged_chunks`` blocks on the sentence queue with no audio yet."""+ await gate.wait()+ yield AudioChunk(pcm=pcm, sample_rate=24_000, timestamp_ns=0, channels=1)+++async def test_play_chunks_does_not_hold_lock_while_awaiting_first_chunk(+ monkeypatch,+) -> None:+ """Regression (2026-06-20 'preamble spoken AFTER the answer'): the answer's+ ``play_chunks(_merged_chunks())`` task is created at turn-start and, on a+ long tool turn, waits seconds for its first audio chunk. It must NOT hold+ the play lock during that wait — otherwise a concurrently-published ack+ preamble blocks behind the still-silent answer and is voiced AFTER it+ (player.py:626 grabbed the lock before pulling the first chunk).++ Contract: while a producer is still awaiting its first chunk, a second+ ``play_chunks`` call can acquire the lock and play to completion.+ """+ player, _ = _make_player_with_recorded_inner(monkeypatch)+ writes: list[str] = []++ real_to_thread = asyncio.to_thread++ async def rec_to_thread(func, *args, **kw):+ if func is player._write_samples:+ writes.append("preamble-write")+ return None+ return await real_to_thread(func, *args, **kw)++ monkeypatch.setattr("jarvis.audio.player.asyncio.to_thread", rec_to_thread)++ gate = asyncio.Event()+ # The "answer" produces no audio until the gate opens.+ answer_task = asyncio.create_task(+ player.play_chunks(_gated_chunk(gate, b"\x09\x00" * 4000))+ )+ # Let the answer task start and (under the bug) seize the lock.+ await asyncio.sleep(0.02)++ # The preamble must be able to play NOW, while the answer is still silent.+ # Under the bug this deadlocks (the answer holds the lock and never+ # releases because its gate is closed) → wait_for raises TimeoutError.+ try:+ await asyncio.wait_for(+ player.play_chunks(_one_chunk(b"\x01\x00" * 4000)), timeout=1.0+ )+ except TimeoutError:+ gate.set()+ await answer_task+ pytest.fail(+ "preamble blocked behind the still-silent answer — play lock held "+ "while awaiting the first chunk"+ )++ assert writes, "the preamble produced no audio while the answer was silent"++ # Release the answer and let it finish cleanly.+ gate.set()+ await answer_task+++async def test_play_chunks_should_play_predicate_drops_stale_playback(+ monkeypatch,+) -> None:+ """A caller may pass ``should_play``; evaluated AFTER the lock is acquired,+ a False verdict drops the playback without writing. This is the staleness+ gate the ack preamble uses so it is never voiced once the answer has+ started speaking (defense-in-depth for the 2026-06-20 misorder)."""+ player, _ = _make_player_with_recorded_inner(monkeypatch)+ writes: list[str] = []++ real_to_thread = asyncio.to_thread++ async def rec_to_thread(func, *args, **kw):+ if func is player._write_samples:+ writes.append("w")+ return None+ return await real_to_thread(func, *args, **kw)++ monkeypatch.setattr("jarvis.audio.player.asyncio.to_thread", rec_to_thread)++ # Stale: should_play() is False → no audio written.+ await player.play_chunks(+ _one_chunk(b"\x01\x00" * 4000), should_play=lambda: False+ )+ assert writes == [], "a stale playback wrote audio instead of being dropped"++ # Valid: should_play() is True → audio written normally.+ await player.play_chunks(+ _one_chunk(b"\x01\x00" * 4000), should_play=lambda: True+ )+ assert writes, "a valid playback was dropped"diff --git a/tests/unit/speech/test_announcement_user_speaking_guard.py b/tests/unit/speech/test_announcement_user_speaking_guard.pyindex cd233a1045..0cd43ccb3b 100644--- a/tests/unit/speech/test_announcement_user_speaking_guard.py+++ b/tests/unit/speech/test_announcement_user_speaking_guard.py@@ -53,8 +53,20 @@ class FakeTTS:class FakePlayer:stop_calls: int = 0plays: int = 0+ last_should_play: object = None- async def play_chunks(self, chunks: AsyncIterator[AudioChunk]) -> None:+ async def play_chunks(+ self,+ chunks: AsyncIterator[AudioChunk],+ *,+ should_play=None,+ ) -> None:+ self.last_should_play = should_play+ # Mirror the real player: a False staleness verdict drops the playback.+ if should_play is not None and not should_play():+ async for _ in chunks:+ pass+ returnself.plays += 1async for _ in chunks:pass@@ -176,6 +188,64 @@ async def test_background_completion_while_user_speaking_is_deferred() -> None:assert tts.calls and "Fertig" in tts.calls[0][0]+async def test_preamble_while_jarvis_speaking_is_dropped() -> None:+ """Regression (2026-06-20 'Ich schaue mir jetzt …' spoken AFTER the answer):+ a preamble that reaches the handler once the answer is already being voiced+ (``JARVIS_SPEAKING``) is stale and must be dropped — never queued behind the+ answer. The pre-existing floor guard only covered USER_SPEAKING/LISTENING;+ JARVIS_SPEAKING (the answer's own playback) was the missing case."""+ bus = EventBus()+ tts = FakeTTS()+ player = FakePlayer()+ pipeline = _make_pipeline(tts, bus, player)+ pipeline._turn_state = TurnTakingState.JARVIS_SPEAKING # type: ignore[attr-defined]++ await bus.publish(+ AnnouncementRequested(+ text="Ich schaue mir jetzt die GitHub-CLI-Repositories an.",+ language="de",+ priority="normal",+ kind="preamble",+ )+ )++ assert tts.calls == [], "a stale preamble spoke after the answer started"+ assert player.plays == 0+++async def test_preamble_during_processing_carries_staleness_gate() -> None:+ """While the brain is still thinking (``PROCESSING``) the preamble plays —+ AND it is handed a ``should_play`` predicate so the player drops it if the+ answer overtakes it during synthesis / the play-lock wait (the race the+ lazy play-lock fix narrows but does not eliminate)."""+ bus = EventBus()+ tts = FakeTTS()+ player = FakePlayer()+ pipeline = _make_pipeline(tts, bus, player)+ pipeline._turn_state = TurnTakingState.PROCESSING # type: ignore[attr-defined]++ await bus.publish(+ AnnouncementRequested(+ text="Ich prüfe gerade den Google-Cloud-Status über die CLI.",+ language="de",+ priority="normal",+ kind="preamble",+ )+ )++ assert player.plays == 1, "the preamble should play during the thinking gap"+ pred = player.last_should_play+ assert callable(pred), "a preamble must carry a staleness predicate"+ # Still thinking → valid.+ assert pred() is True+ # The answer starts voicing mid-flight → the predicate now reports stale,+ # so the player would drop the still-unplayed preamble.+ pipeline._turn_state = TurnTakingState.JARVIS_SPEAKING # type: ignore[attr-defined]+ assert pred() is False++@pytest.mark.asyncioasync def test_announcement_while_idle_is_unaffected() -> None:"""Regression guard: the guard only arms while the user holds the floor."""