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): silent provider can no longer veto a delegated turn; phantom interrupted edges defer during silent delegate spans (BUG-068)
Ruben Lütke5c1825b18d37
diff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.pyindex 9db8159120..6b8472be27 100644--- a/jarvis/realtime/scrub_gate.py+++ b/jarvis/realtime/scrub_gate.py@@ -10,6 +10,8 @@ Regex-only, no LLM (AP-11).from __future__ import annotations+import time+from jarvis.brain.output_filter import FALLBACK_PHRASES, ScrubResult, scrub_for_voicefrom jarvis.core.protocols import AudioChunk@@ -59,6 +61,24 @@ class ScrubHoldGate:self._transcript_seen = Falseself._transcript_tail = ""self._hard_leak_actions: tuple[str, ...] = ()+ # Hold-time telemetry: how long the batch released last waited for its+ # clearing transcript. Lets the session attribute an audible mid-reply+ # hole to a late transcript delta instead of a silent provider+ # (live forensic 2026-07-16 10:26).+ self._pending_since: float | None = None+ self.last_hold_ms = 0.0++ @property+ def pending_audio_ms(self) -> float:+ """Milliseconds of audio currently held while awaiting a transcript."""+ return self._pending_audio_ms++ def _consume_hold_clock(self) -> None:+ if self._pending_since is not None:+ self.last_hold_ms = (time.monotonic() - self._pending_since) * 1_000.0+ self._pending_since = None+ else:+ self.last_hold_ms = 0.0def hard_leak_pending(self) -> bool:return self._hard_leak@@ -102,6 +122,7 @@ class ScrubHoldGate:self._cleared = Falseself._pending.clear()self._pending_audio_ms = 0.0+ self._pending_since = Nonereturn self.fallback_phrase()if _is_stream_safe_residue(aggregate):# A realtime provider may emit punctuation or the first half of a@@ -136,7 +157,10 @@ class ScrubHoldGate:self._pending = []self._pending_audio_ms = 0.0self._cleared = False+ self._consume_hold_clock()return out+ if not self._pending and self._pending_since is None:+ self._pending_since = time.monotonic()self._pending.append(chunk)sample_rate = max(1, int(chunk.sample_rate or 0))self._pending_audio_ms += (len(chunk.pcm) / 2) * 1_000 / sample_rate@@ -155,6 +179,7 @@ class ScrubHoldGate:self._pending = []self._pending_audio_ms = 0.0self._cleared = False+ self._consume_hold_clock()return outdef fail_closed(self) -> bool:@@ -163,6 +188,7 @@ class ScrubHoldGate:return Falseself._pending.clear()self._pending_audio_ms = 0.0+ self._pending_since = Noneself._cleared = Falseself._hard_leak = Trueself._hard_leak_actions = ("no_transcript",)@@ -178,6 +204,7 @@ class ScrubHoldGate:return Falseself._pending.clear()self._pending_audio_ms = 0.0+ self._pending_since = Noneself._cleared = Falseself._hard_leak = Trueself._hard_leak_actions = ("transcript_stalled",)@@ -191,6 +218,7 @@ class ScrubHoldGate:self._pending = []self._pending_audio_ms = 0.0self._cleared = False+ self._consume_hold_clock()return outdef drain(self) -> None:@@ -202,6 +230,8 @@ class ScrubHoldGate:self._transcript_seen = Falseself._transcript_tail = ""self._hard_leak_actions = ()+ self._pending_since = None+ self.last_hold_ms = 0.0def _restore_edge_whitespace(original: str, cleaned: str) -> str:diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 2a3edc6d14..f10c0a9735 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -8,9 +8,11 @@ status callbacks.from __future__ import annotations+import arrayimport asyncioimport inspectimport logging+import timefrom dataclasses import dataclass, fieldfrom typing import Anyfrom uuid import uuid4@@ -70,7 +72,32 @@ _END_CALL_DECLARATION: dict[str, Any] = {# turn that exceeds this is stuck, not busy._DELEGATE_TIMEOUT_S = 90.0_DELEGATE_INPUT_BOUNDARY_WAIT_S = 3.0+# A provider that stays completely silent must never veto a delegated turn.+# Each wait round re-arms only while the input transcript is still growing+# (the user is audibly mid-utterance); a stable transcript dispatches.+_DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS = 6_DELEGATE_NATIVE_BOUNDARY_WAIT_S = 1.0+# Mid-reply audio-flow diagnostics: an audible hole inside one spoken answer+# has three distinct producers (scrub gate waiting for a late transcript, the+# provider sending no audio, or silence embedded in the provider's own PCM).+# Logging separates them, because each needs a different fix (live forensic+# 2026-07-16 10:26: a ~1 s hole mid-sentence was unattributable from the log).+_AUDIO_FLOW_STALL_LOG_MS = 400.0+_EMBEDDED_SILENCE_LOG_MS = 400.0+# int16 peak below this is treated as silence inside provider PCM (~0.6 % of+# full scale — comfortably above the AP-27 silence-ghost RMS empirics, far+# below any audible speech).+_EMBEDDED_SILENCE_PEAK = 200+++def _pcm16_peak(pcm: bytes) -> int:+ """Peak absolute amplitude of little-endian int16 PCM (C-speed, no numpy)."""+ usable = len(pcm) - (len(pcm) % 2)+ if usable < 2:+ return 0+ samples = array.array("h")+ samples.frombytes(pcm[:usable])+ return max(max(samples), -min(samples))# A realtime bridge is useful only for a genuinely long delegated turn. Starting# a second provider response after two seconds made ordinary 5-7 second searches# slower: the trusted result had to wait for the interim response lifecycle to@@ -565,6 +592,10 @@ class RealtimeVoiceSession:self._end_after_turn = Falseself._end_call_timer: asyncio.Task[None] | None = Noneself._scrub_cancelled_for_turn = False+ # Mid-reply audio-flow diagnostics (attribution of audible holes).+ self._last_audio_emit_monotonic = 0.0+ self._last_audio_emit_turn = ""+ self._embedded_silence_ms = 0.0def _resolve_lang(self, *, text: str) -> str:brain = getattr(self._config, "brain", None)@@ -1220,15 +1251,27 @@ class RealtimeVoiceSession:await self._cancel_unsafe_output(reason="output transcript exceeded safe audio buffer")- elif (- event.type == "speech_started"- and self._pending_delegate_needs_endpoint_protection()+ elif event.type in {"speech_started", "interrupted"} and (+ self._pending_delegate_needs_endpoint_protection()+ or self._delegate_readback_awaits_first_audio()):+ # Gemini has no separate speech-start edge: its server VAD+ # reports noise blips and real barge-ins alike as+ # ``interrupted``. During the silent span of a delegated+ # action — thinking, or the trusted readback injected but+ # not yet audible — there is no output to cut, so an+ # unconfirmed edge must not abandon the turn: doing so+ # closed the turn with the trusted reply recorded but+ # never spoken, and the barge-in drop flag then swallowed+ # the injected readback (live forensic 2026-07-16 10:26).+ # Defer it; a real utterance confirms itself through its+ # final input transcript moments later.if not self._deferred_provider_speech_start:log.info("realtime[%s] deferred an unconfirmed provider "- "speech start while an action result was pending",+ "%s edge while an action result was pending",self.session_id,+ event.type,)self._deferred_provider_speech_start = Trueelif event.type in {"speech_started", "interrupted"}:@@ -2093,6 +2136,7 @@ class RealtimeVoiceSession:self._delegate_required_for_turn = Falseself._deferred_provider_speech_start = Falseself._scrub_cancelled_for_turn = False+ self._embedded_silence_ms = 0.0def _declared_tools(self) -> tuple[dict[str, Any], ...]:if self._delegate_enabled:@@ -2210,6 +2254,27 @@ class RealtimeVoiceSession:and self._turn_has_pending_delegate(self._turn_id))+ def _delegate_readback_awaits_first_audio(self) -> bool:+ """Protect a delivered-but-not-yet-audible trusted delegate result.++ Between the injection of a delegate result (``send_text`` /+ ``send_tool_result``) and the first audible PCM of the provider's+ readback the session is completely silent, so a provider VAD edge in+ this window is indistinguishable from room noise. Closing the turn+ here records a reply the user never heard and arms the barge-in drop+ flag against the very response that would have spoken it (live+ forensic 2026-07-16 10:26).+ """+ state = self._delegate_turns.get(self._turn_id)+ return bool(+ self._turn_id+ and state is not None+ and state.result_complete+ and state.delivery_started+ and not self._output_active+ and self._output_samples_sent == 0+ )+@staticmethodasync def _coalesce_ready_delegate_result(turn_state: _DelegateTurnState,@@ -2657,13 +2722,58 @@ class RealtimeVoiceSession:except Exception: # noqa: BLE001, S110 — boundary wait retains its fallbackpass+ async def _await_stable_input_boundary(+ self, turn_state: _DelegateTurnState+ ) -> None:+ """Delay a deterministic dispatch until the utterance is provably over.++ The provider's own boundary (its held turn_complete, native function+ call, or the dispatching path marking the input final) is the+ strongest end-of-utterance evidence. A provider that stays completely+ silent must not veto the turn, though: after a full wait window in+ which the accumulated input transcript did not grow, the utterance is+ final by local evidence and the dispatch proceeds (live forensic+ 2026-07-16 10:26 — Gemini produced neither a response nor a boundary+ for a complete question, and the old veto answered it with the canned+ generic failure phrase instead of dispatching the brain). A+ transcript still growing re-arms the window: the user is audibly+ mid-utterance, and dispatching would act on a partial request.+ """+ for _ in range(_DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS):+ transcript_before_wait = self._last_user_text+ try:+ await asyncio.wait_for(+ turn_state.input_boundary_ready.wait(),+ timeout=_DELEGATE_INPUT_BOUNDARY_WAIT_S,+ )+ except TimeoutError:+ if turn_state.input_final or (+ self._last_user_text == transcript_before_wait+ ):+ log.info(+ "realtime[%s] deterministic delegate: provider input "+ "boundary missing after %.1fs; dispatching on the "+ "stable local transcript",+ self.session_id,+ _DELEGATE_INPUT_BOUNDARY_WAIT_S,+ )+ return+ continue+ return+ log.warning(+ "realtime[%s] deterministic delegate: input transcript kept "+ "growing through %d wait rounds; dispatching on the newest "+ "snapshot",+ self.session_id,+ _DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS,+ )+async def _run_deterministic_delegate(self,turn_id: str,turn_state: _DelegateTurnState,) -> None:try:- boundary_ready = Trueif turn_state.wait_for_provider_boundary or bool(getattr(self._session,@@ -2671,19 +2781,7 @@ class RealtimeVoiceSession:False,)):- try:- await asyncio.wait_for(- turn_state.input_boundary_ready.wait(),- timeout=_DELEGATE_INPUT_BOUNDARY_WAIT_S,- )- except TimeoutError:- # The refusal below protects against acting on a PARTIAL- # input transcript. When the dispatching path marked the- # input final, the missing provider boundary is only a- # wire artifact (an interrupt that landed on an- # already-completed response) — proceed; result delivery- # still waits for its own provider boundary.- boundary_ready = turn_state.input_final+ await self._await_stable_input_boundary(turn_state)else:# A manual-response provider may already have queued a native# function call or cancelled output behind the final input@@ -3061,9 +3159,60 @@ class RealtimeVoiceSession:)except Exception: # noqa: BLE001, S110 — best-effort telemetrypass+ self._note_audio_flow(pcm, chunk)self._output_samples_sent += len(pcm) // 2await self._send_binary(pcm)+ def _note_audio_flow(self, pcm: bytes, chunk: Any) -> None:+ """Attribute audible mid-reply holes to their actual producer.++ A silent gap inside one spoken answer has three distinct causes that a+ plain log cannot separate after the fact (live forensic 2026-07-16+ 10:26, ~1 s hole mid-sentence): the scrub gate holding released audio+ because its transcript delta arrived late, the provider sending no+ audio for that span, or silence embedded in the provider's own PCM.+ Emit one INFO line per event so the next occurrence is attributable.+ Pure integer math on the already-decoded chunk — no LLM, no I/O.+ """+ now = time.monotonic()+ if (+ self._output_samples_sent > 0+ and self._turn_id+ and self._last_audio_emit_turn == self._turn_id+ ):+ gap_ms = (now - self._last_audio_emit_monotonic) * 1_000.0+ if gap_ms >= _AUDIO_FLOW_STALL_LOG_MS:+ held_ms = float(getattr(self._gate, "last_hold_ms", 0.0) or 0.0)+ cause = (+ "the transcript needed to clear this audio arrived late"+ if held_ms >= gap_ms * 0.6+ else "the provider sent no audio for this span"+ )+ log.info(+ "realtime[%s] mid-reply audio stalled %d ms before this "+ "chunk (scrub-gate hold %d ms, %d ms still gated) — %s",+ self.session_id,+ int(gap_ms),+ int(held_ms),+ int(float(getattr(self._gate, "pending_audio_ms", 0.0) or 0.0)),+ cause,+ )+ self._last_audio_emit_monotonic = now+ self._last_audio_emit_turn = self._turn_id+ sample_rate = max(1, int(getattr(chunk, "sample_rate", 0) or 24_000))+ chunk_ms = (len(pcm) / 2) * 1_000.0 / sample_rate+ if _pcm16_peak(pcm) < _EMBEDDED_SILENCE_PEAK:+ self._embedded_silence_ms += chunk_ms+ return+ if self._embedded_silence_ms >= _EMBEDDED_SILENCE_LOG_MS:+ log.info(+ "realtime[%s] provider audio carried %d ms of embedded "+ "silence mid-reply (generation pause rendered as silent PCM)",+ self.session_id,+ int(self._embedded_silence_ms),+ )+ self._embedded_silence_ms = 0.0+async def _barge_in(self, *, interrupt_provider: bool = True) -> None:should_interrupt = bool(interrupt_providerdiff --git a/tests/unit/realtime/test_delegate_endpointing.py b/tests/unit/realtime/test_delegate_endpointing.pyindex bda9f809db..7a702bfcf1 100644--- a/tests/unit/realtime/test_delegate_endpointing.py+++ b/tests/unit/realtime/test_delegate_endpointing.py@@ -150,3 +150,238 @@ async def test_unconfirmed_speech_start_does_not_abandon_pending_delegate() -> N"is_final": False,} in messagesassert {"type": "turn_complete"} in messages+++class _InstantBrain:+ """Orchestrator-path brain that answers immediately."""++ conversation_language = "en"++ def __init__(self, reply: str = "Tomorrow is Friday.") -> None:+ self.reply = reply+ self.calls: list[str] = []+ self.started = asyncio.Event()+ self.release = asyncio.Event()+ self.release.set()++ def plan_turn(self, _text: str) -> TurnPlan:+ return TurnPlan(+ path=TurnPath.ORCHESTRATOR,+ reasons=frozenset({TurnReason.LOCAL_STATE}),+ requires_evidence=True,+ )++ async def __call__(self, text: str) -> str:+ self.calls.append(text)+ self.started.set()+ await self.release.wait()+ return self.reply+++class _AutoResponseWire:+ """Gemini-shaped wire: automatic responses, no manual response calls.++ ``script`` controls what the provider does after the final input+ transcript; a completely silent provider keeps the iterator open until+ the session closes it.+ """++ session_id = "auto-response-wire"+ supports_tool_updates = False+ creates_responses_automatically = True+ isolates_response_generations = True++ def __init__(self, brain: Any, *, script: str) -> None:+ self._brain = brain+ self._script = script+ self.text_inputs: list[str] = []+ self.text_sent = asyncio.Event()+ self.interrupts = 0+ self.closed = asyncio.Event()++ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text="What day is tomorrow?",+ is_final=True,+ item_id="date-turn",+ )+ if self._script == "silent":+ # The provider never answers, never calls the tool, and never+ # sends a boundary — the orchestrator must still act.+ await self.closed.wait()+ return+ if self._script == "interrupted-while-pending":+ await self._brain.started.wait()+ # A phantom VAD edge (noise) with no following final transcript.+ yield RealtimeEvent(type="interrupted")+ self._brain.release.set()+ await self.text_sent.wait()+ if self._script == "interrupted-after-delivery":+ # The trusted readback was injected but no PCM is audible yet.+ yield RealtimeEvent(type="interrupted")+ yield RealtimeEvent(+ type="output_transcript_delta",+ text="Tomorrow is Friday.",+ )+ yield RealtimeEvent(type="turn_complete")++ async def send_audio(self, _chunk: Any) -> None:+ return None++ 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:+ self.text_inputs.append(text)+ self.text_sent.set()++ async def truncate(self, _audio_end_ms: int) -> None:+ return None++ async def interrupt(self) -> None:+ self.interrupts += 1++ async def send_tool_result(self, *_args: Any) -> None:+ return None++ async def close(self) -> None:+ self.closed.set()+++class _AutoResponseProvider:+ name = "auto-response"+ supports_realtime = True+ input_sample_rate = 16_000+ output_sample_rate = 24_000++ def __init__(self, brain: Any, *, script: str) -> None:+ self.session = _AutoResponseWire(brain, script=script)++ async def can_open_duplex_session(self) -> bool:+ return True++ async def open_session(self, _config: Any) -> _AutoResponseWire:+ return self.session+++def _shorten_delegate_waits(monkeypatch: pytest.MonkeyPatch) -> None:+ import jarvis.realtime.session as session_module++ monkeypatch.setattr(session_module, "_DELEGATE_INPUT_BOUNDARY_WAIT_S", 0.05)+ monkeypatch.setattr(session_module, "_DELEGATE_NATIVE_BOUNDARY_WAIT_S", 0.05)+++async def _run_auto_response_session(+ brain: Any,+ provider: _AutoResponseProvider,+ messages: list[dict[str, Any]],+ *,+ wait_finished: bool,+) -> RealtimeVoiceSession:+ session = RealtimeVoiceSession(+ session_id="delegate-boundary",+ send_binary=lambda _data: asyncio.sleep(0),+ 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)+ if wait_finished:+ await asyncio.wait_for(session.wait_finished(), timeout=2.0)+ finally:+ await session.end(reason="test")+ return session+++async def test_silent_provider_boundary_timeout_dispatches_instead_of_refusing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A provider that never confirms the input must not veto the action.++ Live forensic 2026-07-16 10:26: Gemini produced neither a response nor a+ boundary for a complete question; the old timeout veto skipped the brain+ entirely and answered with the canned failure phrase.+ """+ _shorten_delegate_waits(monkeypatch)+ brain = _InstantBrain()+ provider = _AutoResponseProvider(brain, script="silent")+ messages: list[dict[str, Any]] = []++ await _run_auto_response_session(+ brain, provider, messages, wait_finished=False+ )++ assert brain.calls == ["What day is tomorrow?"]+ assert len(provider.session.text_inputs) == 1+ assert "Tomorrow is Friday." in provider.session.text_inputs[0]+ assert "didn't work" not in provider.session.text_inputs[0]+++async def test_phantom_interrupted_edge_defers_while_delegate_pending(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An unconfirmed ``interrupted`` edge must not abandon a running action.++ Gemini reports noise blips and real barge-ins alike as ``interrupted``;+ during the silent thinking span there is no output to cut, so the edge is+ deferred exactly like an unconfirmed OpenAI speech start.+ """+ _shorten_delegate_waits(monkeypatch)+ brain = _DelayedBrain()+ provider = _AutoResponseProvider(brain, script="interrupted-while-pending")+ messages: list[dict[str, Any]] = []++ await _run_auto_response_session(+ brain, provider, messages, wait_finished=True+ )++ assert len(provider.session.text_inputs) == 1+ assert "three folders" in provider.session.text_inputs[0]+ assert {+ "type": "transcript",+ "role": "assistant",+ "text": "Tomorrow is Friday.",+ "is_final": False,+ } in messages+ assert {"type": "turn_complete"} in messages+++async def test_phantom_interrupted_after_delivery_keeps_the_readback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A VAD edge between result injection and first audible PCM must defer.++ Closing the turn in this window records a reply the user never heard and+ arms the barge-in drop flag against the very response that would have+ spoken it (live forensic 2026-07-16 10:26).+ """+ _shorten_delegate_waits(monkeypatch)+ brain = _InstantBrain()+ provider = _AutoResponseProvider(brain, script="interrupted-after-delivery")+ messages: list[dict[str, Any]] = []++ await _run_auto_response_session(+ brain, provider, messages, wait_finished=True+ )++ assert len(provider.session.text_inputs) == 1+ assert {+ "type": "transcript",+ "role": "assistant",+ "text": "Tomorrow is Friday.",+ "is_final": False,+ } in messages+ assert {"type": "turn_complete"} in messages