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): cool down repeated provider-down and recovery notices (BUG-089)

Ruben Lütkeb08b823d316d
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 2c0879ea2b..cb656d6058 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -67,6 +67,11 @@ _HANGUP_BUFFER_MAX_CHARS = 300
# be dated (estimated playback drain, BUG-089). Bounds a runaway estimate
# from a mis-reported sample rate; real replies stay far below it.
_ECHO_HORIZON_MAX_S = 120.0
+# One canned outage/recovery notice per window, aligned with the brain
+# chain's RateLimitTracker cooldown: while the chain is cooling down, every
+# turn would re-speak the same apology — exactly the audio the self-talk
+# loop feeds on (BUG-089). Repeats inside the window stay silent + logged.
+_OUTAGE_NOTICE_COOLDOWN_S = 30.0
# Declared to the realtime model alongside the bridge tools, but handled by
# the session itself: ending the call is surface lifecycle (like the hotkey),
# not a risk-tiered Jarvis tool, and must work even without a tool bridge.
@@ -800,6 +805,7 @@ class RealtimeVoiceSession:
# a turn — otherwise the brain answers its own speaker echo forever.
self._echo_guard = SelfEchoGuard()
self._echo_playback_horizon = 0.0
+ self._last_outage_notice_at = float("-inf")
self._provider_output_probe = ""
self._executed_tool_names: set[str] = set()
self._direct_tool_results: list[tuple[str, dict[str, Any]]] = []
@@ -2538,6 +2544,47 @@ class RealtimeVoiceSession:
or self._executed_tool_names
)
+ def _outage_notice_allowed(self) -> bool:
+ """One canned outage/recovery notice per cooldown window.
+
+ Returns True and stamps the window when speaking is allowed; False
+ means the caller must stay silent AND keep the phrase out of
+ ``_output_transcript`` — the audible record must never claim words
+ the user did not hear (BUG-056 class).
+ """
+ now = time.monotonic()
+ if now - self._last_outage_notice_at >= _OUTAGE_NOTICE_COOLDOWN_S:
+ self._last_outage_notice_at = now
+ return True
+ return False
+
+ def _suppress_repeated_outage_notice(
+ self, turn_state: _DelegateTurnState
+ ) -> bool:
+ """True when this turn's reply is a repeat provider-down apology.
+
+ One outage notice per window is honest; re-speaking it on every turn
+ is the self-talk loop's fuel (BUG-089): each spoken apology can echo
+ back as the next "user" turn while the chain's rate-limit cooldown
+ never expires. Suppression marks the turn delivered so nothing is
+ spoken and the late-result queue stays empty. A turn with pending
+ native tool calls is never suppressed — the provider protocol
+ requires those calls to be answered.
+ """
+ if turn_state.pending_tool_calls:
+ return False
+ if not bool(getattr(self._brain, "_last_turn_all_failed", False)):
+ return False
+ if self._outage_notice_allowed():
+ return False
+ turn_state.delivery_started = True
+ log.info(
+ "realtime[%s] provider-down notice suppressed (repeat within %.0fs)",
+ self.session_id,
+ _OUTAGE_NOTICE_COOLDOWN_S,
+ )
+ return True
+
async def _recover_empty_provider_turn(self) -> bool:
"""Route a content-bearing turn away from a provider's empty response.
@@ -2569,9 +2616,18 @@ class RealtimeVoiceSession:
if not self._last_user_text:
if self._input_turn_observed:
- fallback_text = self._gate.fallback_phrase()
- self._output_transcript.append(fallback_text)
- await self._send_json(self._surface_speech_message(fallback_text))
+ if self._outage_notice_allowed():
+ fallback_text = self._gate.fallback_phrase()
+ self._output_transcript.append(fallback_text)
+ await self._send_json(
+ self._surface_speech_message(fallback_text)
+ )
+ else:
+ log.info(
+ "realtime[%s] empty-turn recovery notice suppressed "
+ "(repeat within cooldown)",
+ self.session_id,
+ )
return False
if self._direct_tool_results:
@@ -2617,14 +2673,32 @@ class RealtimeVoiceSession:
if self._executed_tool_names:
from jarvis.voice.action_phrases import action_phrase
- fallback_text = action_phrase("cu_done", self._language)
- self._output_transcript.append(fallback_text)
- await self._send_json(self._surface_speech_message(fallback_text))
+ if self._outage_notice_allowed():
+ fallback_text = action_phrase("cu_done", self._language)
+ self._output_transcript.append(fallback_text)
+ await self._send_json(
+ self._surface_speech_message(fallback_text)
+ )
+ else:
+ log.info(
+ "realtime[%s] empty-turn recovery notice suppressed "
+ "(repeat within cooldown)",
+ self.session_id,
+ )
return False
if self._brain is None:
- fallback_text = self._gate.fallback_phrase()
- self._output_transcript.append(fallback_text)
- await self._send_json(self._surface_speech_message(fallback_text))
+ if self._outage_notice_allowed():
+ fallback_text = self._gate.fallback_phrase()
+ self._output_transcript.append(fallback_text)
+ await self._send_json(
+ self._surface_speech_message(fallback_text)
+ )
+ else:
+ log.info(
+ "realtime[%s] empty-turn recovery notice suppressed "
+ "(repeat within cooldown)",
+ self.session_id,
+ )
return False
self._delegate_required_for_turn = True
@@ -3682,6 +3756,19 @@ class RealtimeVoiceSession:
self._executed_tool_names.add(str(_DELEGATE_DECLARATION["name"]))
if self._ended or self._session is None:
return
+ if self._suppress_repeated_outage_notice(turn_state):
+ if not bool(
+ getattr(
+ self._session, "creates_responses_automatically", False
+ )
+ ):
+ # No response was requested for this turn and none will be:
+ # close the turn locally so the surface leaves PROCESSING
+ # (same local-boundary pattern as the held-turn_complete and
+ # rebuild paths).
+ await self._send_json({"type": "turn_complete"})
+ await self._publish_turn_completed()
+ return
if not self._delegate_turn_is_active(turn_id, turn_state):
self._queue_late_delegate_result(turn_state)
return
diff --git a/tests/unit/realtime/test_outage_notice_cooldown.py b/tests/unit/realtime/test_outage_notice_cooldown.py
new file mode 100644
index 0000000000..afd3441659
--- /dev/null
+++ b/tests/unit/realtime/test_outage_notice_cooldown.py
@@ -0,0 +1,226 @@
+"""BUG-089: repeated provider-down / recovery notices cool down.
+
+While the brain chain's rate-limit cooldown is active, EVERY delegate turn
+returns the same canned apology; re-speaking it each turn is the self-talk
+loop's fuel (each spoken apology can echo back as the next "user" turn).
+The session speaks ONE outage notice per window, completes repeat turns
+silently, and never writes a suppressed phrase into the audible transcript
+record. German fixture strings quote the runtime voice product surface.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+import jarvis.realtime.session as session_module
+from jarvis.realtime.session import RealtimeVoiceSession, _DelegateTurnState
+
+APOLOGY = (
+ "Tut mir leid, mein Sprachmodell ist im Moment nicht erreichbar. " # i18n-allow: voice fixture
+ "Ich versuche es gleich erneut." # i18n-allow: voice fixture
+)
+
+
+class OutageBrain:
+ """Delegate brain whose whole chain is down: apology + all-failed flag."""
+
+ def __init__(self):
+ self._last_turn_all_failed = True
+ self.calls = 0
+
+ async def generate(self, text, **kwargs):
+ del text, kwargs
+ self.calls += 1
+ return APOLOGY
+
+
+class FakeTransport:
+ creates_responses_automatically = False
+
+ def __init__(self):
+ self.text_inputs = []
+ self.tool_results = []
+ self.interrupts = 0
+
+ async def send_text(self, text):
+ self.text_inputs.append(text)
+
+ async def send_tool_result(self, call_id, name, result):
+ self.tool_results.append((call_id, name, result))
+
+ async def request_response(self, *, required_tool=None):
+ del required_tool
+
+ async def interrupt(self):
+ self.interrupts += 1
+
+ async def close(self):
+ pass
+
+
+class FakeProvider:
+ name = "fake"
+ supports_realtime = True
+ input_sample_rate = 16000
+ output_sample_rate = 24000
+
+ def __init__(self):
+ self.opened_with = None
+
+ async def can_open_duplex_session(self):
+ return True
+
+ async def open_session(self, cfg):
+ self.opened_with = cfg
+ return FakeTransport()
+
+
+def _cfg():
+ return SimpleNamespace(
+ brain=SimpleNamespace(reply_language="auto", providers={}),
+ stt=SimpleNamespace(language="auto"),
+ voice=SimpleNamespace(mode="realtime"),
+ latency=SimpleNamespace(enabled=False),
+ )
+
+
+def _build(brain):
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="cooldown",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),
+ provider=FakeProvider(),
+ config=_cfg(),
+ bus=None,
+ brain=brain,
+ )
+ sess._session = FakeTransport()
+ return sess, jsons
+
+
+async def _delegate_turn(sess, turn_id):
+ """Run one deterministic delegate turn end to end and return its state."""
+ sess._turn_id = turn_id
+ state = _DelegateTurnState(
+ deterministic=True,
+ user_text="wie wird das wetter morgen in berlin", # i18n-allow: voice fixture
+ provider_boundary_seen=True,
+ )
+ state.input_boundary_ready.set()
+ state.provider_ready.set()
+ sess._delegate_turns[turn_id] = state
+ await sess._run_deterministic_delegate(turn_id, state)
+ return state
+
+
+def _spoken_notices(jsons):
+ return [m for m in jsons if m.get("type") == "error_spoken"]
+
+
+async def test_repeat_provider_down_apology_is_suppressed(monkeypatch):
+ monkeypatch.setattr(session_module, "_DELEGATE_READBACK_WAIT_S", 0.05)
+ brain = OutageBrain()
+ sess, jsons = _build(brain)
+ transport = sess._session
+
+ await _delegate_turn(sess, "t1")
+ first_text_inputs = len(transport.text_inputs)
+ first_notices = len(_spoken_notices(jsons))
+ assert first_text_inputs == 1, "first outage turn must be delivered"
+
+ state2 = await _delegate_turn(sess, "t2")
+ assert len(transport.text_inputs) == first_text_inputs, (
+ "repeat apology within the window must not be re-delivered"
+ )
+ assert len(_spoken_notices(jsons)) == first_notices, (
+ "repeat apology must not be re-spoken through the surface"
+ )
+ assert state2.delivery_started is True, (
+ "the suppressed turn counts as delivered (no late-result replay)"
+ )
+ # The suppressed manual-provider turn is closed locally.
+ assert any(m.get("type") == "turn_complete" for m in jsons)
+
+
+async def test_apology_speaks_again_after_the_window(monkeypatch):
+ monkeypatch.setattr(session_module, "_DELEGATE_READBACK_WAIT_S", 0.05)
+ monkeypatch.setattr(session_module, "_OUTAGE_NOTICE_COOLDOWN_S", 0.2)
+ brain = OutageBrain()
+ sess, _jsons = _build(brain)
+ transport = sess._session
+
+ await _delegate_turn(sess, "t1")
+ await asyncio.sleep(0.25)
+ await _delegate_turn(sess, "t2")
+ assert len(transport.text_inputs) == 2, (
+ "after the window a fresh outage notice is honest again"
+ )
+
+
+async def test_healthy_brain_reply_is_never_suppressed(monkeypatch):
+ monkeypatch.setattr(session_module, "_DELEGATE_READBACK_WAIT_S", 0.05)
+ brain = OutageBrain()
+ brain._last_turn_all_failed = False
+ sess, _jsons = _build(brain)
+ transport = sess._session
+
+ await _delegate_turn(sess, "t1")
+ await _delegate_turn(sess, "t2")
+ assert len(transport.text_inputs) == 2
+
+
+async def test_pending_native_tool_call_is_always_answered(monkeypatch):
+ """Provider protocol wins: a native function call must get its result."""
+ monkeypatch.setattr(session_module, "_DELEGATE_READBACK_WAIT_S", 0.05)
+ brain = OutageBrain()
+ sess, _jsons = _build(brain)
+ transport = sess._session
+
+ await _delegate_turn(sess, "t1")
+
+ sess._turn_id = "t2"
+ state = _DelegateTurnState(
+ deterministic=True,
+ user_text="wie wird das wetter", # i18n-allow: voice fixture
+ provider_boundary_seen=True,
+ )
+ state.pending_tool_calls.append(("call-1", "delegate"))
+ state.input_boundary_ready.set()
+ state.provider_ready.set()
+ sess._delegate_turns["t2"] = state
+ await sess._run_deterministic_delegate("t2", state)
+ assert transport.tool_results, (
+ "a pending native call is answered even inside the cooldown window"
+ )
+
+
+async def test_empty_turn_recovery_notice_cools_down():
+ brain = OutageBrain()
+ sess, jsons = _build(brain)
+ sess._input_turn_observed = True
+ sess._last_user_text = ""
+
+ sess._turn_id = "t1"
+ await sess._recover_empty_provider_turn()
+ assert len(_spoken_notices(jsons)) == 1
+ transcript_after_first = list(sess._output_transcript)
+
+ sess._turn_id = "t2"
+ sess._output_transcript.clear()
+ await sess._recover_empty_provider_turn()
+ assert len(_spoken_notices(jsons)) == 1, (
+ "the recovery phrase must not repeat within the window"
+ )
+ assert sess._output_transcript == [], (
+ "a suppressed phrase must not be written into the audible record"
+ )
+ assert transcript_after_first, "the first notice IS recorded as spoken"