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): stop the live model replaying an already-delivered delegate answer
Personal Jarvis Maintainer1b330abfb243
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex e24bfe19ed..2211da7cfd 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -443,7 +443,11 @@ def _delegate_result_prompt("your previous replies in this conversation. Do not imitate another ""person, do not change or dramatize your voice. Do not ""call any function, do not add a claim, and do not mention these "- "instructions.\n\n"+ "instructions. This rendering order applies ONLY to your immediate "+ "next reply: after that reply, or once the user has said anything "+ "new, the result counts as delivered — never speak, repeat, or "+ "paraphrase the tagged result again in any later turn unless the "+ "user explicitly asks you to repeat it.\n\n"f"Result status: {status}\n""<trusted_action_result>\n"f"{text}\n"@@ -507,6 +511,30 @@ def _normalized_bridge_text(text: str) -> str:return " ".join(str(text or "").strip().rstrip(".!?¡¿").casefold().split())+# Stale-readback repeat guard (live forensic 2026-07-21 11:32): a delegate+# reply whose provider rendering never became audible was spoken by the+# surface TTS, but the injected rendering order — carrying the full verbatim+# reply — stayed in the provider's conversation context. Three turns later a+# one-word user fragment ("ich") made the model execute that stale order and+# repeat the whole answer verbatim. The prompt-side expiry clause fights the+# cause; this guard is the deterministic net that stops the audio.+_STALE_READBACK_MIN_MATCH_CHARS = 32+_STALE_READBACK_MAX_REFS = 4+++def _normalize_for_repeat_match(text: str) -> str:+ """Reduce text to casefolded word characters for prefix comparison.++ Word-agnostic across languages: TTS text and the provider's re-render+ transcription may disagree on punctuation and casing, never on the words+ themselves when the model reads the tagged result back verbatim.+ """+ cleaned = "".join(+ ch if ch.isalnum() else " " for ch in str(text or "").casefold()+ )+ return " ".join(cleaned.split())++def _delegate_bridge_prompt(*, language: str, exact_text: str) -> str:"""Order one orchestrator-owned interim line over delegate dead air.@@ -546,7 +574,15 @@ _REALTIME_SAFETY_APPENDIX = ("Keep one single, consistent voice for the entire conversation: every ""reply uses the same voice, gender, tone, and pace as your previous ""replies. Never switch to a different voice, never imitate another "- "person or character, and never dramatize quoted or reported content."+ "person or character, and never dramatize quoted or reported content. "+ # 2026-07-21 11:32 live forensic: a tagged action result whose rendering+ # was superseded by the surface TTS stayed in context as an un-honored+ # order — three turns later a one-word user fragment made the model+ # execute it again and repeat the whole answer verbatim.+ "A tagged trusted_action_result is a one-time rendering order for the "+ "reply that immediately follows it; afterwards the system has already "+ "delivered it to the user. Never repeat or paraphrase an earlier tagged "+ "result in a later turn unless the user explicitly asks for a repeat.")_LANGUAGE_NAMES = {"de": "German", "en": "English", "es": "Spanish"}@@ -705,6 +741,26 @@ def _session_instructions("up, or verify, that is an explicit action request for your action ""function, not world knowledge.")+ # Fabricated-precision guard (live 2026-07-21 11:36: asked whether a+ # Gulfstream G800 can land in St. Moritz, the model invented a runway+ # length and delivered a flat "cannot land" — the real figures say a+ # landing is feasible under conditions). The time-agnostic sibling of+ # the freshness guard: niche numbers and the categorical verdicts built+ # on them are exactly what a realtime model confabulates most fluently,+ # and a confident wrong verdict is worse than a marked estimate.+ precision_line = (+ "Precision guard: for niche technical facts — exact measurements, "+ "dimensions, specifications, performance figures, capacities, "+ "limits — your memory is unreliable even where nothing changes "+ "over time. Never present a remembered niche figure as exact, and "+ "never rest a categorical verdict on one ('it cannot land there', "+ "'it will not fit', 'it is not compatible'): such feasibility "+ "questions rarely have a flat yes/no — give your best estimate "+ "clearly marked as such, name what the answer actually depends "+ "on, and offer to check the real figures. If the user then asks "+ "you to check or look it up, that is an explicit action request "+ "for your action function."+ )language_name = _LANGUAGE_NAMES.get(language, "the user's language")input_language_name = _LANGUAGE_NAMES.get(input_language)if input_language_name:@@ -739,6 +795,7 @@ def _session_instructions(input_directive,clock_line,freshness_line,+ precision_line,("Runtime identity: this voice session is using the Realtime engine"+ (f", provider {provider}" if provider else "")@@ -948,6 +1005,12 @@ class RealtimeVoiceSession:# closed (turn state popped), so this session-level guard withholds# provider output until the user audibly opens the next turn.self._drop_provider_output_until_user_turn = False+ # Normalized texts of delegate replies the surface TTS had to speak+ # because the provider rendered no audio for them. Their injected+ # rendering orders remain live in the provider context, so a later+ # plain turn re-rendering one of them is a stale ghost repeat, not a+ # fresh answer (live forensic 2026-07-21 11:32).+ self._stale_readback_refs: list[str] = []self._hangup_reason = ""self._turn_final_text = ""self._end_after_turn = False@@ -1952,6 +2015,44 @@ class RealtimeVoiceSession:self._gate.drain()continueself._output_transcript.append(display)+ if (+ delegate_state is None+ and self._external_update is None+ and self._stale_readback_refs+ ):+ # A plain turn re-rendering a reply the surface TTS+ # already delivered is the provider executing its+ # stale rendering order, not a fresh answer (live+ # forensic 2026-07-21 11:32: the whole School-District+ # answer repeated verbatim on the fragment "ich").+ # One-shot per armed reply: a genuine "repeat that"+ # that trips this once works on the next attempt.+ stale_ref = self._match_stale_readback(+ "".join(self._output_transcript)+ )+ if stale_ref is not None:+ self._stale_readback_refs.remove(stale_ref)+ from jarvis.voice.action_phrases import (+ action_phrase,+ )++ log.warning(+ "realtime[%s] provider re-rendered an "+ "already-delivered delegate reply on a later "+ "turn; suppressing the stale repeat",+ self.session_id,+ )+ await self._cancel_unsafe_output(+ reason=(+ "stale delegate readback re-rendered on "+ "a later turn"+ ),+ fallback_text=action_phrase(+ "stale_repeat_clarify", self._language+ ),+ )+ self._gate.drain()+ continue# Cumulative snapshot under ONE slot: what the provider# is audibly saying this turn, as an echo-guard reference# (BUG-089). Slot replacement keeps the growing snapshot@@ -2016,6 +2117,7 @@ class RealtimeVoiceSession:)if trusted_reply:delegate_state.surface_fallback_spoken = True+ self._arm_stale_readback_guard(trusted_reply)await self._cancel_unsafe_output(reason="output transcript exceeded safe audio buffer",fallback_text=trusted_reply or None,@@ -2256,6 +2358,7 @@ class RealtimeVoiceSession:# user opens the next turn.delegate_state.surface_fallback_spoken = Trueself._drop_provider_output_until_user_turn = True+ self._arm_stale_readback_guard(fallback_text)await self._send_json(self._surface_speech_message(fallback_text))@@ -2287,6 +2390,7 @@ class RealtimeVoiceSession:self._drop_provider_output_until_user_turn = (True)+ self._arm_stale_readback_guard(trusted_reply)await self._cancel_unsafe_output(reason="output transcript missing at turn completion",interrupt_provider=False,@@ -3638,6 +3742,32 @@ class RealtimeVoiceSession:state = self._delegate_turns.get(self._turn_id)return bool(state is not None and state.surface_fallback_spoken)+ def _arm_stale_readback_guard(self, reply: str) -> None:+ """Remember one surface-delivered delegate reply for repeat detection.++ Armed only on the surface-TTS fallback paths: those are exactly the+ turns whose injected rendering order the provider never honored, so+ the order — with the full reply text — is still live in its context.+ Short texts never arm (canned phrases are too generic to match on).+ """+ normalized = _normalize_for_repeat_match(reply)+ if len(normalized) < _STALE_READBACK_MIN_MATCH_CHARS:+ return+ if normalized in self._stale_readback_refs:+ return+ self._stale_readback_refs.append(normalized)+ del self._stale_readback_refs[:-_STALE_READBACK_MAX_REFS]++ def _match_stale_readback(self, accumulated: str) -> str | None:+ """Return the armed reply this turn's output is re-rendering, if any."""+ normalized = _normalize_for_repeat_match(accumulated)+ if len(normalized) < _STALE_READBACK_MIN_MATCH_CHARS:+ return None+ for ref in self._stale_readback_refs:+ if ref.startswith(normalized) or normalized.startswith(ref):+ return ref+ return None+def _must_withhold_provider_output(self) -> bool:"""Drop untrusted output during delegation and after barge-in."""return bool(@@ -4483,6 +4613,7 @@ class RealtimeVoiceSession:returnturn_state.surface_fallback_spoken = Trueself._drop_provider_output_until_user_turn = True+ self._arm_stale_readback_guard(reply)log.warning("realtime[%s] provider rendered no readback for a delivered ""delegate result within %.1fs; speaking it through the "diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.pyindex a1b9805989..a708311b44 100644--- a/jarvis/voice/action_phrases.py+++ b/jarvis/voice/action_phrases.py@@ -229,6 +229,17 @@ _PHRASES: dict[str, dict[str, str]] = {"en": "That didn't work just now.","es": "Eso no funcionó ahora mismo.",},+ # A stale re-render of an already-delivered answer was suppressed: the+ # live model executed the leftover rendering order of an earlier delegate+ # reply and started repeating the whole answer on a later turn (live+ # forensic 2026-07-21 11:32). The clarify line stays honest in both+ # worlds — the ghost repeat (common case) and a genuine repeat request+ # that tripped the one-shot guard (the user simply asks again).+ "stale_repeat_clarify": {+ "de": "Das hatte ich gerade schon beantwortet. Was genau möchtest du wissen?", # i18n-allow+ "en": "I already answered that just now. What exactly would you like to know?",+ "es": "Eso ya lo acabo de responder. ¿Qué querías saber exactamente?",+ },# Action failure WITH a human reason forwarded (the speakable cause pulled# from the tool's stderr/error — never a bare exit code)."action_failed_reason": {diff --git a/tests/unit/realtime/test_stale_readback_repeat.py b/tests/unit/realtime/test_stale_readback_repeat.pynew file mode 100644index 0000000000..d7dac8c961--- /dev/null+++ b/tests/unit/realtime/test_stale_readback_repeat.py@@ -0,0 +1,321 @@+"""Stale delegate-readback repeat guard (live forensic 2026-07-21 11:32).++A delegate reply whose provider rendering never became audible is spoken by+the surface TTS — but the injected rendering order, carrying the verbatim+reply text, stays live in the provider's conversation context. Three turns+later a one-word user fragment made Gemini execute that stale order and+repeat the whole earlier answer word for word. The session must recognize a+plain turn that re-renders an already-delivered delegate reply and suppress+it, while a sanctioned delegate readback of the same text stays audible.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest++import jarvis.realtime.session as session_mod+from jarvis.core.protocols import AudioChunk+from jarvis.realtime.protocol import RealtimeEvent+from jarvis.realtime.session import RealtimeVoiceSession+from jarvis.voice.action_phrases import action_phrase++DELIVERED_REPLY = (+ "School districts in the United States are organized locally and "+ "regionally and play a central role in the education system. They are "+ "largely independent and fund themselves mostly from local property "+ "taxes."+)++AUDIO = AudioChunk(pcm=b"\x01\x02" * 7_200, sample_rate=24_000, timestamp_ns=0)+++class FakeSession:+ session_id = "fake"+ supports_tool_updates = True+ creates_responses_automatically = False+ isolates_response_generations = False++ def __init__(self, events):+ self._events = events+ self.sent_audio = []+ self.text_inputs = []+ self.tool_results = []+ self.session_updates = []+ self.response_requests = 0+ self.interrupts = 0+ self.closed = False++ async def send_audio(self, chunk):+ self.sent_audio.append(chunk)++ async def receive(self):+ for event in self._events:+ yield event+ await asyncio.sleep(0)++ async def update_session(self, *, instructions=None, language=None, tools=None):+ self.session_updates.append(+ {"instructions": instructions, "language": language, "tools": tools}+ )++ async def request_response(self, *, required_tool=None):+ del required_tool+ self.response_requests += 1++ async def send_text(self, text):+ self.text_inputs.append(text)++ async def truncate(self, audio_end_ms):+ del audio_end_ms++ async def interrupt(self):+ self.interrupts += 1++ async def send_tool_result(self, call_id, name, result):+ self.tool_results.append((call_id, name, result))++ async def close(self):+ self.closed = True+++class FakeProvider:+ name = "fake"+ supports_realtime = True+ input_sample_rate = 16_000+ output_sample_rate = 24_000++ def __init__(self, events):+ self._events = events+ self.opened_with = None+ self.session = None++ async def can_open_duplex_session(self):+ return True++ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = FakeSession(self._events)+ return self.session+++class ReadbackGatedSession(FakeSession):+ """Yield the user turn, then hold the readback until the result arrives."""++ def __init__(self, events):+ super().__init__(events)+ self._text_sent = asyncio.Event()++ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text="What is in my Gmail inbox?",+ is_final=True,+ )+ await self._text_sent.wait()+ for event in self._events:+ yield event+ await asyncio.sleep(0)++ async def send_text(self, text):+ await super().send_text(text)+ self._text_sent.set()+++class ReadbackGatedProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = ReadbackGatedSession(self._events)+ return self.session+++class FakeBrain:+ def __init__(self, replies=("done",)):+ self.calls = []+ self._replies = list(replies)++ async def generate(self, text, **kwargs):+ self.calls.append((text, kwargs))+ return self._replies.pop(0) if self._replies else "done"++ async def __call__(self, text):+ return await self.generate(text)+++def _cfg():+ return SimpleNamespace(+ brain=SimpleNamespace(reply_language="en", providers={}),+ stt=SimpleNamespace(language="auto"),+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),+ latency=SimpleNamespace(enabled=False),+ )+++def _session(provider, *, brain=None, jsons=None, binaries=None):+ return RealtimeVoiceSession(+ session_id="stale-readback-test",+ send_binary=(+ (lambda data: binaries.append(data) or asyncio.sleep(0))+ if binaries is not None+ else (lambda _data: asyncio.sleep(0))+ ),+ send_json=(+ (lambda m: jsons.append(m) or asyncio.sleep(0))+ if jsons is not None+ else (lambda _m: asyncio.sleep(0))+ ),+ provider=provider,+ config=_cfg(),+ brain=brain,+ )+++# ---------------------------------------------------------------------------+# Matching primitives+# ---------------------------------------------------------------------------+++def test_repeat_match_is_word_agnostic_about_punctuation_and_case():+ sess = _session(FakeProvider([]))+ sess._arm_stale_readback_guard(DELIVERED_REPLY)+ # The provider's re-render transcription drops commas and changes casing;+ # the words are what identify the stale repeat.+ rerender = DELIVERED_REPLY[:80].upper().replace(",", " ")+ assert sess._match_stale_readback(rerender) is not None+++def test_short_or_fresh_text_never_arms_or_matches():+ sess = _session(FakeProvider([]))+ sess._arm_stale_readback_guard("Done.")+ assert sess._stale_readback_refs == []+ sess._arm_stale_readback_guard(DELIVERED_REPLY)+ assert (+ sess._match_stale_readback(+ "Here is a completely fresh answer about tomorrow's weather in Berlin."+ )+ is None+ )+ # Too little accumulated text is never conclusive, even when it matches.+ assert sess._match_stale_readback(DELIVERED_REPLY[:20]) is None+++def test_full_one_delta_rerender_with_trailing_extra_still_matches():+ sess = _session(FakeProvider([]))+ sess._arm_stale_readback_guard(DELIVERED_REPLY)+ assert sess._match_stale_readback(DELIVERED_REPLY + " Would you like more?") is not None+++# ---------------------------------------------------------------------------+# Pump behavior+# ---------------------------------------------------------------------------+++async def test_plain_turn_rerendering_a_delivered_reply_is_cancelled():+ """The live failure: three turns after the surface TTS delivered the+ delegate reply, a plain turn started re-rendering it verbatim. The guard+ must cancel the repeat, speak the clarify line, and disarm (one-shot)."""+ provider = FakeProvider(+ [+ RealtimeEvent(type="input_transcript", text="hello", is_final=True),+ RealtimeEvent(type="output_transcript_delta", text=DELIVERED_REPLY[:80]),+ RealtimeEvent(type="output_transcript_delta", text=DELIVERED_REPLY[80:]),+ RealtimeEvent(type="audio_delta", audio=AUDIO),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ jsons: list[dict] = []+ binaries: list[bytes] = []+ sess = _session(provider, brain=FakeBrain(), jsons=jsons, binaries=binaries)+ sess._arm_stale_readback_guard(DELIVERED_REPLY)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=5)+ await sess.end(reason="test")++ assert any(m.get("type") == "tts_cancel" for m in jsons)+ spoken = [m for m in jsons if m.get("type") == "error_spoken"]+ assert [m["text"] for m in spoken] == [action_phrase("stale_repeat_clarify", "en")]+ # The stale rendering's audio never reaches the surface.+ assert binaries == []+ # One-shot: a genuine repeat request right after works on its next try.+ assert sess._stale_readback_refs == []+++async def test_plain_turn_with_fresh_text_plays_normally():+ fresh = (+ "Tomorrow looks calm and sunny with a light breeze from the west "+ "and no rain expected until the evening hours."+ )+ provider = FakeProvider(+ [+ RealtimeEvent(type="input_transcript", text="hello", is_final=True),+ RealtimeEvent(type="output_transcript_delta", text=fresh),+ RealtimeEvent(type="audio_delta", audio=AUDIO),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ jsons: list[dict] = []+ binaries: list[bytes] = []+ sess = _session(provider, brain=FakeBrain(), jsons=jsons, binaries=binaries)+ sess._arm_stale_readback_guard(DELIVERED_REPLY)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=5)+ await sess.end(reason="test")++ assert not any(m.get("type") == "tts_cancel" for m in jsons)+ assert binaries, "fresh provider audio must keep flowing"+ # The guard stays armed for the reply that was never re-rendered.+ assert sess._stale_readback_refs != []+++async def test_sanctioned_delegate_readback_of_same_text_stays_audible():+ """A delegate turn rendering ITS OWN trusted reply is the sanctioned+ readback — even when an earlier fallback delivery armed the guard with+ identical text (the user asked the same question again)."""+ provider = ReadbackGatedProvider(+ [+ RealtimeEvent(type="output_transcript_delta", text=DELIVERED_REPLY),+ RealtimeEvent(type="audio_delta", audio=AUDIO),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ jsons: list[dict] = []+ binaries: list[bytes] = []+ sess = _session(+ provider,+ brain=FakeBrain(replies=(DELIVERED_REPLY,)),+ jsons=jsons,+ binaries=binaries,+ )+ sess._arm_stale_readback_guard(DELIVERED_REPLY)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=10)+ await sess.end(reason="test")++ assert provider.session.text_inputs, "trusted result was never injected"+ assert not any(m.get("type") == "tts_cancel" for m in jsons)+ assert binaries, "the sanctioned readback's audio must stay audible"+++# ---------------------------------------------------------------------------+# Prompt-side expiry+# ---------------------------------------------------------------------------+++def test_result_prompt_orders_a_single_expiring_rendering():+ prompt = session_mod._delegate_result_prompt("The answer.", language="en", success=True)+ assert "immediate next reply" in prompt+ assert "never speak, repeat, or paraphrase" in prompt+++def test_session_instructions_forbid_replaying_earlier_action_results():+ text = session_mod._session_instructions("en")+ assert "one-time rendering order" in text+ assert "unless the user explicitly asks for a repeat" in text