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(speech,audio): spoken-emit + TTS pipeline overlap updates
Ruben Lütkeb0402fb7aee9
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.pyindex cf17db6afb..e198e572c0 100644--- a/jarvis/audio/player.py+++ b/jarvis/audio/player.py@@ -769,8 +769,13 @@ class AudioPlayer:chunks: AsyncIterator[AudioChunk],*,should_play: Callable[[], bool] | None = None,- ) -> None:- """Stream TTS chunks into a persistent WASAPI OutputStream.+ ) -> bool:+ """Stream TTS chunks into a persistent output stream.++ Return ``True`` only when at least one PCM frame was accepted by the+ device stream. A producer that yields no audio, or a stale playback+ rejected by ``should_play``, returns ``False``. Callers use this receipt+ to keep the audible transcript free of text that never reached output.``should_play`` is an optional staleness predicate evaluated ONCE rightafter the play lock is acquired (and before any audio is written). When@@ -835,7 +840,7 @@ class AudioPlayer:try:candidate = await chunk_aiter.__anext__()except StopAsyncIteration:- return # producer yielded nothing — nothing to play+ return False # producer yielded nothingif candidate.pcm:first_chunk = candidatebreak@@ -851,7 +856,7 @@ class AudioPlayer:# 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():- return+ return Falsedef _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@@ -927,6 +932,7 @@ class AudioPlayer:pending.extend(chunk.pcm)await _flush_pending()await _flush_pending(final=True)+ return self.frames_written > 0def abort_active(self) -> None:"""Force-abort the live OutputStream to unblock a wedged ``stream.write``.diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex a795bcd8bc..94a9804d99 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -92,6 +92,7 @@ from jarvis.sessions.constants import (SPOKEN_KIND_PREAMBLE,SPOKEN_KIND_PRIVACY,SPOKEN_KIND_PROGRESS,+ SPOKEN_KIND_REPLY,SPOKEN_KIND_STT_UNAVAILABLE,SPOKEN_KIND_SUBAGENT,SPOKEN_KIND_TIMEOUT,@@ -3305,12 +3306,6 @@ class SpeechPipeline:# ``detail`` carries an optional technical diagnostic (e.g. a failed# Computer-Use exit code + harness reason) that is NOT spoken but is# surfaced in the transcript for debugging.- self._emit_spoken(- scrubbed.cleaned,- ann_lang,- _announcement_spoken_kind(getattr(event, "kind", None)),- getattr(event, "detail", None),- )# A finished sub-agent / mission readback (completion / subagent) hands# the floor BACK to the user — drive the UI/orb into SPEAKING for its# duration so the mascot animates. The out-of-band announcement path@@ -3344,7 +3339,7 @@ class SpeechPipeline:# 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(+ playback_result = await self._player.play_chunks(chunks,should_play=lambda: (getattr(self, "_turn_state", TurnTakingState.IDLE)@@ -3352,9 +3347,16 @@ class SpeechPipeline:),)except TypeError:- await self._player.play_chunks(chunks)+ playback_result = await self._player.play_chunks(chunks)else:- await self._player.play_chunks(chunks)+ playback_result = await self._player.play_chunks(chunks)+ if self._playback_confirmed(playback_result):+ self._emit_spoken(+ scrubbed.cleaned,+ ann_lang,+ _announcement_spoken_kind(getattr(event, "kind", None)),+ getattr(event, "detail", None),+ )except Exception as exc: # noqa: BLE001log.warning("Announcement-Speak fehlgeschlagen: %s", exc)finally:@@ -3672,7 +3674,6 @@ class SpeechPipeline:# through this background path, not _speak, so it would otherwise be# invisible in the Transcription view. Tagged ``subagent`` so it renders# on the attributed "Jarvis Sub-Agent / Output" track.- self._emit_spoken(cleaned, lang, SPOKEN_KIND_SUBAGENT)# Re-arm the readback grace exactly like ``_on_announcement`` (:2386): a# background result delivered through THIS direct path also hands the# floor back to the user, so ``_active_session`` must keep the mic open@@ -3696,7 +3697,9 @@ class SpeechPipeline:chunks = self._tts.synthesize(cleaned, language_code=self._bcp47(lang))except TypeError:chunks = self._tts.synthesize(cleaned)- await self._player.play_chunks(chunks)+ playback_result = await self._player.play_chunks(chunks)+ if self._playback_confirmed(playback_result):+ self._emit_spoken(cleaned, lang, SPOKEN_KIND_SUBAGENT)except Exception as exc: # noqa: BLE001log.warning("Background-completed Voice-Ansage failed: %s", exc)finally:@@ -6193,7 +6196,9 @@ class SpeechPipeline:)except TypeError:chunks = self._tts.synthesize(cleaned)- await self._player.play_chunks(chunks)+ playback_result = await self._player.play_chunks(chunks)+ if self._playback_confirmed(playback_result):+ self._emit_spoken(cleaned, language, SPOKEN_KIND_REPLY)except Exception as exc: # noqa: BLE001 -- final voice fallbacklog.warning("Realtime surface TTS fallback failed: %s",@@ -8375,27 +8380,33 @@ class SpeechPipeline:finally:await channel.put(None)- async def _merged_chunks() -> AsyncIterator[AudioChunk]:- """Drain per-sentence channels FIFO into one continuous stream.+ async def _play_sentences() -> None:+ """Play synthesized sentences FIFO and commit confirmed text.++ The built-in player keeps its device stream open across calls, so a+ per-sentence receipt preserves voice continuity while providing an+ exact text unit for the audible transcript.+ """+ async def _sentence_chunks(+ source: asyncio.Queue,+ ) -> AsyncIterator[AudioChunk]:+ while True:+ chunk = await source.get()+ if chunk is None:+ return+ self._brain_first_frame_played = True+ yield chunk- FIFO over ``sentence_channels`` guarantees audio plays in sentence- order regardless of which synthesis task finishes first — the key- single-voice-continuity invariant (never as_completed)."""while True:- channel = await sentence_channels.get()+ item = await sentence_channels.get()try:- if channel is None:- return # end-of-turn sentinel- while True:- chunk = await channel.get()- if chunk is None:- break- # First real audio chunk reaches the player: the thinking- # phase is over, so the thinking-interrupt monitor in- # _run_brain_with_stall_guard stands down and the- # per-playback barge monitor takes over interruption.- self._brain_first_frame_played = True- yield chunk+ if item is None:+ return+ channel, sentence = item++ result = await self._player.play_chunks(_sentence_chunks(channel))+ if self._playback_confirmed(result):+ self._emit_spoken(sentence, lang, SPOKEN_KIND_REPLY)finally:sentence_channels.task_done()@@ -8421,7 +8432,7 @@ class SpeechPipeline:asyncio.create_task(_synth_into(channel, cleaned), name="tts-synth"))# Blocks once ``lookahead`` channels are outstanding — back-pressure.- await sentence_channels.put(channel)+ await sentence_channels.put((channel, cleaned))async def _produce() -> None:nonlocal sentence_buffer, paraphrase_stripped, brain_first_token_marked@@ -8504,9 +8515,7 @@ class SpeechPipeline:await sentence_channels.put(None)produce_task = asyncio.create_task(_produce(), name="tts-produce-turn")- play_task = asyncio.create_task(- self._player.play_chunks(_merged_chunks()), name="tts-play-turn"- )+ play_task = asyncio.create_task(_play_sentences(), name="tts-play-turn")barge_task = asyncio.create_task(self._barge_monitor(), name="barge-monitor-turn")# Hangup is the hard kill-switch ("auflegen"): when the user hangs up# MID-TURN, ``_player.stop()`` alone does not free this wait — a tool-use@@ -9347,21 +9356,14 @@ class SpeechPipeline:kind: str,detail: str | None = None,) -> None:- """Announce a VOICED phrase on the bus as a ``SpeechSpoken`` event.-- The Transcription log was previously blind to everything Jarvis speaks- except the brain's normal reply (recorded via ``ResponseGenerated`` ->- ``jarvis_text``). This publishes every OTHER voiced phrase so the- passive ``SessionRecorder`` can document it in the transcript.-- Fire-and-forget (``asyncio.create_task``), mirroring the- ``LatencyTurnComplete`` telemetry emit — the voice hot path never waits- on the bus dispatch (AP-9 / AD-OE2). The ``reply`` sentinel is dropped- because the reply is already in the transcript; empty text and a- missing bus are no-ops, and every error is swallowed so a telemetry- hiccup can never break a turn.+ """Publish one playback-confirmed phrase to the audible transcript.++ Callers own the playback receipt and invoke this only after audio was+ accepted. Normal replies and supplemental phrases share this event.+ Publishing remains fire-and-forget so the passive recorder cannot add+ latency to the voice path. Empty text and a missing bus are no-ops."""- if kind == "reply" or not text or not text.strip():+ if not text or not text.strip():returnbus = getattr(self, "_bus", None)if bus is None:@@ -9378,6 +9380,17 @@ class SpeechPipeline:except Exception: # noqa: BLE001 — telemetry must never break the turnlog.debug("SpeechSpoken emit failed", exc_info=True)+ def _playback_confirmed(self, result: object) -> bool:+ """Interpret a player receipt without breaking compatible older players.++ The built-in player returns an explicit boolean. Older compatible+ players returned ``None`` after successful consumption, so only those+ non-built-in implementations retain the legacy success interpretation.+ """+ if isinstance(self._player, AudioPlayer):+ return result is True+ return result is not False+#: Spoken readback for an OpenClaw background task that finished off the#: chat path. de/en/es so the readback follows the conversation language#: instead of a hardcoded German literal (forensic 2026-06-23). German@@ -9453,11 +9466,9 @@ class SpeechPipeline:und an TTS übergeben (voice bleibt gleich — Gemini-Voices sindsprachagnostisch).- ``kind`` tags WHAT is being voiced for the Transcription log. The- default ``"reply"`` is the ordinary brain answer (already documented as- ``jarvis_text``, so not re-recorded); a canned phrase passes its- specific kind (``"timeout"``, ``"clarify"``, ``"privacy"`` …) and is- published as a ``SpeechSpoken`` event via ``_emit_spoken``.+ ``kind`` tags what is being voiced for the Transcription log. The+ default ``"reply"`` is the ordinary brain answer; canned phrases pass+ their specific kind. Both are published only after playback succeeds.Parallel zum Playback läuft ``_barge_monitor`` auf einer separatenMic-Instanz. Erkennt Silero-VAD dort User-Sprache (Threshold 0.8,@@ -9490,7 +9501,6 @@ class SpeechPipeline:# Document the voiced phrase in the session log (no-op for the reply# sentinel and empty text). After the mute check, so a suppressed# phrase — which is never actually voiced — is not recorded.- self._emit_spoken(text, language, kind)# Track that the assistant has spoken at least once in this session.# Used by _emit_completeness_signal to pick earcon vs. spoken cue.self._session_has_assistant_spoken = True@@ -9563,6 +9573,13 @@ class SpeechPipeline:await texcept (asyncio.CancelledError, Exception):pass+ if (+ play_task.done()+ and not play_task.cancelled()+ and play_task.exception() is None+ and self._playback_confirmed(play_task.result())+ ):+ self._emit_spoken(text, language, kind)if not barged:self._suppress_session_input_after_tts("response")return bargeddiff --git a/tests/unit/speech/test_spoken_emit.py b/tests/unit/speech/test_spoken_emit.pyindex e8aac6498d..3a2903c7b8 100644--- a/tests/unit/speech/test_spoken_emit.py+++ b/tests/unit/speech/test_spoken_emit.py@@ -1,14 +1,15 @@-"""Every voiced phrase that is NOT the brain's normal reply must be announced-on the bus as a ``SpeechSpoken`` event, so the SessionRecorder can document it-in the Transcription log (user report 2026-06-15).+"""Every playback-confirmed phrase must be announced as ``SpeechSpoken``.++The SessionRecorder uses this authoritative audible track for normal replies+and supplemental output alike.Two seams are under test:- ``_emit_spoken(text, language, kind)`` — the fire-and-forget publish helper.- It suppresses the ``reply`` sentinel (the normal reply is already captured as- ``jarvis_text``) and empty text, and never raises when there is no bus.+ It accepts playback-confirmed replies, suppresses empty text, and never raises+ when there is no bus.- ``_speak(..., kind=...)`` — the universal non-streaming speak chokepoint.- A canned phrase (kind != "reply") emits; a plain reply (default) does not.+ It emits canned phrases and normal replies only after playback succeeds.- ``_announcement_spoken_kind`` — maps an ``AnnouncementRequested.kind`` to thespoken-track tag."""@@ -26,7 +27,6 @@ from jarvis.core.protocols import AudioChunkfrom jarvis.sessions.constants import SPOKEN_KINDSfrom jarvis.speech.pipeline import SpeechPipeline, _announcement_spoken_kind-# --- minimal __new__ pipe for the pure _emit_spoken helper -----------------@@ -64,9 +64,7 @@ async def test_emit_spoken_publishes_for_nonreply_kind() -> None:@pytest.mark.asyncio-async def test_emit_spoken_skips_the_reply_sentinel() -> None:- # The normal brain reply is already recorded via jarvis_text — re-emitting- # it would double-document the conversational turn.+async def test_emit_spoken_publishes_playback_confirmed_reply() -> None:bus = EventBus()captured = await _capture(bus)pipe = _bare_pipe(bus)@@ -74,7 +72,9 @@ async def test_emit_spoken_skips_the_reply_sentinel() -> None:pipe._emit_spoken("Hello, how can I help?", "de", "reply")await asyncio.sleep(0.05)- assert captured == []+ assert len(captured) == 1+ assert captured[0].spoken_kind == "reply"+ assert captured[0].text == "Hello, how can I help?"@pytest.mark.asyncio@@ -134,6 +134,17 @@ class _CompletingPlayer:pass+@dataclass+class _DroppingPlayer:+ async def play_chunks(self, chunks: AsyncIterator[AudioChunk]) -> bool:+ async for _chunk in chunks:+ pass+ return False++ def stop(self) -> None:+ pass++def _make_speak_pipeline(bus: EventBus) -> SpeechPipeline:pipeline = SpeechPipeline(tts=_OneShotTTS(), bus=bus, enable_whisper_wake=False)pipeline._player = _CompletingPlayer() # type: ignore[assignment]@@ -162,15 +173,30 @@ async def test_speak_emits_spoken_for_a_canned_kind() -> None:@pytest.mark.asyncio-async def test_speak_default_reply_does_not_emit_spoken() -> None:+async def test_speak_default_reply_emits_after_playback() -> None:bus = EventBus()captured = await _capture(bus)pipeline = _make_speak_pipeline(bus)- # Default kind is the reply sentinel — the main brain reply path.+ # The normal reply now joins the authoritative audible transcript track.await pipeline._speak("Hello, how can I help?", language="de")await asyncio.sleep(0.05)+ assert len(captured) == 1+ assert captured[0].spoken_kind == "reply"+ assert captured[0].text == "Hello, how can I help?"+++async def test_speak_does_not_record_audio_rejected_by_player() -> None:+ bus = EventBus()+ captured = await _capture(bus)+ pipeline = _make_speak_pipeline(bus)+ pipeline._player = _DroppingPlayer() # type: ignore[assignment]++ await pipeline._speak("This must stay out of the transcript.", language="en")+ await asyncio.sleep(0.05)+assert captured == []diff --git a/tests/unit/speech/test_tts_pipeline_overlap.py b/tests/unit/speech/test_tts_pipeline_overlap.pyindex fa89382af0..8715b493f6 100644--- a/tests/unit/speech/test_tts_pipeline_overlap.py+++ b/tests/unit/speech/test_tts_pipeline_overlap.py@@ -24,6 +24,7 @@ from dataclasses import dataclass, fieldimport pytestfrom jarvis.core.bus import EventBus+from jarvis.core.events import SpeechSpokenfrom jarvis.core.protocols import AudioChunkfrom jarvis.speech.pipeline import SpeechPipeline@@ -110,8 +111,8 @@ def _make_pipeline(tts, player, brain) -> SpeechPipeline:return pipeline-async def _wait_until(pred, timeout: float = 2.0) -> bool:- steps = max(1, int(timeout / 0.01))+async def _wait_until(pred, timeout_s: float = 2.0) -> bool:+ steps = max(1, int(timeout_s / 0.01))for _ in range(steps):if pred():return True@@ -148,7 +149,7 @@ async def test_next_sentence_synthesizes_while_current_sentence_plays() -> None:player.release_play_1.set()try:await asyncio.wait_for(turn, timeout=2.0)- except (asyncio.TimeoutError, asyncio.CancelledError):+ except (TimeoutError, asyncio.CancelledError):turn.cancel()@@ -195,6 +196,12 @@ async def test_barge_in_stops_playback_and_skips_pending_sentences() -> None:player = _BargePlayer()brain = _ThreeSentenceBrain()pipeline = _make_pipeline(tts, player, brain)+ confirmed: list[SpeechSpoken] = []++ async def _capture(event: SpeechSpoken) -> None:+ confirmed.append(event)++ pipeline._bus.subscribe(SpeechSpoken, _capture)async def _barge_after_play_starts() -> bool:await player.play_started.wait()@@ -210,6 +217,7 @@ async def test_barge_in_stops_playback_and_skips_pending_sentences() -> None:assert player.stop_calls >= 1# Only sentence 1 ever reached the player; the rest were cancelled.assert player.consumed == ["Erstes."]+ assert confirmed == []# Full raw text is still returned for post-stream hangup/history logic.assert full_text == "Erstes. Zweites. Drittes."@@ -222,12 +230,21 @@ async def test_sentences_play_in_order_and_full_text_returned() -> None:player = _GatingPlayer()brain = _ThreeSentenceBrain()pipeline = _make_pipeline(tts, player, brain)+ confirmed: list[SpeechSpoken] = []++ async def _capture(event: SpeechSpoken) -> None:+ confirmed.append(event)++ pipeline._bus.subscribe(SpeechSpoken, _capture)turn = asyncio.create_task(pipeline._brain_streaming("egal", "de"))await _wait_until(player.play_1_started.is_set)player.release_play_1.set()full_text, barged = await asyncio.wait_for(turn, timeout=2.0)+ await asyncio.sleep(0.05)assert player.consumed == ["Erstes.", "Zweites.", "Drittes."]assert full_text == "Erstes. Zweites. Drittes."assert barged is False+ assert [event.text for event in confirmed] == ["Erstes.", "Zweites.", "Drittes."]+ assert {event.spoken_kind for event in confirmed} == {"reply"}