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(realtime): enforce strict realtime/pipeline mode separation for the emergency voice

Ruben Lütked8cc87a6ac57
diff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.py
index 4df265de1b..8fd97e9e50 100644
--- a/jarvis/plugins/tts/__init__.py
+++ b/jarvis/plugins/tts/__init__.py
@@ -260,36 +260,38 @@ def resolve_keyed_fallback(
# 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.
+# credential slots — never through 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 emergency re-render stays TEXT-ONLY — the maintainer
+# mandate (2026-07-17) is STRICT mode independence: a realtime session must
+# work with only realtime keys and must never spend pipeline credentials,
+# not even as a last resort.
_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:
+def build_realtime_surface_tts(cfg: Any, realtime_provider: str) -> Any | None:
"""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
+ STRICT mode separation (maintainer mandate 2026-07-17): the emergency
+ voice is 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).
+ first) and speaking the session's configured voice. Realtime and
+ pipeline are independent modes: each must work with only its own keys,
+ so the pipeline ``[tts]`` chain is NEVER a candidate here.
- Never raises: any resolution problem returns ``pipeline_tts`` unchanged.
+ Returns ``None`` when the realtime family has no TTS sibling or no
+ usable key — the caller then keeps the turn text-only with an honest
+ log instead of borrowing the pipeline voice. Never raises.
"""
provider_id = (realtime_provider or "").strip().lower()
family = _REALTIME_SURFACE_TTS_FAMILY.get(provider_id)
if not family:
- return pipeline_tts
+ return None
try:
from jarvis.core.config import get_provider_secret
@@ -297,10 +299,11 @@ def build_realtime_surface_tts(
if not api_key:
log.info(
"Realtime surface TTS: no key for realtime provider %r — "
- "using the pipeline TTS chain.",
+ "the emergency re-render stays text-only (strict mode "
+ "separation).",
provider_id,
)
- return pipeline_tts
+ return None
providers = getattr(getattr(cfg, "brain", None), "providers", None)
provider_cfg = (
@@ -316,7 +319,7 @@ def build_realtime_surface_tts(
# 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(
+ surface: Any = GeminiFlashTTS(
default_voice=voice,
language_code=getattr(tts_cfg, "language_code", None) or "de-DE",
allow_sapi5_fallback=bool(
@@ -326,23 +329,21 @@ def build_realtime_surface_tts(
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
+ return None
log.info(
"Realtime surface TTS: same-family %r (voice %r) serves realtime "
- "provider %r; the pipeline chain remains the last resort.",
+ "provider %r (strict mode separation — no pipeline voice).",
family, voice, provider_id,
)
- return FallbackTTS(primary, pipeline_tts)
- except Exception as exc: # noqa: BLE001 — resolution must never mute the fallback
+ return surface
+ except Exception as exc: # noqa: BLE001 — an unbuildable emergency voice must not crash the turn
log.warning(
- "Realtime surface TTS resolution failed (%s) — using the pipeline "
- "TTS chain.",
+ "Realtime surface TTS resolution failed (%s) — the emergency "
+ "re-render stays text-only (strict mode separation).",
exc,
)
- return pipeline_tts
+ return None
def _effective_primary_voice(family: str, tts_cfg: Any) -> str | None:
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index aba6a48e0e..3457597e4c 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -6200,23 +6200,39 @@ class SpeechPipeline:
)
scrubbed = scrub_for_voice(text, language=language)
cleaned = scrubbed.cleaned.strip()
- if cleaned and not getattr(self, "_muted", False):
+ surface_tts = (
+ self._resolve_realtime_surface_tts(
+ self._active_realtime_provider
+ )
+ if cleaned and not getattr(self, "_muted", False)
+ else None
+ )
+ if cleaned and surface_tts is None and not getattr(self, "_muted", False):
+ # STRICT mode separation (maintainer mandate 2026-07-17):
+ # a realtime session must never spend pipeline credentials
+ # or speak with the pipeline's [tts] voice — not even as a
+ # last resort. Without a realtime-scoped TTS the reply
+ # stays TEXT-ONLY (the transcript already carries it);
+ # this log line is the honest audible-gap marker.
+ log.warning(
+ "Realtime surface fallback has no realtime-scoped TTS "
+ "for provider %r — keeping the turn text-only instead "
+ "of borrowing the pipeline voice (mode separation).",
+ self._active_realtime_provider,
+ )
+ if cleaned and surface_tts is not None:
# Realtime has already failed to render this grounded text.
- # 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.
+ # Re-render through the REALTIME-scoped TTS (same provider
+ # family + realtime credential slots + session voice —
+ # strict 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()
speaking = True
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,
@@ -9447,30 +9463,28 @@ class SpeechPipeline:
self._abort_playback_device()
return set()
- def _resolve_realtime_surface_tts(self, provider: str) -> Any:
+ def _resolve_realtime_surface_tts(self, provider: str) -> Any | None:
"""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.
+ STRICT separation (maintainer mandate 2026-07-17): resolves ONLY the
+ active realtime provider's own TTS family, keyed through the realtime
+ credential slots and speaking the session voice. The pipeline ``[tts]``
+ instance is never a candidate — ``None`` means "keep the turn
+ text-only". Cached per provider; never raises.
"""
- base = getattr(self, "_tts", None)
key = (provider or "").strip().lower()
- if not key or base is None:
- return base
+ if not key:
+ return None
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]
+ if cached is not None and cached[0] == key:
+ return cached[1]
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)
+ built = build_realtime_surface_tts(self._config, key)
+ except Exception: # noqa: BLE001 — the emergency voice must never break the turn
+ built = None
+ self._realtime_surface_tts_cache = (key, built)
return built
def _emit_spoken(
diff --git a/tests/unit/plugins/tts/test_realtime_surface_tts.py b/tests/unit/plugins/tts/test_realtime_surface_tts.py
index c28fe52396..a043dc6e2e 100644
--- a/tests/unit/plugins/tts/test_realtime_surface_tts.py
+++ b/tests/unit/plugins/tts/test_realtime_surface_tts.py
@@ -1,13 +1,16 @@
-"""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).
+"""STRICT mode separation for the realtime surface fallback voice (2026-07-17).
+
+Realtime and Pipeline are independent modes (maintainer mandate 2026-07-17):
+each must work with only its own API keys, and neither may fall back onto the
+other's providers or credentials — not even as a last resort. 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 `[tts]`
+primary was openrouter-tts.
+
+Forward guard: the emergency re-render resolves ONLY a same-family TTS keyed
+through the realtime credential slots; no candidate → ``None`` (text-only).
+Reverse guard: pipeline TTS credential resolution must never see a
+realtime-scoped key slot.
"""
from __future__ import annotations
@@ -16,11 +19,19 @@ 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.core.config import (
+ PROVIDER_SECRET_CANDIDATES,
+ override_provider_secrets,
+)
+from jarvis.plugins.tts import (
+ _TTS_SECRET_CANDIDATES,
+ _tts_has_credential,
+ build_realtime_surface_tts,
+)
from jarvis.plugins.tts.gemini_flash_tts import GeminiFlashTTS
+_REALTIME_PROVIDER_IDS = ("gemini-live", "openai-realtime")
+
def _cfg(voice: str = "Fenrir") -> SimpleNamespace:
return SimpleNamespace(
@@ -35,69 +46,102 @@ def _cfg(voice: str = "Fenrir") -> SimpleNamespace:
)
-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
+# ---------------------------------------------------------------------------
+# Forward direction: realtime emergency voice stays realtime-scoped.
+# ---------------------------------------------------------------------------
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)
+ tts = build_realtime_surface_tts(_cfg(), "gemini-live")
+ assert isinstance(tts, GeminiFlashTTS)
# The session voice carries over verbatim (shared prebuilt-voice catalog).
- assert tts.primary._default_voice == "Fenrir"
+ assert tts._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
+ assert tts._resolve_api_key() == "rt-scoped-key"
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"
+ tts = build_realtime_surface_tts(_cfg(voice="cedar"), "gemini-live")
+ assert isinstance(tts, GeminiFlashTTS)
+ assert tts._default_voice == "Charon"
-def test_keyless_realtime_provider_keeps_pipeline_chain() -> None:
- pipeline_tts = _PipelineTTS()
+def test_keyless_realtime_provider_yields_no_surface_tts() -> None:
with override_provider_secrets({"gemini-live": None}):
- tts = build_realtime_surface_tts(_cfg(), "gemini-live", pipeline_tts)
- assert tts is pipeline_tts
+ assert build_realtime_surface_tts(_cfg(), "gemini-live") is None
-def test_realtime_family_without_tts_sibling_keeps_pipeline_chain() -> None:
- pipeline_tts = _PipelineTTS()
+def test_realtime_family_without_tts_sibling_yields_no_surface_tts() -> None:
+ # A key alone is not enough: without a same-family TTS sibling the
+ # emergency re-render stays text-only — never the pipeline voice.
with override_provider_secrets({"openai-realtime": "some-key"}):
- tts = build_realtime_surface_tts(_cfg(), "openai-realtime", pipeline_tts)
- assert tts is pipeline_tts
+ assert build_realtime_surface_tts(_cfg(), "openai-realtime") is None
-def test_empty_provider_keeps_pipeline_chain() -> None:
- pipeline_tts = _PipelineTTS()
- assert build_realtime_surface_tts(_cfg(), "", pipeline_tts) is pipeline_tts
+def test_empty_provider_yields_no_surface_tts() -> None:
+ assert build_realtime_surface_tts(_cfg(), "") is None
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
+ assert build_realtime_surface_tts(_cfg(), "gemini-live") is None
def test_injected_api_key_wins_over_environment_lookup() -> None:
tts = GeminiFlashTTS(api_key="explicit-key")
assert tts._resolve_api_key() == "explicit-key"
+
+
+# ---------------------------------------------------------------------------
+# Reverse direction: pipeline resolution never sees realtime key slots.
+# ---------------------------------------------------------------------------
+
+
+def test_pipeline_tts_credential_map_lists_no_realtime_slots() -> None:
+ """Static guard: the pipeline TTS key-aware factory consults
+ ``_TTS_SECRET_CANDIDATES`` — a realtime-scoped slot appearing there would
+ silently let pipeline mode spend realtime credentials."""
+ for family, candidates in _TTS_SECRET_CANDIDATES.items():
+ for keyring_key, env_var in candidates:
+ assert not keyring_key.startswith("realtime_"), (
+ f"pipeline TTS family {family!r} lists realtime slot "
+ f"{keyring_key!r}"
+ )
+ assert "REALTIME" not in (env_var or ""), (
+ f"pipeline TTS family {family!r} lists realtime env var "
+ f"{env_var!r}"
+ )
+
+
+def test_realtime_slots_exist_only_under_realtime_provider_ids() -> None:
+ """Static guard: dedicated realtime slots live ONLY under the realtime
+ provider ids, so brain / Jarvis-Agent / pipeline resolution (which key off
+ their own family ids) can structurally never reach them."""
+ for provider, candidates in PROVIDER_SECRET_CANDIDATES.items():
+ for keyring_key, _env in candidates:
+ if keyring_key.startswith("realtime_"):
+ assert provider in _REALTIME_PROVIDER_IDS, (
+ f"realtime slot {keyring_key!r} leaked into provider "
+ f"{provider!r}"
+ )
+
+
+def test_pipeline_tts_cannot_see_a_realtime_only_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Behavioral guard: with ONLY the dedicated realtime Gemini key present,
+ the pipeline gemini-flash-tts family reads as keyless — pipeline mode
+ must not light up on a realtime-only install."""
+
+ def _secret(name: str, env_fallback: str | None = None, **_kw: object):
+ return "rt-only-key" if name == "realtime_gemini_api_key" else None
+
+ monkeypatch.setattr("jarvis.core.config.get_secret", _secret)
+ tts_cfg = SimpleNamespace(use_vertex=False)
+ assert _tts_has_credential("gemini-flash-tts", tts_cfg) is False
diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.py
index e75ba074d5..f404a3329a 100644
--- a/tests/unit/speech/test_realtime_mode.py
+++ b/tests/unit/speech/test_realtime_mode.py
@@ -296,7 +296,14 @@ async def test_unsafe_output_cancel_stops_playback_and_returns_to_listening(
) -> None:
pipe = _pipe()
fallback_pcm = b"\x06\x00" * 32
- pipe._tts = _FakeTTS(fallback_pcm)
+ # Strict mode separation: the audible emergency phrase comes from the
+ # REALTIME-scoped TTS; the pipeline [tts] instance must stay untouched.
+ pipe._tts = _FakeTTS(b"\x0f\x00" * 32)
+ surface_tts = _FakeTTS(fallback_pcm)
+ monkeypatch.setattr(
+ "jarvis.plugins.tts.build_realtime_surface_tts",
+ lambda _cfg, _provider: surface_tts,
+ )
cancel_delivered = asyncio.Event()
built: dict[str, object] = {}
@@ -330,7 +337,8 @@ async def test_unsafe_output_cancel_stops_playback_and_returns_to_listening(
assert pipe._player.stopped >= 1
assert fallback_pcm in pipe._player.pcm
- assert pipe._tts.calls == [("An error occurred.", "en-US")]
+ assert surface_tts.calls == [("An error occurred.", "en-US")]
+ assert pipe._tts.calls == []
assert pipe._test_states[-2:] == [
pipeline_mod.TurnTakingState.JARVIS_SPEAKING,
pipeline_mod.TurnTakingState.LISTENING,
@@ -358,10 +366,9 @@ async def test_error_spoken_renders_through_realtime_scoped_surface_tts(
resolved: dict[str, object] = {}
spoken_delivered = asyncio.Event()
- def _scoped_surface_tts(cfg, provider, base):
+ def _scoped_surface_tts(cfg, provider):
resolved["cfg"] = cfg
resolved["provider"] = provider
- resolved["base"] = base
return surface_tts
monkeypatch.setattr(
@@ -390,10 +397,9 @@ async def test_error_spoken_renders_through_realtime_scoped_surface_tts(
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.
+ # The resolver received the active realtime provider, and the scoped
+ # instance did ALL the speaking — the pipeline [tts] stayed untouched.
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
@@ -402,6 +408,52 @@ async def test_error_spoken_renders_through_realtime_scoped_surface_tts(
assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY
+async def test_error_spoken_without_realtime_scoped_tts_never_borrows_pipeline_voice(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """STRICT mode separation (maintainer mandate 2026-07-17): a realtime
+ provider without a same-family TTS sibling keeps the emergency re-render
+ TEXT-ONLY. The pipeline's [tts] instance is never a last resort — its
+ credentials belong to a different, independent mode."""
+ pipe = _pipe()
+ pipeline_tts = _FakeTTS(b"\x07\x00" * 32)
+ pipe._tts = pipeline_tts
+ spoken_delivered = asyncio.Event()
+
+ 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"])
+
+ # No build_realtime_surface_tts mock: the REAL resolver runs and finds no
+ # TTS sibling for the unmapped "fake-live" family.
+ 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 pipeline_tts.calls == []
+ assert pipe._player.pcm == []
+ # No JARVIS_SPEAKING flash for an unspoken turn.
+ assert pipeline_mod.TurnTakingState.JARVIS_SPEAKING not in pipe._test_states
+
+ 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."""
@@ -448,7 +500,7 @@ async def test_error_spoken_voice_hint_is_capability_gated(
monkeypatch.setattr(
"jarvis.plugins.tts.build_realtime_surface_tts",
- lambda _cfg, _provider, _base: surface_tts,
+ lambda _cfg, _provider: surface_tts,
)
class _VoiceHintSession(_HandshakeOnlyRealtimeSession):