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): re-render aborted realtime turns with a realtime-scoped voice
Ruben Lütkeb8649c4b3d6f
diff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.pyindex 8822013e51..4df265de1b 100644--- a/jarvis/plugins/tts/__init__.py+++ b/jarvis/plugins/tts/__init__.py@@ -256,6 +256,95 @@ def resolve_keyed_fallback(return None+# Same-family surface TTS per REALTIME provider (mode separation, 2026-07-17).+# The desktop surface re-renders a realtime turn locally when the live provider+# fails to deliver audio (scrub-gate cancel, text-only completion). That+# emergency voice must sound like the SESSION and resolve through the REALTIME+# credential slots — never jump straight to the pipeline's separately+# configured [tts] provider (live incident 2026-07-17 10:04: a gemini-live+# session's re-render spoke as "Charon @ openrouter" because the pipeline+# primary was openrouter-tts). Realtime families absent here have no native+# TTS sibling installed; their surface fallback stays on the key-aware+# pipeline chain.+_REALTIME_SURFACE_TTS_FAMILY: dict[str, str] = {+ "gemini-live": "gemini-flash-tts",+}+++def build_realtime_surface_tts(+ cfg: Any, realtime_provider: str, pipeline_tts: Any+) -> Any:+ """TTS for re-rendering a REALTIME turn locally (the surface fallback).++ Mode separation: prefer a TTS of the SAME provider family as the active+ realtime session — keyed through the realtime credential slots+ (``PROVIDER_SECRET_CANDIDATES[<realtime id>]``, dedicated realtime slot+ first) and speaking the session's configured voice — over the pipeline's+ separately configured ``[tts]`` chain. The pipeline chain stays wired as+ the cross-family last resort so a dead or keyless family still degrades+ honestly instead of going mute (AD-OE6 zero-silent-drops, AP-22).++ Never raises: any resolution problem returns ``pipeline_tts`` unchanged.+ """+ provider_id = (realtime_provider or "").strip().lower()+ family = _REALTIME_SURFACE_TTS_FAMILY.get(provider_id)+ if not family:+ return pipeline_tts+ try:+ from jarvis.core.config import get_provider_secret++ api_key = get_provider_secret(provider_id)+ if not api_key:+ log.info(+ "Realtime surface TTS: no key for realtime provider %r — "+ "using the pipeline TTS chain.",+ provider_id,+ )+ return pipeline_tts++ providers = getattr(getattr(cfg, "brain", None), "providers", None)+ provider_cfg = (+ providers.get(provider_id) if isinstance(providers, dict) else 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++ # The Live API and Gemini Flash TTS share one prebuilt-voice+ # catalog, so the session voice usually carries over verbatim;+ # an unknown voice falls back to the plugin default.+ voice = session_voice if session_voice in _GEMINI_VOICES else "Charon"+ primary: Any = GeminiFlashTTS(+ default_voice=voice,+ language_code=getattr(tts_cfg, "language_code", None) or "de-DE",+ allow_sapi5_fallback=bool(+ getattr(tts_cfg, "allow_sapi5_fallback", False)+ ),+ streaming=bool(getattr(tts_cfg, "streaming", False)),+ api_key=api_key,+ )+ else: # pragma: no cover — map entries always name a buildable family+ return pipeline_tts++ from jarvis.plugins.tts.fallback_tts import FallbackTTS++ log.info(+ "Realtime surface TTS: same-family %r (voice %r) serves realtime "+ "provider %r; the pipeline chain remains the last resort.",+ family, voice, provider_id,+ )+ return FallbackTTS(primary, pipeline_tts)+ except Exception as exc: # noqa: BLE001 — resolution must never mute the fallback+ log.warning(+ "Realtime surface TTS resolution failed (%s) — using the pipeline "+ "TTS chain.",+ exc,+ )+ return pipeline_tts++def _effective_primary_voice(family: str, tts_cfg: Any) -> str | None:"""Best-effort offline prediction of the voice ``family`` will speak with.diff --git a/jarvis/plugins/tts/gemini_flash_tts.py b/jarvis/plugins/tts/gemini_flash_tts.pyindex 2bc3df03de..49ee8f2234 100644--- a/jarvis/plugins/tts/gemini_flash_tts.py+++ b/jarvis/plugins/tts/gemini_flash_tts.py@@ -138,7 +138,13 @@ class GeminiFlashTTS:vertex_project: str | None = None,vertex_location: str = "us-central1",service_account_path: str | None = None,+ api_key: str | None = None,) -> None:+ # An explicitly injected key wins over the environment lookup. The+ # realtime surface fallback resolves the REALTIME credential slots+ # (realtime_gemini_api_key first) and passes the key in here, so a+ # realtime-scoped key never has to enter the generic pipeline lookup.+ self._api_key = (api_key or "").strip() or Noneself._model_name = modelself._default_voice = default_voiceself._language_code = language_code@@ -193,9 +199,12 @@ class GeminiFlashTTS:def _resolve_api_key(self) -> str:"""Key lookup with .env alias support.+ An injected constructor key (realtime surface fallback) wins. Otherwise:`.env` uses `GOOGLE_AIStudio_API_KEY` (user-specific), but google-genailooks for `GEMINI_API_KEY` / `GOOGLE_API_KEY`. We bridge that."""+ if self._api_key:+ return self._api_keyfor env_var in ("GEMINI_API_KEY", "GOOGLE_AIStudio_API_KEY", "GOOGLE_API_KEY"):val = cfg.get_secret(env_var.lower(), env_fallback=env_var)if val:diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex e4338dec10..aba6a48e0e 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -6202,8 +6202,11 @@ class SpeechPipeline:cleaned = scrubbed.cleaned.strip()if cleaned and not getattr(self, "_muted", False):# Realtime has already failed to render this grounded text.- # Use the configured classic TTS + the same AudioPlayer as- # an independent last mile. The existing mic pump and local+ # Re-render through a REALTIME-scoped TTS (same provider+ # family + realtime credential slots + session voice; the+ # classic pipeline chain only as last resort — mode+ # separation 2026-07-17) on the same AudioPlayer as an+ # independent last mile. The existing mic pump and local# barge detector remain active, so this does not open a# second microphone or replay the user's request.await playback.cancel()@@ -6211,17 +6214,62 @@ class SpeechPipeline:barge_detector.start_output()await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)try:+ surface_tts = self._resolve_realtime_surface_tts(+ self._active_realtime_provider+ )+ # Voice-identity continuity: the realtime session names+ # the voice it was speaking with, so this last mile does+ # not flip speakers mid-conversation (Fenrir→Charon,+ # live forensic 2026-07-17 10:04). Honored only when the+ # resolved TTS actually offers that voice — a capability+ # check, never a provider pin (AP-21); no match keeps+ # the TTS's own configured voice exactly as before.+ voice_hint = (+ str(message.get("voice", "") or "").strip() or None+ )+ if voice_hint:+ try:+ list_voices = getattr(+ surface_tts, "list_voices", None+ )+ known = (+ set(list_voices() or [])+ if callable(list_voices)+ else set()+ )+ except Exception: # noqa: BLE001 -- a hint must never block speech+ known = set()+ if voice_hint not in known:+ voice_hint = Nonelang_code = self._bcp47(language)+ # Pass ``voice`` only when a validated hint exists:+ # protocol-compatible TTS doubles/legacy providers+ # without that kwarg must keep their language_code+ # instead of dropping to the bare-text retry.+ synth_kwargs: dict[str, Any] = {+ "language_code": lang_code,+ }+ if voice_hint:+ synth_kwargs["voice"] = voice_hinttry:- chunks = self._tts.synthesize(- cleaned,- language_code=lang_code,+ chunks = surface_tts.synthesize(+ cleaned, **synth_kwargs)except TypeError:- chunks = self._tts.synthesize(cleaned)+ try:+ chunks = surface_tts.synthesize(+ cleaned, language_code=lang_code+ )+ except TypeError:+ chunks = surface_tts.synthesize(cleaned)playback_result = await self._player.play_chunks(chunks)if self._playback_confirmed(playback_result):- self._emit_spoken(cleaned, language, SPOKEN_KIND_REPLY)+ self._emit_spoken(+ cleaned,+ language,+ SPOKEN_KIND_REPLY,+ tts=surface_tts,+ )except Exception as exc: # noqa: BLE001 -- final voice fallbacklog.warning("Realtime surface TTS fallback failed: %s",@@ -9399,12 +9447,39 @@ class SpeechPipeline:self._abort_playback_device()return set()+ def _resolve_realtime_surface_tts(self, provider: str) -> Any:+ """TTS for re-rendering a realtime turn locally (mode separation).++ Prefers the active realtime provider's own TTS family, keyed through+ the realtime credential slots and speaking the session voice; the+ classic pipeline chain stays wired underneath as the cross-family+ last resort (AD-OE6). Cached per (provider, pipeline TTS instance) so+ a live TTS switch via ``set_tts`` naturally invalidates it. Any+ resolution failure returns the pipeline TTS — never raises.+ """+ base = getattr(self, "_tts", None)+ key = (provider or "").strip().lower()+ if not key or base is None:+ return base+ cached = getattr(self, "_realtime_surface_tts_cache", None)+ if cached is not None and cached[0] == key and cached[1] is base:+ return cached[2]+ try:+ from jarvis.plugins.tts import build_realtime_surface_tts++ built = build_realtime_surface_tts(self._config, key, base)+ except Exception: # noqa: BLE001 — the emergency voice must never break+ built = base+ self._realtime_surface_tts_cache = (key, base, built)+ return built+def _emit_spoken(self,text: str,language: str | None,kind: str,detail: str | None = None,+ tts: Any | None = None,) -> None:"""Publish one playback-confirmed phrase to the audible transcript.@@ -9423,7 +9498,10 @@ class SpeechPipeline:# through self._tts, whose providers record their resolved voice# per utterance (last_voice protocol, 2026-07-17). Read after# playback so a fallback takeover reports the TAKEOVER voice.- tts = getattr(self, "_tts", None)+ # A caller that rendered through a DIFFERENT instance (realtime+ # surface fallback) passes it in so the label stays honest.+ if tts is None:+ tts = getattr(self, "_tts", None)voice = getattr(tts, "last_voice", None)voice_provider = getattr(tts, "last_voice_provider", None) or getattr(tts, "name", Nonediff --git a/tests/unit/plugins/tts/test_realtime_surface_tts.py b/tests/unit/plugins/tts/test_realtime_surface_tts.pynew file mode 100644index 0000000000..c28fe52396--- /dev/null+++ b/tests/unit/plugins/tts/test_realtime_surface_tts.py@@ -0,0 +1,103 @@+"""Mode separation for the realtime surface fallback voice (2026-07-17).++A realtime session's emergency re-render (scrub-gate cancel, text-only+completion) must speak with the SESSION's provider family, resolved through+the REALTIME credential slots — not with whatever the pipeline's separately+configured ``[tts]`` provider happens to be. Live incident 2026-07-17 10:04:+a gemini-live session (voice Fenrir) aborted a readback and the re-render+spoke as "Charon @ openrouter" because the pipeline primary was+openrouter-tts. The pipeline chain stays wired as the cross-family last+resort (AD-OE6 zero-silent-drops, AP-22).+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.core.config import override_provider_secrets+from jarvis.plugins.tts import build_realtime_surface_tts+from jarvis.plugins.tts.fallback_tts import FallbackTTS+from jarvis.plugins.tts.gemini_flash_tts import GeminiFlashTTS+++def _cfg(voice: str = "Fenrir") -> SimpleNamespace:+ return SimpleNamespace(+ brain=SimpleNamespace(+ providers={"gemini-live": SimpleNamespace(voice=voice)},+ ),+ tts=SimpleNamespace(+ language_code="de-DE",+ allow_sapi5_fallback=False,+ streaming=False,+ ),+ )+++class _PipelineTTS:+ name = "pipeline-chain"++ async def synthesize(self, text, voice=None, language_code=None):+ if False: # pragma: no cover — makes this an async iterator+ yield None+++def test_gemini_live_builds_same_family_tts_with_session_voice() -> None:+ pipeline_tts = _PipelineTTS()+ with override_provider_secrets({"gemini-live": "rt-scoped-key"}):+ tts = build_realtime_surface_tts(_cfg(), "gemini-live", pipeline_tts)+ assert isinstance(tts, FallbackTTS)+ assert isinstance(tts.primary, GeminiFlashTTS)+ # The session voice carries over verbatim (shared prebuilt-voice catalog).+ assert tts.primary._default_voice == "Fenrir"+ # The realtime-resolved key is injected — never left to the generic+ # environment lookup, so realtime-scoped keys stay out of pipeline scope.+ assert tts.primary._resolve_api_key() == "rt-scoped-key"+ # The pipeline chain remains the cross-family last resort.+ assert tts.fallback is pipeline_tts+++def test_unknown_session_voice_falls_back_to_family_default() -> None:+ pipeline_tts = _PipelineTTS()+ with override_provider_secrets({"gemini-live": "rt-scoped-key"}):+ tts = build_realtime_surface_tts(+ _cfg(voice="cedar"), "gemini-live", pipeline_tts+ )+ assert isinstance(tts, FallbackTTS)+ assert tts.primary._default_voice == "Charon"+++def test_keyless_realtime_provider_keeps_pipeline_chain() -> None:+ pipeline_tts = _PipelineTTS()+ with override_provider_secrets({"gemini-live": None}):+ tts = build_realtime_surface_tts(_cfg(), "gemini-live", pipeline_tts)+ assert tts is pipeline_tts+++def test_realtime_family_without_tts_sibling_keeps_pipeline_chain() -> None:+ pipeline_tts = _PipelineTTS()+ with override_provider_secrets({"openai-realtime": "some-key"}):+ tts = build_realtime_surface_tts(_cfg(), "openai-realtime", pipeline_tts)+ assert tts is pipeline_tts+++def test_empty_provider_keeps_pipeline_chain() -> None:+ pipeline_tts = _PipelineTTS()+ assert build_realtime_surface_tts(_cfg(), "", pipeline_tts) is pipeline_tts+++def test_resolution_failure_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline_tts = _PipelineTTS()++ def _boom(_provider: str) -> str:+ raise RuntimeError("keyring exploded")++ monkeypatch.setattr("jarvis.core.config.get_provider_secret", _boom)+ tts = build_realtime_surface_tts(_cfg(), "gemini-live", pipeline_tts)+ assert tts is pipeline_tts+++def test_injected_api_key_wins_over_environment_lookup() -> None:+ tts = GeminiFlashTTS(api_key="explicit-key")+ assert tts._resolve_api_key() == "explicit-key"diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.pyindex e7fc837414..e75ba074d5 100644--- a/tests/unit/speech/test_realtime_mode.py+++ b/tests/unit/speech/test_realtime_mode.py@@ -341,6 +341,146 @@ async def test_unsafe_output_cancel_stops_playback_and_returns_to_listening(assert built["session"].end_reason == HANGUP_HOTKEY+async def test_error_spoken_renders_through_realtime_scoped_surface_tts(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Mode separation (2026-07-17): the realtime emergency re-render resolves+ a REALTIME-scoped surface TTS for the active provider instead of blindly+ speaking through the pipeline's separately configured [tts] instance, and+ the spoken-voice label is read from the instance that actually spoke."""+ pipe = _pipe()+ pipeline_pcm = b"\x07\x00" * 32+ surface_pcm = b"\x08\x00" * 32+ pipeline_tts = _FakeTTS(pipeline_pcm)+ surface_tts = _FakeTTS(surface_pcm)+ pipe._tts = pipeline_tts+ resolved: dict[str, object] = {}+ spoken_delivered = asyncio.Event()++ def _scoped_surface_tts(cfg, provider, base):+ resolved["cfg"] = cfg+ resolved["provider"] = provider+ resolved["base"] = base+ return surface_tts++ monkeypatch.setattr(+ "jarvis.plugins.tts.build_realtime_surface_tts", _scoped_surface_tts+ )++ class _ErrorSpokenSession(_HandshakeOnlyRealtimeSession):+ async def handle_control(self, message) -> None:+ await super().handle_control(message)+ await self._send_json(+ {+ "type": "error_spoken",+ "text": "The grounded reply.",+ "language": "en",+ }+ )+ spoken_delivered.set()++ def _build(**kwargs):+ return _ErrorSpokenSession(kwargs["send_binary"], kwargs["send_json"])++ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic())++ task = asyncio.create_task(pipe._active_realtime_session())+ await asyncio.wait_for(spoken_delivered.wait(), timeout=0.5)+ await asyncio.sleep(0)++ # The resolver received the active realtime provider + the pipeline TTS as+ # the last-resort base, and the scoped instance did ALL the speaking.+ assert resolved["provider"] == "fake-live"+ assert resolved["base"] is pipeline_tts+ assert [text for text, _lang in surface_tts.calls] == ["The grounded reply."]+ assert pipeline_tts.calls == []+ assert surface_pcm in pipe._player.pcm++ pipe._hangup_event.set()+ assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY+++class _VoiceAwareTTS(_FakeTTS):+ """A surface TTS that supports per-utterance voice pinning + listing."""++ def __init__(self, pcm: bytes, voices: list[str]) -> None:+ super().__init__(pcm)+ self.voices = voices+ self.voice_calls: list[str | None] = []++ def list_voices(self, language: str | None = None) -> list[str]:+ return list(self.voices)++ def synthesize(+ self,+ text: str,+ *,+ voice: str | None = None,+ language_code: str | None = None,+ ):+ self.voice_calls.append(voice)+ return super().synthesize(text, language_code=language_code)+++ ("catalogue", "expected_voice"),+ [+ (["Fenrir", "Charon"], "Fenrir"), # hint offered -> voice continuity+ (["leo"], None), # foreign catalogue -> provider's own default+ ],+)+async def test_error_spoken_voice_hint_is_capability_gated(+ monkeypatch: pytest.MonkeyPatch,+ catalogue: list[str],+ expected_voice: str | None,+) -> None:+ """Voice-identity continuity (live forensic 2026-07-17 10:04: Fenrir's+ aborted readback re-spoken by Charon): the realtime session's voice hint is+ honored when the resolved surface TTS offers that voice, and silently+ dropped when it does not — a capability check, never a provider pin."""+ pipe = _pipe()+ pipe._tts = _FakeTTS(b"\x07\x00" * 32)+ surface_tts = _VoiceAwareTTS(b"\x08\x00" * 32, catalogue)+ spoken_delivered = asyncio.Event()++ monkeypatch.setattr(+ "jarvis.plugins.tts.build_realtime_surface_tts",+ lambda _cfg, _provider, _base: surface_tts,+ )++ class _VoiceHintSession(_HandshakeOnlyRealtimeSession):+ async def handle_control(self, message) -> None:+ await super().handle_control(message)+ await self._send_json(+ {+ "type": "error_spoken",+ "text": "The grounded reply.",+ "language": "en",+ "voice": "Fenrir",+ }+ )+ spoken_delivered.set()++ def _build(**kwargs):+ return _VoiceHintSession(kwargs["send_binary"], kwargs["send_json"])++ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic())++ task = asyncio.create_task(pipe._active_realtime_session())+ await asyncio.wait_for(spoken_delivered.wait(), timeout=0.5)+ await asyncio.sleep(0)++ assert surface_tts.voice_calls == [expected_voice]+ assert [text for text, _lang in surface_tts.calls] == ["The grounded reply."]++ pipe._hangup_event.set()+ assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY++@pytest.mark.asyncioasync def test_desktop_cpu_barge_in_cancels_and_forwards_user_preroll(monkeypatch: pytest.MonkeyPatch,