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(realtime): a readback is spoken once even after a long speaker drain, and Vertex Live gets its emergency voice
Harald315658318294
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.pyindex 6aeeac34b2..08863c8c80 100644--- a/jarvis/plugins/realtime/gemini_live.py+++ b/jarvis/plugins/realtime/gemini_live.py@@ -9,6 +9,7 @@ mono PCM at 16 kHz and emits the same format at 24 kHz.from __future__ import annotationsimport logging+import timefrom collections.abc import AsyncIteratorfrom dataclasses import dataclassfrom typing import Any@@ -253,6 +254,55 @@ class _GeminiLiveSession:# open a turn of its own.self._user_turn_open = Falseself._model_generating = False+ # Wire forensics (BUG-148). One line per client text/tool input and+ # one per server generation boundary — the minimum that lets a+ # doubled or missing reply be attributed from the log alone. The+ # 2026-08-18 18:40 session (a readback spoken twice, then three+ # answers never rendered) was undiagnosable without it: neither what+ # was sent nor which generation a boundary closed was recorded.+ self._gen_audio_bytes = 0+ self._gen_transcript_chars = 0+ self._gen_function_calls = 0+ self._gen_started_at = 0.0+ self._last_input_kind = "connect"+ self._last_input_at = time.monotonic()++ def _note_input_sent(self, kind: str) -> None:+ self._last_input_kind = kind+ self._last_input_at = time.monotonic()++ def _note_generation_output(+ self, *, audio_bytes: int = 0, transcript_chars: int = 0, calls: int = 0+ ) -> None:+ if not self._gen_started_at:+ self._gen_started_at = time.monotonic()+ log.info(+ "gemini-live: generation started %.2fs after the last %s input",+ self._gen_started_at - self._last_input_at,+ self._last_input_kind,+ )+ self._gen_audio_bytes += audio_bytes+ self._gen_transcript_chars += transcript_chars+ self._gen_function_calls += calls++ def _log_generation_boundary(self, *, kind: str, reason: str = "") -> None:+ started = self._gen_started_at+ log.info(+ "gemini-live: %s — audio=%.1fs transcript=%d chars function_calls=%d "+ "generation=%s; %.2fs after the last %s input%s",+ kind,+ self._gen_audio_bytes / float(_OUTPUT_RATE * 2),+ self._gen_transcript_chars,+ self._gen_function_calls,+ (f"{time.monotonic() - started:.2f}s" if started else "none"),+ time.monotonic() - self._last_input_at,+ self._last_input_kind,+ f" reason={reason}" if reason else "",+ )+ self._gen_audio_bytes = 0+ self._gen_transcript_chars = 0+ self._gen_function_calls = 0+ self._gen_started_at = 0.0async def send_audio(self, chunk: Any) -> None:from google.genai import types # lazy (AP-26)@@ -286,6 +336,7 @@ class _GeminiLiveSession:data = getattr(message, "data", None)if data:self._note_model_output()+ self._note_generation_output(audio_bytes=len(data))yield _ProviderEvent(type="audio_delta",audio=_PcmChunk(pcm=bytes(data), sample_rate=_OUTPUT_RATE),@@ -308,6 +359,14 @@ class _GeminiLiveSession:self._pending_usage = Noneif function_calls:self._note_model_output()+ self._note_generation_output(calls=len(function_calls))+ log.info(+ "gemini-live: function call(s) %s",+ ", ".join(+ str(getattr(call, "name", "") or "?")+ for call in function_calls+ ),+ )for function_call in function_calls:raw_args = getattr(function_call, "args", None) or {}if hasattr(raw_args, "model_dump"):@@ -333,6 +392,9 @@ class _GeminiLiveSession:)if output_text:self._note_model_output()+ self._note_generation_output(+ transcript_chars=len(output_text)+ )yield _ProviderEvent(type="output_transcript_delta", text=output_text)@@ -352,6 +414,7 @@ class _GeminiLiveSession:# A barge-in ends the generation, so the channel is# free again for the user turn that just started.self._model_generating = False+ self._log_generation_boundary(kind="interrupted")yield _ProviderEvent(type="interrupted")input_transcription = getattr(@@ -401,6 +464,15 @@ class _GeminiLiveSession:type="usage", usage=self._pending_usage)self._pending_usage = None+ self._log_generation_boundary(+ kind=(+ "turn complete (function call, boundary "+ "withheld)"+ if function_calls+ else "turn complete"+ ),+ reason=reason_name,+ )if not function_calls:yield _ProviderEvent(type="turn_complete")@@ -501,12 +573,15 @@ class _GeminiLiveSession:for key in ordered:self._delivered_steering[key] = self._pending_steering[key][0]self._pending_steering.clear()+ self._note_input_sent("steering text")# Keys only, never the directive text: this line exists so a call where# the model "did not answer the way it normally would" can be checked- # against what actually reached it.- log.debug(- "gemini-live: delivered a per-turn steering delta (%s)",+ # against what actually reached it — and, since it is a text input of+ # its own on this channel, so a generation it provokes is attributable.+ log.info(+ "gemini-live: delivered a per-turn steering delta (%s; %d chars)",", ".join(ordered),+ len(body),)async def update_session(@@ -563,7 +638,16 @@ class _GeminiLiveSession:"""Send an incremental text turn through the current Gemini 3.1 API."""# Gemini 3.1 permits send_client_content only for initial history.# Runtime text updates must use the realtime-input text stream.- await self._session.send_realtime_input(text=str(text))+ payload = str(text)+ log.info(+ "gemini-live: text input sent (%d chars; model_generating=%s "+ "user_turn_open=%s)",+ len(payload),+ self._model_generating,+ self._user_turn_open,+ )+ await self._session.send_realtime_input(text=payload)+ self._note_input_sent("text")async def truncate(self, audio_end_ms: int) -> None:del audio_end_ms # Gemini interrupts generation when new audio arrives.@@ -577,6 +661,11 @@ class _GeminiLiveSession:) -> None:from google.genai import types # lazy (AP-26)+ log.info(+ "gemini-live: tool response sent for %s (model_generating=%s)",+ name or "?",+ self._model_generating,+ )await self._session.send_tool_response(function_responses=[types.FunctionResponse(@@ -586,6 +675,7 @@ class _GeminiLiveSession:)])+ self._note_input_sent("tool response")async def close(self) -> None:if self._closed:diff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.pyindex e47dfe6e70..d6b4fd0085 100644--- a/jarvis/plugins/tts/__init__.py+++ b/jarvis/plugins/tts/__init__.py@@ -294,6 +294,13 @@ def resolve_keyed_fallback(# not even as a last resort._REALTIME_SURFACE_TTS_FAMILY: dict[str, str] = {"gemini-live": "gemini-flash-tts",+ # Vertex Live's own sibling: the same Gemini voices on the Cloud project+ # path, keyed by the Vertex slots or Application Default Credentials —+ # never the AI-Studio key. Without this entry a Vertex Live turn whose+ # provider rendered no audio stayed TEXT-ONLY while the pipeline had a+ # working Vertex TTS all along (live 2026-08-18 18:41: three grounded+ # answers in a row were never heard; provider & mode parity, BUG-148).+ "vertex-live": "vertex-tts",}@@ -317,10 +324,19 @@ def build_realtime_surface_tts(cfg: Any, realtime_provider: str) -> Any | None:if not family:return Nonetry:- from jarvis.core.config import get_provider_secret+ from jarvis.core.config import (+ get_provider_secret,+ vertex_credential_configured,+ )- api_key = get_provider_secret(provider_id)- if not api_key:+ api_key = get_provider_secret(provider_id) or ""+ if not api_key and family == "vertex-tts" and vertex_credential_configured():+ # The Cloud project path signs with Application Default+ # Credentials: a fully configured Vertex host may hold no key at+ # all. ``VertexTTS`` resolves that itself; an empty key here+ # simply means "the shared Vertex credential state decides".+ api_key = ""+ elif not api_key:log.info("Realtime surface TTS: no key for realtime provider %r — ""the emergency re-render stays text-only (strict mode "@@ -336,8 +352,11 @@ def build_realtime_surface_tts(cfg: Any, realtime_provider: str) -> Any | None:session_voice = str(getattr(provider_cfg, "voice", "") or "").strip()tts_cfg = getattr(cfg, "tts", None)- if family == "gemini-flash-tts":- from jarvis.plugins.tts.gemini_flash_tts import GeminiFlashTTS+ if family in {"gemini-flash-tts", "vertex-tts"}:+ from jarvis.plugins.tts.gemini_flash_tts import (+ GeminiFlashTTS,+ VertexTTS,+ )# The Live API and Gemini Flash TTS share one prebuilt-voice# catalog, so the session voice usually carries over verbatim.@@ -359,7 +378,12 @@ def build_realtime_surface_tts(cfg: Any, realtime_provider: str) -> Any | None:if profile_genderelse None) or "Charon"- surface: Any = GeminiFlashTTS(+ # Same voice catalogue, same emergency-render knobs; only the+ # credential path differs (AI-Studio key vs. Vertex key/ADC).+ surface_cls: Any = (+ VertexTTS if family == "vertex-tts" else GeminiFlashTTS+ )+ surface: Any = surface_cls(default_voice=voice,language_code=getattr(tts_cfg, "language_code", None) or "de-DE",allow_sapi5_fallback=bool(@@ -389,7 +413,7 @@ def build_realtime_surface_tts(cfg: Any, realtime_provider: str) -> Any | None:chunk_by_sentence=False,seed=getattr(tts_cfg, "seed", None),temperature=getattr(tts_cfg, "temperature", None),- api_key=api_key,+ api_key=api_key or None,)else: # pragma: no cover — map entries always name a buildable familyreturn Nonediff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 0a26271657..31213b15af 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -266,7 +266,12 @@ _DELEGATE_READBACK_POLL_S = 0.1# a provider-rendered delegate readback, with NO new user input in between,# answers nothing the user asked. The window bounds the guard so a genuine# later answer is never at risk; local microphone voice, a new transcript, or-# any deliberate injection disarms it immediately.+# any deliberate injection disarms it immediately. It is measured from the+# SURFACE boundary, not from the provider's: the desktop drains its speaker+# queue inside that boundary, and the provider streams a reply faster than+# real time, so a stamp taken at the provider boundary is stale by the+# reply's remaining playback — 7.6 s and 4.6 s readbacks both slipped past a+# 2.5 s window and were spoken twice (live 2026-08-18 18:40, BUG-148)._STALE_GENERATION_WINDOW_S = 2.5# A discarded generation is released by its own boundary. Every awaited state# in this file carries a bound (the turn stall watchdog, the late-result@@ -1353,6 +1358,10 @@ class _DelegateTurnState:requires_public_fact_grounding: bool = Falsepublic_fact_grounding_timeout_s: float = 0.0delivery_started: bool = False+ # When the trusted result left for the provider (monotonic); 0.0 until+ # then. Forensics only: it lets a boundary that closes the turn with no+ # audio say how long after the delivery it arrived (BUG-148).+ delivered_at: float = 0.0provider_boundary_seen: bool = Falseprovider_stream_ended: bool = Falseuser_text: str = ""@@ -4864,8 +4873,16 @@ class RealtimeVoiceSession:self._output_transcript.append(fallback_text)log.warning("realtime[%s] provider produced no audio for a "- "grounded Brain result; using surface TTS fallback",+ "grounded Brain result (boundary %.2fs after "+ "delivery, transcript=%d chars); using surface "+ "TTS fallback",self.session_id,+ (+ time.monotonic() - delegate_state.delivered_at+ if delegate_state.delivered_at+ else -1.0+ ),+ len("".join(self._output_transcript)),)# One reply, one voice (live forensic 2026-07-16# 11:43: THREE renderings of the same answer). The@@ -4926,6 +4943,7 @@ class RealtimeVoiceSession:self._external_update is not Noneand self._output_samples_sent > 0)+ guard_reply = ""if rendered_delegate_reply or rendered_injected_readback:# The provider just rendered a text Jarvis injected (a# delegate result, a late result, an announcement) and@@ -4933,10 +4951,16 @@ class RealtimeVoiceSession:# transport a SECOND generation can follow within# milliseconds — the answer to the user's trailing# speech, which re-renders the same text (BUG-143).- # Arm the guard before the turn resets so that- # generation is discarded instead of opening a phantom- # turn and speaking the reply twice.- self._arm_stale_generation_guard(+ # The guard is armed AFTER the surface boundary below,+ # not here: on the desktop that boundary blocks until+ # the speaker queue has drained, and the provider had+ # streamed the whole reply faster than real time — so+ # a stamp taken now is already seconds old when the+ # next event is judged, and every reply longer than+ # the guard window slipped through as a phantom turn+ # (live 2026-08-18 18:40: 7.6 s and 4.6 s readbacks,+ # both spoken twice; BUG-148).+ guard_reply = (str(delegate_state.last_reply or "")if rendered_delegate_reply and delegate_state is not Noneelse str(@@ -4944,7 +4968,12 @@ class RealtimeVoiceSession:or ""))+ boundary_at = time.monotonic()await self._complete_surface_turn()+ if guard_reply and self._may_arm_stale_generation_guard(+ boundary_at+ ):+ self._arm_stale_generation_guard(guard_reply)if self._end_after_turn:# end_call was acknowledged; the model has now spoken# its goodbye to the end — hang up.@@ -7596,6 +7625,28 @@ class RealtimeVoiceSession:returnself._stale_generation_guard_armed_at = time.monotonic()self._stale_generation_guard_reply = str(reply or "")+ log.info(+ "realtime[%s] stale-generation guard armed for %.1fs after the "+ "rendered readback",+ self.session_id,+ _STALE_GENERATION_WINDOW_S,+ )++ def _may_arm_stale_generation_guard(self, boundary_at: float) -> bool:+ """Whether the readback turn closed quietly enough to arm the guard.++ ``boundary_at`` is when the provider's boundary was received; the+ surface boundary that follows it can take seconds (the desktop drains+ its speaker queue inside ``send_json``). Anything the user did in+ that span — a confirmed barge-in, local voice, a transcript that+ opened the next turn — is fresh evidence that whatever the provider+ says next was asked for, so the guard must not arm at all.+ """+ return bool(+ not self._turn_id+ and not self._user_speech_active+ and self._last_voiced_input_monotonic <= boundary_at+ )def _disarm_stale_generation_guard(self) -> None:self._stale_generation_guard_armed_at = 0.0@@ -9666,6 +9717,7 @@ class RealtimeVoiceSession:)turn_state.pending_tool_calls.clear()if turn_state.pending_tool_calls:+ delivery_wire = "tool result"for call_id, wire_name in tuple(turn_state.pending_tool_calls):await self._session.send_tool_result(call_id,@@ -9676,6 +9728,7 @@ class RealtimeVoiceSession:else:send_speech = getattr(self._session, "send_speech", None)if callable(send_speech):+ delivery_wire = "direct speech"await send_speech(trusted_reply)if getattr(self._session, "direct_speech_is_authoritative", False@@ -9689,6 +9742,7 @@ class RealtimeVoiceSession:for chunk in self._gate.release_available():await self._emit_audio(chunk)else:+ delivery_wire = "text"await self._session.send_text(_delegate_result_prompt(trusted_reply,@@ -9710,6 +9764,14 @@ class RealtimeVoiceSession:turn_state.last_reply,)return+ turn_state.delivered_at = time.monotonic()+ log.info(+ "realtime[%s] deterministic delegate result delivered via %s "+ "(%d chars) — awaiting the provider's readback",+ self.session_id,+ delivery_wire,+ len(trusted_reply),+ )await self._verify_delegate_readback(turn_id, turn_state)async def _verify_delegate_readback(@@ -9924,6 +9986,13 @@ class RealtimeVoiceSession:exc_info=True,)return+ turn_state.delivered_at = time.monotonic()+ log.info(+ "realtime[%s] delegate result delivered via tool result "+ "(%d chars) — awaiting the provider's readback",+ self.session_id,+ len(str(turn_state.last_reply or "")),+ )await self._verify_delegate_readback(turn_id, turn_state)async def _dispatch_brain_turn(diff --git a/tests/unit/plugins/tts/test_realtime_surface_tts.py b/tests/unit/plugins/tts/test_realtime_surface_tts.pyindex c506a5cff3..5cc4a03e06 100644--- a/tests/unit/plugins/tts/test_realtime_surface_tts.py+++ b/tests/unit/plugins/tts/test_realtime_surface_tts.py@@ -28,7 +28,7 @@ from jarvis.plugins.tts import (_tts_has_credential,build_realtime_surface_tts,)-from jarvis.plugins.tts.gemini_flash_tts import GeminiFlashTTS+from jarvis.plugins.tts.gemini_flash_tts import GeminiFlashTTS, VertexTTSfrom jarvis.ui.web.provider_spec import PROVIDERS# The realtime tier's own provider ids — the ones ALLOWED to put a@@ -44,7 +44,10 @@ _REALTIME_PROVIDER_IDS = tuple(def _cfg(voice: str = "Fenrir") -> SimpleNamespace:return SimpleNamespace(brain=SimpleNamespace(- providers={"gemini-live": SimpleNamespace(voice=voice)},+ providers={+ "gemini-live": SimpleNamespace(voice=voice),+ "vertex-live": SimpleNamespace(voice=voice),+ },),tts=SimpleNamespace(language_code="de-DE",@@ -157,6 +160,51 @@ def test_surface_fallback_always_streams_whatever_the_pipeline_knob_says() -> Noassert tts._chunk_by_sentence is False+# ---------------------------------------------------------------------------+# Vertex Live: same voices, Cloud project credential path (BUG-148).+# ---------------------------------------------------------------------------+++def test_vertex_live_builds_vertex_tts_with_session_voice() -> None:+ """Live 2026-08-18 18:41: three grounded Vertex Live answers were never+ heard because the family map knew only gemini-live — the surface fallback+ stayed text-only while the host had a working Vertex TTS. Provider parity:+ vertex-live gets its own sibling, keyed through the Vertex slots."""+ with override_provider_secrets({"vertex-live": "rt-vertex-key"}):+ tts = build_realtime_surface_tts(_cfg(), "vertex-live")+ assert isinstance(tts, VertexTTS)+ assert tts._default_voice == "Fenrir"+ assert tts._resolve_api_key() == "rt-vertex-key"+ # Same emergency-render profile as the AI-Studio sibling.+ assert tts._streaming is True+ assert tts._chunk_by_sentence is False+++def test_vertex_live_builds_on_the_project_path_without_a_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Application Default Credentials: a configured [google].vertex_project+ is a full Vertex setup with no key anywhere. The sibling must still be+ built; VertexTTS resolves the credential state itself."""+ monkeypatch.setattr(+ "jarvis.core.config.vertex_credential_configured", lambda *_a, **_k: True+ )+ with override_provider_secrets({"vertex-live": None}):+ tts = build_realtime_surface_tts(_cfg(), "vertex-live")+ assert isinstance(tts, VertexTTS)+ assert tts._api_key is None+++def test_vertex_live_without_any_credential_yields_no_surface_tts(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ "jarvis.core.config.vertex_credential_configured", lambda *_a, **_k: False+ )+ with override_provider_secrets({"vertex-live": None}):+ assert build_realtime_surface_tts(_cfg(), "vertex-live") is None++def test_keyless_realtime_provider_yields_no_surface_tts() -> None:with override_provider_secrets({"gemini-live": None}):assert build_realtime_surface_tts(_cfg(), "gemini-live") is Nonediff --git a/tests/unit/realtime/test_stale_generation_after_readback.py b/tests/unit/realtime/test_stale_generation_after_readback.pyindex 4a86153706..3e1d2547bc 100644--- a/tests/unit/realtime/test_stale_generation_after_readback.py+++ b/tests/unit/realtime/test_stale_generation_after_readback.py@@ -519,6 +519,104 @@ async def test_follow_up_landing_mid_drop_keeps_its_own_turn(assert session._stale_generations_dropped == 1+# ---------------------------------------------------------------------------+# The surface boundary drains the speaker (BUG-148)+# ---------------------------------------------------------------------------+++async def _run_with_draining_surface(+ provider: _ServerVadProvider,+ *,+ drain_s: float,+ on_drain: Any = None,+ settle_s: float = 0.6,+) -> tuple[RealtimeVoiceSession, list[dict[str, Any]], list[bytes], _FakeBus]:+ """Like ``_run``, but ``send_json`` blocks on ``turn_complete`` the way+ the desktop surface does while its speaker queue drains."""+ brain = _DelegatingBrain()+ messages: list[dict[str, Any]] = []+ binaries: list[bytes] = []+ bus = _FakeBus()+ holder: dict[str, RealtimeVoiceSession] = {}++ async def _send_json(message: dict[str, Any]) -> None:+ messages.append(message)+ if message.get("type") == "turn_complete":+ await asyncio.sleep(drain_s)+ if on_drain is not None:+ await on_drain(holder["session"])++ session = RealtimeVoiceSession(+ session_id="stale-generation-guard-drain",+ send_binary=lambda data: binaries.append(data) or asyncio.sleep(0),+ send_json=_send_json,+ provider=provider,+ config=_config(),+ bus=bus,+ browser_sample_rate=16_000,+ surface="desktop",+ brain=brain,+ )+ holder["session"] = session+ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})+ try:+ await asyncio.wait_for(provider.session.text_sent.wait(), timeout=10.0)+ await asyncio.wait_for(provider.session.readback_done.wait(), timeout=10.0)+ await asyncio.sleep(drain_s + settle_s)+ finally:+ await session.end(reason="test")+ return session, messages, binaries, bus+++async def test_second_generation_is_discarded_even_after_a_long_speaker_drain(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Live 2026-08-18 18:40 (BUG-148): the provider streams a 7.6 s reply in+ a couple of seconds and sends its boundary; the desktop then drains the+ speaker for the rest of the reply INSIDE the surface boundary. A guard+ stamped at the provider boundary is older than its own window by the+ time the phantom generation is judged — so the reply was spoken twice.+ The window must run from the surface boundary."""+ _shorten_delegate_waits(monkeypatch)+ # Window shorter than the drain: the old stamp would already be stale.+ monkeypatch.setattr(session_module, "_STALE_GENERATION_WINDOW_S", 0.1)+ provider = _ServerVadProvider(script="second-generation")++ session, messages, binaries, bus = await _run_with_draining_surface(+ provider, drain_s=0.35+ )++ assert len(binaries) == 1+ assert _assistant_texts(messages) == [REPLY]+ assert sum(1 for m in messages if m.get("type") == "turn_complete") == 1+ assert _turn_starts(bus) == 1+ assert session._stale_generations_dropped == 1+++async def test_voice_during_the_speaker_drain_keeps_the_next_answer(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The user barged in while the reply was still draining: what the+ provider says next was asked for, so the guard must not arm at all."""+ _shorten_delegate_waits(monkeypatch)+ provider = _ServerVadProvider(script="after-local-voice")++ async def _user_barges_in(session: RealtimeVoiceSession) -> None:+ # What handle_audio_frame stamps for the confirmed barge-in frame.+ session._last_voiced_input_monotonic = time.monotonic()++ session, messages, binaries, _bus = await _run_with_draining_surface(+ provider, drain_s=0.2, on_drain=_user_barges_in+ )++ assert len(binaries) == 2+ assert _assistant_texts(messages) == [REPLY, FOLLOW_UP_ANSWER]+ assert session._stale_generations_dropped == 0+ assert session._stale_generation_guard_armed_at == 0.0++# ---------------------------------------------------------------------------# Capability gate and predicate# ---------------------------------------------------------------------------