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): isolate live voice from classic pipeline
Ruben Lütkec1513be7a8dd
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 9238a9e0cf..5db955a135 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -3612,20 +3612,33 @@ session (text input would interrupt the provider's response lifecycle), and`_on_announcement` treated every refusal as "use classic TTS" — it neverdistinguished a BUSY live call from a DEAD one.-**Fix.** `RealtimeVoiceSession.is_active` + a gate in `_on_announcement`:-while a healthy live call owns the voice, ephemeral preamble/progress lines-are dropped (stale by the time the live model could speak them) and owed-readbacks are parked in `_deferred_announcements`, whose existing-turn-boundary replay hands them to the now-idle live model. Classic TTS-speaks only once the call has ended or failed.--**Guards.** `tests/unit/speech/test_realtime_announcement_bridge.py` — busy-call defers owed readbacks and drops preambles, dead call keeps the classic-fallback, deferred readback reaches the idle live model at the boundary.+The 19:59 recurrence exposed a second state bug. OpenAI rejected a raced+`response.create` with `conversation_already_has_active_response`; the receive+pump continued and the realtime call remained usable, but the wrapper set its+sticky `_failed` flag. `is_active` then returned false, so a later delegated+`brain.router.ack` preamble crossed into classic TTS even though the accepted+realtime socket was still carrying the conversation.++**Fix.** Voice ownership now follows the accepted realtime handle, never a+provider-health flag. Until that lifecycle fully unwinds, ephemeral+preamble/progress lines are dropped and owed readbacks are parked; classic TTS+cannot speak into the call. Provider events carry explicit recoverability, so+the OpenAI active-response collision no longer poisons a usable session, while+terminal events end the receive pump. The OpenAI adapter also serializes every+local `response.create` against `response.done`, preventing the collision.+Finally, realtime tool mode defaults to `direct`: the live model calls the+supervisor safety gateway with its own realtime credential and does not invoke+the classic Brain/TTS pipeline. Legacy `delegate` remains an explicit opt-in.++**Guards.** `tests/unit/speech/test_realtime_announcement_bridge.py` and+`test_announcement_bridge.py` cover voice ownership; realtime pipeline+isolation, autonomous defaults, error recoverability, and OpenAI response+serialization are covered under `tests/unit/realtime/`.**Class rule.** A voice surface has ONE voice at a time. Any fallback from-the live realtime voice to classic TTS must be gated on the live call being-GONE, never merely busy — "busy" means wait or drop, not switch voices.+the live realtime voice to classic TTS must be gated on the accepted call+handle being GONE, never merely busy or unhealthy — those states mean wait,+drop, or end the call, not switch voices mid-call.## BUG-050: run_shell on Windows echoes quoted commands instead of executing them (HIGH, 2026-07-13)diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex ba905932c6..ab383e52a7 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -1932,13 +1932,12 @@ class VoiceConfig(BaseModel):# reserved for an EXPLICIT user pick (mode present in the TOML), so a# fresh keyless install degrades silently instead of nagging every call.mode: str = "realtime"- # Realtime tool exposure. "delegate" (default) declares ONE action function- # (jarvis_action) that hands the user's spoken request to the classic- # router brain — full ToolExecutor safety path, two-turn voice confirm,- # spawn-worker escalation for heavy missions. "direct" declares every- # router tool individually via RealtimeToolBridge. Read once per session;- # unknown values fall back to "delegate".- realtime_tool_mode: str = "delegate"+ # Realtime tool exposure. "direct" (default) lets the realtime model call+ # every available tool through the supervisor safety gateway without a+ # classic Brain provider or TTS hop. "delegate" is a compatibility opt-in+ # that hands one jarvis_action call to the classic router brain. Read once+ # per session; unknown values fail closed to the autonomous direct mode.+ realtime_tool_mode: str = "direct"# Per-gap budget after which a stale pending fragment is silently# discarded (user-mandated 2026-05-26 — was: flushed/spoken). NOT a total# budget — every continuation resets the timer. Bumped from 8 s to 15 sdiff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex a92c4af574..ca2f7e9364 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -24,6 +24,7 @@ _INPUT_RATE = 24_000_OUTPUT_RATE = 24_000_HANDSHAKE_TIMEOUT_S = 12.0_RESPONSE_REQUEST_METADATA_KEY = "jarvis_request_id"+_RECOVERABLE_ERROR_CODES = frozenset({"conversation_already_has_active_response"})@dataclass(frozen=True, slots=True)@@ -41,15 +42,21 @@ class _ProviderEvent:is_final: bool = Falsems_played: int | None = Noneerror: str | None = None+ recoverable: bool = Falseitem_id: str | None = Nonecall_id: str | None = Nonetool_name: str | None = Nonetool_args: dict[str, Any] | None = None+def _error_code(event: Any) -> str:+ error = getattr(event, "error", None)+ return str(getattr(error, "code", "") or "").strip()++def _error_message(event: Any) -> str:error = getattr(event, "error", None)- code = str(getattr(error, "code", "") or "").strip()+ code = _error_code(event)message = str(getattr(error, "message", "") or "").strip()if code and message:return f"{code}: {message}"[:800]@@ -148,6 +155,13 @@ class _OpenAIRealtimeSession:# any PCM reaches the speaker.self._pending_response_markers: set[str] = set()self._accepted_response_ids: set[str] = set()+ # OpenAI accepts only one active response per conversation. Every+ # local response request (native reply, tool continuation, trusted+ # update) passes this lifecycle boundary so concurrent callers cannot+ # race two response.create operations onto the same session.+ self._response_create_lock = asyncio.Lock()+ self._response_idle = asyncio.Event()+ self._response_idle.set()self._closed = Falseasync def wait_until_ready(self) -> None:@@ -245,13 +259,19 @@ class _OpenAIRealtimeSession:self._accepted_response_ids.discard(response_id)elif len(self._accepted_response_ids) == 1:self._accepted_response_ids.pop()+ self._response_idle.set()if self._response_had_tool_calls:self._tool_response_done_seen = Trueawait self._continue_after_tools_if_ready()else:yield _ProviderEvent(type="turn_complete")elif event_type == "error":- yield _ProviderEvent(type="error", error=_error_message(event))+ error_code = _error_code(event)+ yield _ProviderEvent(+ type="error",+ error=_error_message(event),+ recoverable=error_code in _RECOVERABLE_ERROR_CODES,+ )async def update_session(self,@@ -315,7 +335,10 @@ class _OpenAIRealtimeSession:self._tool_response_done_seen = Falseself._pending_tool_call_ids.clear()self._last_item_id = ""- await self._conn.response.cancel()+ try:+ await self._conn.response.cancel()+ finally:+ self._response_idle.set()async def send_tool_result(self, call_id: str, name: str, result: dict[str, Any]@@ -343,18 +366,22 @@ class _OpenAIRealtimeSession:await self._create_response()async def _create_response(self, *, tool_choice: Any = None) -> None:- marker = uuid4().hex- self._pending_response_markers.add(marker)- response: dict[str, Any] = {- "metadata": {_RESPONSE_REQUEST_METADATA_KEY: marker},- }- if tool_choice is not None:- response["tool_choice"] = tool_choice- try:- await self._conn.response.create(response=response)- except BaseException:- self._pending_response_markers.discard(marker)- raise+ async with self._response_create_lock:+ await self._response_idle.wait()+ self._response_idle.clear()+ marker = uuid4().hex+ self._pending_response_markers.add(marker)+ response: dict[str, Any] = {+ "metadata": {_RESPONSE_REQUEST_METADATA_KEY: marker},+ }+ if tool_choice is not None:+ response["tool_choice"] = tool_choice+ try:+ await self._conn.response.create(response=response)+ except BaseException:+ self._pending_response_markers.discard(marker)+ self._response_idle.set()+ raise@staticmethoddef _event_response_id(event: Any) -> str:@@ -428,6 +455,7 @@ class _OpenAIRealtimeSession:self._closed = Trueself._pending_response_markers.clear()self._accepted_response_ids.clear()+ self._response_idle.set()try:await self._connection_cm.__aexit__(None, None, None)finally:diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.pyindex eebdf6a310..63054cb8e8 100644--- a/jarvis/realtime/protocol.py+++ b/jarvis/realtime/protocol.py@@ -36,6 +36,10 @@ class RealtimeEvent:is_final: bool = Falsems_played: int | None = None # speech_started: ms of our audio already hearderror: str | None = None+ # A recoverable provider event reports a rejected operation while the+ # duplex transport remains usable. It must not end voice ownership or+ # trigger the classic pipeline.+ recoverable: bool = Falseitem_id: str | None = Nonecall_id: str | None = Nonetool_name: str | None = Nonediff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 404998c385..e0fa20fd2e 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -393,12 +393,12 @@ class RealtimeVoiceSession:self._brain = brainmode = str(getattr(- getattr(self._config, "voice", None), "realtime_tool_mode", "delegate"+ getattr(self._config, "voice", None), "realtime_tool_mode", "direct")- or "delegate"+ or "direct").strip().lower()if mode not in {"delegate", "direct"}:- mode = "delegate"+ mode = "direct"self._tool_mode = mode# Delegate mode needs only a callable brain (the boot proxy and the# real BrainManager both qualify); an explicitly injected bridge@@ -406,12 +406,12 @@ class RealtimeVoiceSession:self._delegate_enabled = (mode == "delegate" and tool_bridge is None and callable(brain))- if tool_bridge is None and brain is not None and not self._delegate_enabled:+ if tool_bridge is None and not self._delegate_enabled:try:from jarvis.realtime.tools import RealtimeToolBridge- tool_bridge = RealtimeToolBridge.from_brain(- brain, language=self._language+ tool_bridge = RealtimeToolBridge.from_supervisor_gateway(+ language=self._language)except Exception: # noqa: BLE001 — conversation still works without toolslog.warning("Realtime tool bridge is unavailable", exc_info=True)@@ -1148,13 +1148,27 @@ class RealtimeVoiceSession:message = safe_preview(event.error or "provider error", max_chars=800)+ recoverable = bool(getattr(event, "recoverable", False))+ log.warning(+ "realtime[%s] %s provider error: %s",+ self.session_id,+ "recoverable" if recoverable else "terminal",+ message,+ )+ await self._publish_error(+ "RealtimeProviderError", message, recoverable=recoverable+ )+ if recoverable:+ await self._send_json(+ {"type": "provider_warning", "error": message}+ )+ continueself._failure_detail = messageself._failed.set()- log.warning("realtime[%s] provider error: %s", self.session_id, message)- await self._publish_error(- "RealtimeProviderError", message, recoverable=True+ await self._send_json(+ {"type": "provider_error", "error": message})- await self._send_json({"type": "provider_error", "error": message})+ breakexcept asyncio.CancelledError:raiseexcept Exception as exc: # noqa: BLE001 — AP-20: pump error is terminaldiff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pyindex 7b60922ce7..96bbd73789 100644--- a/jarvis/realtime/tools.py+++ b/jarvis/realtime/tools.py@@ -103,13 +103,20 @@ class RealtimeToolBridge:self._last_user_text = ""@classmethod- def from_brain(cls, _brain: Any, *, language: str) -> RealtimeToolBridge | None:- """Build from the public supervisor gateway registered by Brain factory."""+ def from_supervisor_gateway(+ cls, *, language: str+ ) -> RealtimeToolBridge | None:+ """Build from the safety gateway without requiring a classic brain call."""gateway = runtime_refs.get_supervisor_tool_gateway()if gateway is None or not gateway.catalog():return Nonereturn cls(gateway=gateway, language=language)+ @classmethod+ def from_brain(cls, _brain: Any, *, language: str) -> RealtimeToolBridge | None:+ """Compatibility wrapper for callers using the former constructor."""+ return cls.from_supervisor_gateway(language=language)+def _read_descriptors(self,tools_override: dict[str, Any] | None = None,diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex fbab92a58d..0fe1c68951 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -3331,11 +3331,16 @@ class SpeechPipeline:await self._transition("IDLE" if hungup else "LISTENING")def _realtime_session_owns_voice(self) -> bool:- """True while a healthy live realtime call is the only valid voice."""+ """True while an accepted realtime call is the only valid voice.++ Provider health is deliberately irrelevant here. The handle is cleared+ only after the realtime lifecycle unwinds; until then, classic TTS must+ stay silent rather than becoming a second voice inside the same call.+ """if getattr(self, "_active_voice_mode", None) != "realtime":return Falsesession = getattr(self, "_active_realtime_handle", None)- return bool(session is not None and getattr(session, "is_active", False))+ return session is not Noneasync def _deliver_announcement_via_realtime(self,@@ -3346,9 +3351,9 @@ class SpeechPipeline:) -> bool:"""Offer a standardized readback to the active duplex model.- The live wrapper rejects busy, failed, or unsupported sessions. Any- rejection returns to ``_on_announcement`` and preserves the established- key-aware classic TTS path.+ The live wrapper rejects busy, failed, or unsupported sessions. While+ the accepted realtime handle still exists, ``_on_announcement`` drops+ or defers that output; only a fully unwound call may use classic TTS."""if getattr(self, "_active_voice_mode", None) != "realtime":return Falsediff --git a/tests/unit/realtime/test_factory.py b/tests/unit/realtime/test_factory.pyindex 5bbbe3e1b2..3dd3aee4df 100644--- a/tests/unit/realtime/test_factory.py+++ b/tests/unit/realtime/test_factory.py@@ -6,6 +6,7 @@ from types import SimpleNamespaceimport pytest+from jarvis.core.config import VoiceConfigfrom jarvis.realtime.factory import (_provider_candidates,_resolve_realtime_provider,@@ -120,6 +121,29 @@ def test_pipeline_mode_never_builds_realtime_session(monkeypatch):)+def test_realtime_tool_mode_defaults_to_autonomous_direct_execution() -> None:+ assert VoiceConfig().realtime_tool_mode == "direct"+++def test_one_realtime_key_builds_without_a_classic_brain(monkeypatch) -> None:+ _fake_registry(monkeypatch, {"gemini"})++ session = build_realtime_session(+ cfg=_cfg(provider="openai-realtime"),+ bus=None,+ session_id="realtime-only",+ send_binary=lambda _data: None,+ send_json=lambda _message: None,+ brain=None,+ )++ assert session is not None+ assert session._brain is None+ assert session._tool_mode == "direct"+ assert session._delegate_enabled is False+ assert [provider.name for provider in session._providers] == ["gemini-live"]++def test_realtime_without_any_key_degrades_to_pipeline(monkeypatch):_fake_registry(monkeypatch, set())assert (diff --git a/tests/unit/realtime/test_openai_realtime.py b/tests/unit/realtime/test_openai_realtime.pyindex 7fe1af3f98..85c62b1918 100644--- a/tests/unit/realtime/test_openai_realtime.py+++ b/tests/unit/realtime/test_openai_realtime.py@@ -2,6 +2,7 @@from __future__ import annotations+import asyncioimport base64from types import SimpleNamespacefrom typing import Any@@ -488,6 +489,87 @@ async def test_handshake_error_rejects_session(monkeypatch: pytest.MonkeyPatch)assert holder_factory["client"].closed is True+ ("code", "recoverable"),+ [+ ("conversation_already_has_active_response", True),+ ("rate_limit_exceeded", False),+ ],+)+async def test_runtime_errors_preserve_provider_recoverability(+ monkeypatch: pytest.MonkeyPatch,+ code: str,+ recoverable: bool,+) -> None:+ holder = _patch_openai_client(monkeypatch)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ conn = holder["client"].realtime.last_conn+ conn._events = iter(+ [+ SimpleNamespace(+ type="error",+ error=SimpleNamespace(code=code, message="Provider rejected operation"),+ )+ ]+ )+ session._events = conn.__aiter__()++ event = await anext(session.receive())++ assert event.type == "error"+ assert event.recoverable is recoverable+ assert code in event.error+ await session.close()+++async def test_response_requests_wait_for_the_active_response_boundary(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ holder = _patch_openai_client(monkeypatch)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ conn = holder["client"].realtime.last_conn++ await session.send_text("First trusted update")+ first_marker = conn.response_create_payloads[0]["response"]["metadata"][+ "jarvis_request_id"+ ]+ second = asyncio.create_task(session.send_text("Second trusted update"))+ await asyncio.sleep(0)++ assert second.done() is False+ assert conn.response_creates == 1++ conn._events = iter(+ [+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(+ id="resp-first",+ metadata={"jarvis_request_id": first_marker},+ ),+ ),+ SimpleNamespace(+ type="response.done",+ response=SimpleNamespace(id="resp-first"),+ ),+ ]+ )+ session._events = conn.__aiter__()++ event = await anext(session.receive())+ await second++ assert event.type == "turn_complete"+ assert conn.response_creates == 2+ await session.close()++@pytest.mark.asyncioasync def test_keyless_provider_is_unavailable() -> None:assert await OpenAIRealtimeProvider().can_open_duplex_session() is Falsediff --git a/tests/unit/realtime/test_pipeline_isolation.py b/tests/unit/realtime/test_pipeline_isolation.pynew file mode 100644index 0000000000..f4554f1df7--- /dev/null+++ b/tests/unit/realtime/test_pipeline_isolation.py@@ -0,0 +1,143 @@+"""Regression guards for realtime ownership and provider error isolation."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.realtime.protocol import RealtimeEvent+from jarvis.realtime.session import RealtimeVoiceSession+++class _EventSession:+ session_id = "provider-session"+ supports_tool_updates = True+ creates_responses_automatically = False+ isolates_response_generations = True++ def __init__(self, event: RealtimeEvent, *, stay_open: bool) -> None:+ self._event = event+ self._stay_open = stay_open+ self.processed = asyncio.Event()+ self.release = asyncio.Event()+ self.closed = False++ async def send_audio(self, _chunk: Any) -> None:+ return None++ async def receive(self):+ yield self._event+ self.processed.set()+ if self._stay_open:+ await self.release.wait()++ async def update_session(self, **_kwargs: Any) -> None:+ return None++ async def request_response(self, **_kwargs: Any) -> None:+ return None++ async def send_text(self, _text: str) -> None:+ return None++ async def truncate(self, _audio_end_ms: int) -> None:+ return None++ async def interrupt(self) -> None:+ return None++ async def send_tool_result(+ self, _call_id: str, _name: str, _result: dict[str, Any]+ ) -> None:+ return None++ async def close(self) -> None:+ self.closed = True+ self.release.set()+++class _Provider:+ name = "realtime-only"+ supports_realtime = True+ input_sample_rate = 16_000+ output_sample_rate = 24_000++ def __init__(self, event: RealtimeEvent, *, stay_open: bool) -> None:+ self.session = _EventSession(event, stay_open=stay_open)++ async def can_open_duplex_session(self) -> bool:+ return True++ async def open_session(self, _config: Any) -> _EventSession:+ return self.session+++def _config() -> SimpleNamespace:+ return SimpleNamespace(+ brain=SimpleNamespace(reply_language="en", providers={}),+ stt=SimpleNamespace(language="auto"),+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="direct"),+ latency=SimpleNamespace(enabled=False),+ )+++def _wrapper(provider: _Provider, messages: list[dict[str, Any]]) -> RealtimeVoiceSession:+ async def _send_json(message: dict[str, Any]) -> None:+ messages.append(message)++ async def _send_binary(_data: bytes) -> None:+ return None++ return RealtimeVoiceSession(+ session_id="pipeline-isolation",+ send_binary=_send_binary,+ send_json=_send_json,+ provider=provider,+ config=_config(),+ bus=None,+ brain=None,+ )+++async def test_recoverable_provider_error_keeps_realtime_session_healthy() -> None:+ messages: list[dict[str, Any]] = []+ provider = _Provider(+ RealtimeEvent(+ type="error",+ error="conversation_already_has_active_response",+ recoverable=True,+ ),+ stay_open=True,+ )+ session = _wrapper(provider, messages)++ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(provider.session.processed.wait(), timeout=1.0)++ assert session.failed is False+ assert session.is_active is True+ assert any(message["type"] == "provider_warning" for message in messages)+ assert not any(message["type"] == "provider_error" for message in messages)+ await session.end(reason="test")+++async def test_terminal_provider_error_keeps_voice_until_teardown() -> None:+ messages: list[dict[str, Any]] = []+ provider = _Provider(+ RealtimeEvent(type="error", error="fatal provider error"),+ stay_open=False,+ )+ session = _wrapper(provider, messages)++ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(session.wait_finished(), timeout=1.0)++ assert session.failed is True+ assert any(message["type"] == "provider_error" for message in messages)+ await session.end(reason="test")+ assert session.is_active is Falsediff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 453bd2440c..e1ab673e77 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -1650,7 +1650,7 @@ class _StubExecutor:return ToolResult(success=True, output="opened")-def _delegate_cfg(tool_mode=None):+def _delegate_cfg(tool_mode="delegate"):cfg = _cfg()if tool_mode is not None:cfg.voice.realtime_tool_mode = tool_mode@@ -1666,7 +1666,7 @@ def _session(*,brain=None,tool_bridge=None,- tool_mode=None,+ tool_mode="delegate",jsons=None,binaries=None,bus=None,diff --git a/tests/unit/realtime/test_tools.py b/tests/unit/realtime/test_tools.pyindex 431e1a1e3e..f30f05c54c 100644--- a/tests/unit/realtime/test_tools.py+++ b/tests/unit/realtime/test_tools.py@@ -89,6 +89,22 @@ def test_declaration_uses_a_cross_provider_safe_wire_name():assert declaration["parameters"]["required"] == ["app_name"]+def test_supervisor_gateway_bridge_needs_no_classic_brain_argument(+ wire_gateway,+) -> None:+ tool = FakeTool("open_app")+ manager = SimpleNamespace(+ _tools={"open_app": tool},+ _tool_executor=FakeExecutor(),+ )+ wire_gateway(manager)++ bridge = RealtimeToolBridge.from_supervisor_gateway(language="en")++ assert bridge is not None+ assert [item["name"] for item in bridge.declarations] == ["open_app"]++@pytest.mark.asyncioasync def test_available_tool_runs_only_through_tool_executor():bridge, tool, executor = _bridge()diff --git a/tests/unit/speech/test_announcement_bridge.py b/tests/unit/speech/test_announcement_bridge.pyindex cc28a8945c..808b708a0f 100644--- a/tests/unit/speech/test_announcement_bridge.py+++ b/tests/unit/speech/test_announcement_bridge.py@@ -130,6 +130,41 @@ async def test_announcement_english_language_passthrough() -> None:assert tts.calls == [("one moment please", "en-US")]+async def test_accepted_realtime_call_never_falls_through_to_classic_tts() -> None:+ class _RejectedRealtimeDelivery:+ # The provider may already have reported a terminal error, but the+ # accepted call still owns the output surface until lifecycle teardown.+ is_active = False++ def __init__(self) -> None:+ self.calls = 0++ async def deliver_announcement(self, **_kwargs) -> bool: # noqa: ANN003+ self.calls += 1+ return False++ bus = EventBus()+ tts = FakeTTS()+ player = FakePlayer()+ pipeline = _make_pipeline(tts, bus, player)+ realtime = _RejectedRealtimeDelivery()+ pipeline._active_voice_mode = "realtime"+ pipeline._active_realtime_handle = realtime++ await bus.publish(+ AnnouncementRequested(+ text="I am gathering the detailed information now.",+ language="en",+ kind="preamble",+ )+ )++ assert realtime.calls == 1+ assert tts.calls == []+ assert player.plays == 0++@pytest.mark.asyncioasync def test_announcement_bypass_skips_brain() -> None:"""Announcements must not touch the brain path (TTS bypass).diff --git a/tests/unit/speech/test_realtime_announcement_bridge.py b/tests/unit/speech/test_realtime_announcement_bridge.pyindex 5fa01c173d..4845cc384d 100644--- a/tests/unit/speech/test_realtime_announcement_bridge.py+++ b/tests/unit/speech/test_realtime_announcement_bridge.py@@ -45,9 +45,8 @@ class _FakePlayer:class _FakeRealtimeHandle:- def __init__(self, *, accepted: bool, is_active: bool = True) -> None:+ def __init__(self, *, accepted: bool) -> None:self.accepted = accepted- self.is_active = is_activeself.calls: list[dict[str, object]] = []async def deliver_announcement(self, **kwargs: object) -> bool:@@ -55,12 +54,12 @@ class _FakeRealtimeHandle:return self.accepted-def _pipeline(*, accepted: bool, is_active: bool = True) -> tuple[+def _pipeline(*, accepted: bool) -> tuple[SpeechPipeline, _FakeTTS, _FakePlayer, _FakeRealtimeHandle]:tts = _FakeTTS()player = _FakePlayer()- realtime = _FakeRealtimeHandle(accepted=accepted, is_active=is_active)+ realtime = _FakeRealtimeHandle(accepted=accepted)pipeline = SpeechPipeline(tts=tts, enable_whisper_wake=False)pipeline._player = player # type: ignore[assignment]pipeline._active_voice_mode = "realtime"@@ -97,8 +96,9 @@ async def test_subagent_readback_is_handed_to_active_realtime_model() -> None:@pytest.mark.asyncioasync def test_dead_session_rejection_preserves_classic_tts_fallback() -> None:- """Classic TTS remains the honest surface once the live call ended."""- pipeline, tts, player, realtime = _pipeline(accepted=False, is_active=False)+ """Classic TTS resumes only after the realtime handle is fully removed."""+ pipeline, tts, player, realtime = _pipeline(accepted=False)+ pipeline._active_realtime_handle = Noneawait pipeline._on_announcement(AnnouncementRequested(@@ -108,7 +108,7 @@ async def test_dead_session_rejection_preserves_classic_tts_fallback() -> None:))- assert len(realtime.calls) == 1+ assert realtime.calls == []assert tts.calls == [("The research report is ready.", "en-US")]assert player.plays == 1@@ -116,7 +116,7 @@ async def test_dead_session_rejection_preserves_classic_tts_fallback() -> None:@pytest.mark.asyncioasync def test_busy_live_session_defers_owed_readback() -> None:"""A healthy busy call parks the readback; no second voice speaks."""- pipeline, tts, player, realtime = _pipeline(accepted=False, is_active=True)+ pipeline, tts, player, realtime = _pipeline(accepted=False)event = AnnouncementRequested(text="The research report is ready.",@@ -134,7 +134,7 @@ async def test_busy_live_session_defers_owed_readback() -> None:@pytest.mark.asyncioasync def test_busy_live_session_drops_ephemeral_preamble() -> None:"""A stale preamble is dropped, never spoken by the classic voice."""- pipeline, tts, player, realtime = _pipeline(accepted=False, is_active=True)+ pipeline, tts, player, realtime = _pipeline(accepted=False)await pipeline._on_announcement(AnnouncementRequested(@@ -153,7 +153,7 @@ async def test_busy_live_session_drops_ephemeral_preamble() -> None:@pytest.mark.asyncioasync def test_deferred_readback_is_replayed_to_the_idle_live_model() -> None:"""At the turn boundary the parked readback reaches the live voice."""- pipeline, tts, player, realtime = _pipeline(accepted=False, is_active=True)+ pipeline, tts, player, realtime = _pipeline(accepted=False)event = AnnouncementRequested(text="The research report is ready.",