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): one delegate reply, one voice - dedupe the two surface fallbacks and mute a post-turn late provider rendering (BUG-068 #5)
Ruben Lütkeb77f519a9114
diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.pyindex f95599b542..0f9171b88a 100644--- a/jarvis/brain/turn_planner.py+++ b/jarvis/brain/turn_planner.py@@ -82,11 +82,18 @@ _OWNERSHIP_RE = re.compile(r"mein\w*|unser\w*|mir|wir|ueber mich|uber mich|erinner\w* mich|" # i18n-allow: speech inputr"mi|mis|mio|nuestr\w*|sobre mi|recuerd\w* de mi)\b" # i18n-allow: speech input)+# Colloquial temporal particles (German "gerade", "eben", "vorhin",+# "soeben") are deliberately NOT in this vocabulary: in spoken language they+# are discourse fillers, not freshness claims, and treating them as+# current-data markers force-delegated plain world-knowledge questions+# ("Wo wohnt der gerade?") through the router brain and its web searches+# (live incident 2026-07-16 11:24, 16 s of silence ending in an error).+# Genuinely current topics keep their strong markers below (weather, news,+# today, now, status, ...). # i18n-allow: names the retired German filler tokens_CURRENT_RE = re.compile(r"\b(?:current|currently|latest|today|tonight|tomorrow|now|recent|"r"news|weather|status|available|online|"r"aktuell\w*|neueste\w*|heute|morgen|jetzt|kuerzlich|nachrichten|"- r"gerade|eben|vorhin|soeben|" # i18n-allow: speech inputr"wetter|status|verfuegbar|online|" # i18n-allow: speech inputr"actual\w*|ultimo\w*|hoy|manana|ahora|reciente\w*|noticias|"r"clima|tiempo|estado|disponible)\b" # i18n-allow: multilingual speech-input matching data@@ -95,6 +102,11 @@ _LOCAL_STATE_RE = re.compile(r"\b(?:wiki|mcp\w*|cli\w*|tool\w*|plugin\w*|connector\w*|"r"integration\w*|setting\w*|configuration\w*|api[\s-]?key\w*|"r"jarvis|installed\w*|connected\w*|capabilit\w*|activity history|"+ # Asking the assistant what it is working on queries its own mission /+ # activity state; the idiom anchors it here instead of leaning on the+ # temporal filler ("gerade") that used to co-trigger it. # i18n-allow+ r"what are you working on|woran arbeitest du|" # i18n-allow: speech input+ r"en que estas trabajando|" # i18n-allow: speech inputr"werkzeug\w*|einstellung\w*|konfiguration\w*|" # i18n-allow: speech inputr"installiert\w*|verbunden\w*|faehigkeit\w*|" # i18n-allow: speech inputr"aktivitaetsverlauf|" # i18n-allow: speech inputdiff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 3b06a3e85b..cc26b2e221 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -126,11 +126,13 @@ _DELEGATE_DECLARATION: dict[str, Any] = {"Execute an action for the user through the Jarvis action system: ""open apps or views, change settings, control the computer on screen ""(click, type, and navigate inside any application window until the "- "task is finished), manage files, start background research or coding "- "missions, read or write the user's private Wiki memory, and inspect "- "the current MCP, CLI, tool, integration, configuration, or system "- "state. Also call this to relay the user's answer to a pending "- "confirmation question."+ "task is finished), manage files, start a background research or "+ "coding mission the user explicitly asked to run, read or write the "+ "user's private Wiki memory, and inspect the current MCP, CLI, tool, "+ "integration, configuration, or system state. Also call this to "+ "relay the user's answer to a pending confirmation question. Never "+ "call it just to look up general world knowledge, public facts or "+ "figures, definitions, or smalltalk — answer those directly yourself."),"parameters": {"type": "object",@@ -155,9 +157,14 @@ _DELEGATE_ROLE_DIRECTIVE = ("apps, their settings, their system state, or any action on their computer ""— including a vague, elliptical, or garbled follow-up that refers back to ""such a turn ('and what else is in there?', 'what does it say?'). You "- "cannot see any of it yourself, so guessing is always wrong. Answer from "- "your own knowledge only for general world knowledge and ordinary social "- "chat. "+ "cannot see any of it yourself, so guessing is always wrong. "+ "General world knowledge is YOURS: public facts and figures, well-known "+ "people and companies, definitions, explanations, recommendations, "+ "opinions, and ordinary social chat. Answer those immediately from your "+ "own knowledge, without any function call, even when you are only mostly "+ "sure — qualify the answer briefly instead of delegating. A jarvis_action "+ "round trip costs the user many seconds of silence, so calling it for a "+ "question you can answer yourself is a latency failure, not caution. ""The action system physically operates the user's computer on screen: it ""opens apps and clicks, types, and navigates inside any application ""window until a multi-step task is finished end to end. Never tell the "@@ -185,6 +192,22 @@ _DELEGATE_REQUIRED_DIRECTIVE = ("Do not answer, do not call a function, and do not promise an outcome. Wait ""for the trusted action result that the orchestrator will inject.")+# The local planner judged the current turn plain world knowledge or social+# chat. The planner's verdict used to steer the model only in one direction+# (forcing delegation); a NATIVE verdict changed nothing, so a+# delegation-biased model still round-tripped trivia through the router+# brain and its web searches (live incident 2026-07-16 11:23: "How much+# money does Peter Thiel have?" cost 16 s of silence). The tool stays+# declared — the planner is conservative and can miss oddly-phrased real+# actions — but the model is told the fast path is the correct one.+_DELEGATE_DISCOURAGED_DIRECTIVE = (+ "This current turn looks like general world knowledge or ordinary "+ "conversation. Answer it directly from your own knowledge now, without "+ "calling any function. Call jarvis_action on this turn ONLY if the "+ "request actually needs the user's own world (their Wiki or personal "+ "memory, their files, apps, settings, or system state) or performs a "+ "real action on their computer."+)# A slow action (a Wiki write curates pages through an LLM) outlives the turn# that asked for it as soon as the user speaks into the waiting silence. The# model must then neither invent an outcome nor deny one: the orchestrator is@@ -604,6 +627,11 @@ class RealtimeVoiceSession:self._response_requested_for_turn = Falseself._response_requested_input_ids: set[str] = set()self._drop_provider_output_until_new_response = False+ # Set when a surface fallback already spoke a delegate reply: a very+ # late provider rendering of that same reply may arrive AFTER its turn+ # 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 = Falseself._hangup_reason = ""self._turn_final_text = ""self._end_after_turn = False@@ -963,6 +991,9 @@ class RealtimeVoiceSession:self._language = resolved_languageself._gate = ScrubHoldGate(resolved_language)self._response_requested_for_turn = True+ # This deliberate injection expects a rendered response; it must not+ # inherit a fallback-era suppression from an earlier delegate turn.+ self._drop_provider_output_until_user_turn = Falseawait self._ensure_turn_started()try:await send_text(@@ -1019,6 +1050,9 @@ class RealtimeVoiceSession:if input_observed:self._input_turn_observed = Trueself._user_speech_active = False+ # The user audibly opened this turn — a fallback-era+ # suppression of stale provider output ends here.+ self._drop_provider_output_until_user_turn = Falseawait self._ensure_turn_started()new_language = self._languageif transcript:@@ -1081,6 +1115,9 @@ class RealtimeVoiceSession:action_pending=(self._has_pending_delegate_from_earlier_turn()),+ delegate_discouraged=(+ not turn_plan.requires_orchestrator+ ),),),"language": new_language,@@ -1265,8 +1302,28 @@ class RealtimeVoiceSession:if self._gate.fail_if_pending_exceeds(_MAX_UNSCRUBBED_AUDIO_MS):+ # A tripped hold during a trusted delegate readback is+ # a rendering failure, not a leak: the provider only+ # re-speaks OUR already-delivered brain reply, and its+ # output transcription simply fell >5 s behind the+ # audio (live incident 2026-07-16 11:24: the user+ # waited 16 s of web searches and then heard a generic+ # error). Speak the trusted reply through the surface+ # TTS instead of discarding it; the flag withholds any+ # late provider rendering so nothing plays twice.+ trusted_reply = ""+ if (+ delegate_state is not None+ and delegate_state.delivery_started+ ):+ trusted_reply = str(+ delegate_state.last_reply or ""+ ).strip()+ if trusted_reply:+ delegate_state.surface_fallback_spoken = Trueawait self._cancel_unsafe_output(- reason="output transcript exceeded safe audio buffer"+ reason="output transcript exceeded safe audio buffer",+ fallback_text=trusted_reply or None,)elif event.type in {"speech_started", "interrupted"} and (self._pending_delegate_needs_endpoint_protection()@@ -1454,6 +1511,14 @@ class RealtimeVoiceSession:"grounded Brain result; using surface TTS fallback",self.session_id,)+ # One reply, one voice (live forensic 2026-07-16+ # 11:43: THREE renderings of the same answer). The+ # readback watchdog must not speak it a second time,+ # and a very late provider rendering — arriving after+ # this turn closes — must stay inaudible until the+ # user opens the next turn.+ delegate_state.surface_fallback_spoken = True+ self._drop_provider_output_until_user_turn = Trueawait self._send_json({"type": "error_spoken",@@ -2176,12 +2241,18 @@ class RealtimeVoiceSession:*,delegate_required: bool = False,action_pending: bool = False,+ delegate_discouraged: bool = False,) -> str:if self._delegate_enabled:if delegate_required:return f"{_DELEGATE_ROLE_DIRECTIVE}\n\n{_DELEGATE_REQUIRED_DIRECTIVE}"if action_pending:return f"{_DELEGATE_ROLE_DIRECTIVE}\n\n{_DELEGATE_PENDING_DIRECTIVE}"+ if delegate_discouraged:+ return (+ f"{_DELEGATE_ROLE_DIRECTIVE}\n\n"+ f"{_DELEGATE_DISCOURAGED_DIRECTIVE}"+ )return _DELEGATE_ROLE_DIRECTIVEif self._tool_bridge is not None:return _TOOL_ROLE_DIRECTIVE@@ -2248,6 +2319,7 @@ class RealtimeVoiceSession:"""Drop untrusted output during delegation and after barge-in."""return bool(self._drop_provider_output_until_new_response+ or self._drop_provider_output_until_user_turnor self._must_withhold_delegate_output()or self._delegate_surface_fallback_spoken())@@ -2438,6 +2510,7 @@ class RealtimeVoiceSession:# being dropped. This trusted follow-up is the new response it waits for.drop_before_delivery = self._drop_provider_output_until_new_responseself._drop_provider_output_until_new_response = False+ self._drop_provider_output_until_user_turn = Falseawait self._ensure_turn_started()try:await send_text(@@ -2970,6 +3043,7 @@ class RealtimeVoiceSession:self._endedor self._session is Noneor self._user_speech_active+ or turn_state.surface_fallback_spokenor not self._delegate_turn_is_active(turn_id, turn_state)):return@@ -2979,9 +3053,15 @@ class RealtimeVoiceSession:breakawait asyncio.sleep(_DELEGATE_READBACK_POLL_S)reply = str(turn_state.last_reply or "").strip()- if not reply:+ # One reply, one voice: the turn-complete no-audio fallback may have+ # spoken it already through the same surface TTS, which never touches+ # the realtime sample counters this loop watches (live forensic+ # 2026-07-16 11:43: both nets fired and the answer was heard twice —+ # then a third time when the provider rendered it late).+ if not reply or turn_state.surface_fallback_spoken:returnturn_state.surface_fallback_spoken = True+ self._drop_provider_output_until_user_turn = Truelog.warning("realtime[%s] provider rendered no readback for a delivered ""delegate result within %.1fs; speaking it through the surface "diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.pyindex bcb0150ac6..fbee455803 100644--- a/tests/unit/brain/test_turn_planner.py+++ b/tests/unit/brain/test_turn_planner.py@@ -81,6 +81,36 @@ def test_private_current_connected_and_action_turns_use_orchestrator(assert plan.path is TurnPath.ORCHESTRATOR+ "utterance",+ [+ # Live incident 2026-07-16 11:24: the temporal filler "gerade" was a+ # current-data marker, so a plain world-knowledge follow-up was+ # force-delegated through the router brain (16 s of web searches+ # ending in a spoken error). Fillers alone must never delegate.+ "Wo wohnt der gerade?", # i18n-allow: German speech-input fixture+ "Wie viel Geld hat Peter Thiel?", # i18n-allow: German fixture+ "Was hat der eben gesagt?", # i18n-allow: German speech-input fixture+ ],+)+def test_temporal_filler_world_knowledge_stays_native(utterance: str) -> None:+ assert plan_turn(utterance).path is TurnPath.NATIVE_REALTIME+++ "utterance",+ [+ # Strong freshness markers must keep forcing the orchestrator even+ # after the colloquial fillers were retired.+ "Wie ist das Wetter gerade?", # i18n-allow: German speech-input fixture+ "Was gibt es heute für Nachrichten?", # i18n-allow: German fixture+ "What is the latest Python release?",+ ],+)+def test_strong_current_markers_still_use_orchestrator(utterance: str) -> None:+ assert plan_turn(utterance).path is TurnPath.ORCHESTRATOR++def test_read_only_dynamic_connector_matches_live_capability(registry: CapabilityRegistry,) -> None:diff --git a/tests/unit/realtime/test_delegate_endpointing.py b/tests/unit/realtime/test_delegate_endpointing.pyindex 698ada4352..62e6f8c29b 100644--- a/tests/unit/realtime/test_delegate_endpointing.py+++ b/tests/unit/realtime/test_delegate_endpointing.py@@ -9,6 +9,7 @@ from typing import Anyimport pytestfrom jarvis.brain.turn_planner import TurnPath, TurnPlan, TurnReason+from jarvis.core.protocols import AudioChunkfrom jarvis.realtime.protocol import RealtimeEventfrom jarvis.realtime.session import RealtimeVoiceSession@@ -220,6 +221,30 @@ class _AutoResponseWire:if self._script == "interrupted-after-delivery":# The trusted readback was injected but no PCM is audible yet.yield RealtimeEvent(type="interrupted")+ if self._script == "turn-complete-no-render":+ # A boundary (e.g. the bridge response ending) arrives after+ # delivery, but the provider never renders the readback at all.+ yield RealtimeEvent(type="turn_complete")+ await self.closed.wait()+ return+ if self._script == "late-render-after-fallback":+ yield RealtimeEvent(type="turn_complete")+ # The provider renders the same reply seconds after the surface+ # fallback already spoke it (live forensic 2026-07-16 11:43:+ # heard a third time). It must stay inaudible.+ yield RealtimeEvent(+ type="output_transcript_delta",+ text="Tomorrow is Friday.",+ )+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=b"\x11\x00" * 480, sample_rate=24_000, timestamp_ns=0+ ),+ )+ yield RealtimeEvent(type="turn_complete")+ await self.closed.wait()+ returnyield RealtimeEvent(type="output_transcript_delta",text="Tomorrow is Friday.",@@ -377,6 +402,103 @@ async def test_undelivered_readback_falls_back_to_surface_tts(]+async def test_no_render_fallback_speaks_exactly_once(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The no-audio fallback and the readback watchdog must never both speak.++ Live forensic 2026-07-16 11:43: the turn-complete fallback spoke the+ reply through the classic TTS (which blocks the pump for the whole+ playback), the watchdog saw zero realtime samples and spoke it AGAIN.+ The blocking playback is emulated by an error_spoken handler that sleeps+ past the watchdog deadline.+ """+ _shorten_delegate_waits(monkeypatch)+ brain = _InstantBrain()+ provider = _AutoResponseProvider(brain, script="turn-complete-no-render")+ messages: list[dict[str, Any]] = []++ async def _send_json(message: dict[str, Any]) -> None:+ messages.append(message)+ if message.get("type") == "error_spoken":+ # Emulate the desktop surface: the fallback playback holds the+ # handler (and with it the pump) well past the watchdog window.+ await asyncio.sleep(0.3)++ session = RealtimeVoiceSession(+ session_id="delegate-single-voice",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=_send_json,+ provider=provider,+ config=_config(),+ bus=None,+ browser_sample_rate=16_000,+ surface="desktop",+ brain=brain,+ )+ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})+ try:+ await asyncio.wait_for(provider.session.text_sent.wait(), timeout=2.0)+ await asyncio.sleep(0.6) # past playback emulation + watchdog window+ finally:+ await session.end(reason="test")++ fallbacks = [m for m in messages if m.get("type") == "error_spoken"]+ assert len(fallbacks) == 1+ assert fallbacks[0]["text"] == "Tomorrow is Friday."+++async def test_late_provider_rendering_after_fallback_stays_silent(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A provider rendering arriving after the surface fallback is withheld.++ Live forensic 2026-07-16 11:43: Gemini rendered the reply ~13 s late,+ AFTER the turn had closed — the per-turn withhold flag was gone with the+ popped turn state and the answer was heard a third time. The+ session-level guard must keep it inaudible until the user opens the+ next turn.+ """+ _shorten_delegate_waits(monkeypatch)+ brain = _InstantBrain()+ provider = _AutoResponseProvider(brain, script="late-render-after-fallback")+ messages: list[dict[str, Any]] = []+ binary_chunks: list[bytes] = []++ async def _send_binary(data: bytes) -> None:+ binary_chunks.append(bytes(data))++ session = RealtimeVoiceSession(+ session_id="delegate-late-render",+ send_binary=_send_binary,+ send_json=lambda message: messages.append(message) or asyncio.sleep(0),+ provider=provider,+ config=_config(),+ bus=None,+ browser_sample_rate=16_000,+ surface="desktop",+ brain=brain,+ )+ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})+ try:+ await asyncio.wait_for(provider.session.text_sent.wait(), timeout=2.0)+ await asyncio.sleep(0.4) # let the late rendering arrive and be judged+ finally:+ await session.end(reason="test")++ fallbacks = [m for m in messages if m.get("type") == "error_spoken"]+ assert len(fallbacks) == 1+ assistant_transcripts = [+ m+ for m in messages+ if m.get("type") == "transcript" and m.get("role") == "assistant"+ ]+ assert assistant_transcripts == []+ assert binary_chunks == []++@pytest.mark.asyncioasync def test_phantom_interrupted_edge_defers_while_delegate_pending(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 99120af153..acc6965cb2 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -1945,6 +1945,130 @@ async def test_general_knowledge_turn_keeps_native_realtime_answering(utterance)await sess.end(reason="test")+async def test_native_turn_update_discourages_delegation():+ """A planner-NATIVE turn steers the model AWAY from the action function.++ The planner verdict used to work in one direction only (forcing+ delegation); a NATIVE verdict changed nothing, so a delegation-biased+ provider still round-tripped plain world knowledge through the router+ brain (live incident 2026-07-16 11:23, 16 s of web searches for a+ net-worth question). The tool stays declared; the directive flips.+ """+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="How much money does Peter Thiel have?",+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(provider, brain=FakeBrain())++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ update = provider.session.session_updates[-1]["instructions"]+ assert "Answer it directly from your own knowledge" in update+ assert "orchestrator is handling this current turn" not in update+ await sess.end(reason="test")+++async def test_forced_turn_update_never_carries_discourage_directive():+ """The orchestrator-owned branch wins over the discourage branch."""+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="What is in my Gmail inbox?",+ is_final=True,+ ),+ ]+ )+ sess = _session(provider, brain=FakeBrain())++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ update = provider.session.session_updates[-1]["instructions"]+ assert "orchestrator is handling this current turn" in update+ assert "Answer it directly from your own knowledge" not in update+ await sess.end(reason="test")+++async def test_scrub_trip_during_delegate_readback_speaks_trusted_reply():+ """A tripped transcript hold re-speaks the delivered reply, not an error.++ Gemini renders an injected trusted result faster than real time while its+ output transcription lags; once >5 s of PCM sat unclaimed the scrub gate+ cancelled the readback and the user heard a generic error AFTER waiting+ through the whole delegated action (live incident 2026-07-16 11:24). The+ reply text is our own already-delivered brain output, so the surface TTS+ must speak it instead.+ """+ reply = "The delegated answer the user must still hear."+ # 3 s of 24 kHz 16-bit PCM per chunk; the second chunk pushes the+ # unclaimed buffer past the 5 s scrub cap without any transcript delta.+ three_seconds = AudioChunk(+ pcm=b"\x01\x02" * 72_000, sample_rate=24_000, timestamp_ns=0+ )++ class _GatedReadbackSession(FakeSession):+ 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()+ async for event in super().receive():+ yield event++ async def send_text(self, text):+ await super().send_text(text)+ self._text_sent.set()++ class _GatedReadbackProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _GatedReadbackSession(self._events)+ return self.session++ jsons: list[dict] = []+ binaries: list[bytes] = []+ provider = _GatedReadbackProvider(+ [+ RealtimeEvent(type="audio_delta", audio=three_seconds),+ RealtimeEvent(type="audio_delta", audio=three_seconds),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(+ provider,+ brain=FakeBrain(replies=(reply,)),+ jsons=jsons,+ binaries=binaries,+ )++ 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 provider.session.text_inputs, "trusted result was never injected"+ spoken = [item for item in jsons if item.get("type") == "error_spoken"]+ assert [item["text"] for item in spoken] == [reply]+ assert not any("error occurred" in item["text"].lower() for item in spoken)+ assert binaries == []++class _ConfirmAwaitingBrain(FakeBrain):"""FakeBrain that reports a pending two-turn voice confirmation."""