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): keep Vertex Live greetings and native tools (BUG-152, BUG-153)
Harald9f43e9d5b72b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4daf28a678..ddafd1cc6f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,20 @@ versioning per [SemVer](https://semver.org/).---+## [Unreleased]++### Fixed++- **A Gemini Live greeting no longer dies mid-sentence.** Vertex Live fires+ an empty `interrupted` for our own steering text, then speaks the real+ reply. The session used to treat the quiet after that reply's+ `turn_complete` as a confirmed barge-in and cancel the speaker drain —+ full text in the log, half a sentence in the air. The same settle could+ also fire *before* first audio and withhold the whole greeting (BUG-152).+- **Vertex Live native tools work again.** Vertex reports hybrid function+ calls as `default:run_shell`. The bridge treated that as an unknown tool+ and the model said the tools were down (BUG-153).+## [1.4.0] — 2026-08-18This release turns the front page into a mission deck, gives the assistant adiff --git a/docs/BUGS.md b/docs/BUGS.mdindex 606a8e141b..1f044ca977 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -10579,3 +10579,122 @@ repro script AND the bench (3/3 clean runs on the laptop) before it counts.**Guards.** None in CI — a crash test cannot run without the native model;`scripts/vosk_native_stress.py churn 180` (3 x clean) plus 3/3 clean benchruns on the weak laptop are the acceptance test until a fix lands.++## BUG-152: Gemini Live greeting cut off mid-sentence — a stale empty interrupt cancels the speaker drain (CRITICAL, FIXED 2026-08-19)++**Symptom (Windows live forensic, 15:59, `vertex-live` /+`gemini-live-2.5-flash-native-audio`).** The user said "Hey Hallo, was geht+ab?". The SAY panel showed the full reply ("Hallo! Mir geht es gut, und ich+bin bereit für deine nächsten Aufgaben.") but the voice stopped around+"nächsten". The session then sat silent until the user hung up. <!-- i18n-allow: quoted live German utterance and spoken reply under forensic analysis -->++**Timeline (`data/jarvis_desktop.log`).**++| Time | What happened |+|---|---|+| 15:59:07.878 | Steering text sent |+| 15:59:08.049 | Empty `interrupted` (audio=0) — deferred (RT-09) |+| 15:59:08.169 | Empty-turn re-ask sent |+| 15:59:08.331 | Second empty `interrupted` |+| 15:59:09.521 | First audio of the real 3.6 s / 71-char greeting |+| 15:59:10.188 | Provider `turn_complete` |+| 15:59:11.257 | Settle commits the stale interrupt ("silent for 1.0s") |+| 15:59:11.339 | `JARVIS_SPEAKING → LISTENING` via `tts_cancel` |++Desktop `_send_json(turn_complete)` awaits `playback.finish_turn()`, so the+pump is blocked on the remaining ~2 s of audio. The settle task treats that+expected provider silence as "the interrupt won" and cancels the drain.++**Root cause.** Three cooperating defects:++1. Gemini Live emits `interrupted` for our own `send_text` (steering, re-ask)+ even when nothing is playing. The session deferred that edge as if a+ reply were being spoken.+2. Every accepted provider event *refreshed* the 1 s silence timer, including+ the real reply's `turn_complete`. The timer then started from the+ boundary, exactly when the surface began draining.+3. `_clear` of the deferral lived in `_reset_turn_tracking`, which runs+ *after* the blocking `finish_turn`. Too late.++**Fix.** Ignore `interrupted` when no reply is in flight. Cancel the silence+backstop on continued production and on any `turn_complete`, and clear the+deferral at the *start* of `_complete_surface_turn` — before the desktop+drain. The 1 s commit remains only for a generation that dies at the edge+with no later boundary. Empty-turn re-ask silence is owned by that+watchdog, not the barge-in settle.++**Guards.**+`tests/unit/realtime/test_session_noise_interrupt.py`+(`test_empty_interrupt_before_a_reply_is_ignored`,+`test_completed_reply_survives_the_interrupt_silence_window`,+`test_stale_interrupt_cannot_cancel_speaker_drain`);+`tests/unit/realtime/test_session.py`+(`test_empty_turn_reask_reply_survives_speaker_drain`,+`test_empty_turn_reask_survives_the_interrupt_settle_window`).+Existing+`test_unconfirmed_interruption_is_committed_once_the_provider_stops` still+requires the backstop when the provider really stops.++**Class rule.** A provider VAD edge is not a barge-in, and provider silence+after a completed generation is not confirmation of that edge. The surface+drain of an already-rendered reply is not a window in which to cancel it.++**Parity.** Session-level, every realtime transport. Gemini Live is the+transport that emits the empty `interrupted` artifact; OpenAI's+`speech_started` stays instant. Desktop is the surface whose+`turn_complete` blocks on the speaker; browser/headless `send_json` is+non-blocking but the same cancel would still drop queued PCM.++**Same class, 16:07 the same afternoon.** "Was geht ab?" produced no spoken+greeting at all: the 1 s settle committed *before* first audio (1.14 s),+`_drop_provider_output_until_new_response` withheld the 2.9 s native+reply, and the user heard silence then the canned failure of BUG-153.+Guard: `test_empty_turn_reask_survives_the_interrupt_settle_window`. <!-- i18n-allow: quoted live German utterance under forensic analysis -->+++## BUG-153: Vertex Live prefixes native tools with `default:` — every hybrid call answers "tools are not available" (HIGH, FIXED 2026-08-19)++**Symptom (Windows live forensic, 16:07, `vertex-live` /+`gemini-live-2.5-flash-native-audio`, hybrid tool mode).** After the+silent greeting of BUG-152 the user said the internet was broken. Jarvis+spoke "Das hat gerade nicht geklappt." Then, asked why: "Das System+meldet, dass die Tools nicht verfügbar sind. Ich kann keine Diagnose+machen, ohne sie zu starten." Tools were up; 110 native tools were+declared. <!-- i18n-allow: quoted live German utterances and spoken replies under forensic analysis -->++**Timeline (`data/jarvis_desktop.log`).**++| Time | What happened |+|---|---|+| 16:07:26.665 | `gemini-live: function call(s) default:run_shell` |+| 16:07:26.669 | tool response sent for `default:run_shell` |+| 16:07:26.674 | direct-tool turn without output; retry speech from the result |+| 16:07:27.377 | second `default:run_shell` |+| 16:07:27.566 | surface TTS fallback of the canned failure (30 chars) |++**Root cause.** Vertex Live groups `function_declarations` under an+unnamed Tool and reports calls as `{toolset}:{function}`+(`default:run_shell`). AI Studio and OpenAI send the bare declared name.+`RealtimeToolBridge.execute` looked up the prefixed name in+`_wire_to_name`, missed, and returned `"Tool is not available in this+session."` The live model read that error back. The original name must+still be echoed on `send_tool_result` or Vertex rejects the response.++**Fix.** `canonical_tool_wire_name` strips an identifier tool-set prefix+when the suffix is a legal wire name. Lookup tries the name as sent, then+the suffix, then the hashed form. Session special-cases (`jarvis_action`,+`end_call`) use the canonical name; the function response uses the+original.++**Guards.** `tests/unit/realtime/test_tools.py`+(`test_vertex_toolset_prefix_resolves_to_the_declared_tool`,+`test_vertex_prefix_on_a_hashed_wire_name_still_runs`);+`tests/unit/realtime/test_session.py`+(`test_vertex_prefixed_native_tool_call_echoes_the_original_wire_name`).++**Class rule.** A transport-specific tool-name spelling is not a missing+tool. Resolve at lookup; echo on the wire what the provider emitted.++**Parity.** Lookup is session/bridge-level, every realtime transport.+Only Vertex Live is known to emit the `default:` prefix; OpenAI and+Gemini AI Studio send the declared name and hit the exact-match path.diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex ff9538f125..b1472311f5 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -64,6 +64,7 @@ from jarvis.core.turn_language import (from jarvis.realtime.audio import StreamingPcm16Resamplerfrom jarvis.realtime.protocol import RealtimeSessionConfig, RealtimeUnavailableErrorfrom jarvis.realtime.scrub_gate import ScrubHoldGate+from jarvis.realtime.tools import canonical_tool_wire_namefrom jarvis.sessions.constants import (HANGUP_CLIENT_STOP,HANGUP_DESKTOP_FALLBACK,@@ -174,12 +175,13 @@ _UNBACKED_CLAIM_SETTLE_POLL_S = 0.05# Gemini's server VAD reports a cough, a closing door and a real barge-in with# the same flag. WORDS are the proof, and they arrive moments later as the# final input transcript that already splits the turn. This is the bounded-# escape hatch for the edge that no words ever confirm: while the provider-# keeps producing, the edge demonstrably cut nothing and the answer runs on;-# once the provider has been silent this long the generation really did end-# there, and the interruption is committed exactly as it always was — late-# enough that room noise no longer truncates a live answer. It is also the-# hard cap on the extra overlap a genuine barge-in can cost.+# escape hatch for the edge that no words ever confirm: production after the+# edge (audio, transcript, or a ``turn_complete`` boundary) cancels it,+# because the generation continued or ended as a normal turn. Only total+# silence with no later boundary commits it — late enough that room noise no+# longer truncates a live answer, and never while the surface is still+# draining the speaker queue (BUG-152). It is also the hard cap on the extra+# overlap a genuine barge-in can cost._INTERRUPTION_CONFIRM_WINDOW_S = 1.0_INTERRUPTION_SETTLE_POLL_S = 0.1# Withheld provider output used to leave no trace anywhere (AP-30): a turn could@@ -2198,9 +2200,8 @@ class RealtimeVoiceSession:self._user_speech_active = Falseself._deferred_provider_speech_start = False# An ``interrupted`` edge awaiting the user's words (RT-09). Non-zero- # while a deferral is live, and refreshed by every accepted provider- # event, so the settle task measures provider SILENCE since the edge- # rather than wall time since it.+ # while a deferral is live. Continued production or a turn boundary+ # cancels it; only total silence with no later boundary commits it.self._interruption_deferred_at = 0.0self._interruption_settle_task: asyncio.Task[None] | None = Noneself._unconfirmed_interruptions = 0@@ -4031,13 +4032,18 @@ class RealtimeVoiceSession:self._note_turn_activity()if not await self._accept_provider_response_event(event):continue- if self._interruption_deferred_at:- # Accepted provider traffic proves a deferred ``interrupted``- # edge cut nothing: the response is still being produced.- # Measured HERE and not from ``_turn_activity_at``, which the- # stall watchdog keeps refreshing on its own while the gate- # holds PCM — the settle backstop would then never fire.- self._interruption_deferred_at = time.monotonic()+ if self._interruption_deferred_at and event.type in {+ "audio_delta",+ "output_transcript_delta",+ }:+ # The generation kept producing after the edge, so the+ # edge cut nothing. Drop the silence backstop; do not+ # refresh it. Refreshing kept the deferral alive until+ # ``turn_complete``, after which the expected provider+ # silence committed the stale edge and cancelled the+ # speaker drain mid-sentence (BUG-152). The deferred+ # flag stays so the user's own words can still confirm.+ self._cancel_interruption_settle()if event.type in {"audio_delta","output_transcript_delta",@@ -5084,6 +5090,7 @@ class RealtimeVoiceSession:elif event.type in {"speech_started", "interrupted"} and (self._pending_delegate_needs_endpoint_protection()or self._delegate_readback_awaits_first_audio()+ or self._empty_turn_reask_owns_turn(self._turn_id)):# Gemini has no separate speech-start edge: its server VAD# reports noise blips and real barge-ins alike as@@ -5094,8 +5101,11 @@ class RealtimeVoiceSession:# 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.+ # The empty-turn re-ask owns the same kind of silence+ # (live 2026-08-19 16:07: Vertex closed the re-ask text+ # empty, the 1s settle committed, native audio 0.1s later+ # was withheld). 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 "@@ -5103,10 +5113,10 @@ class RealtimeVoiceSession:self.session_id,event.type,)- # No settle task here: this window is owned by the delegate,- # whose own budget and readback watchdog decide when it is- # over. A silence timer would abandon exactly the turn this- # branch exists to protect.+ # No settle task here: this window is owned by the+ # delegate or the re-ask watchdog, whose own budget+ # decides when it is over. A silence timer would abandon+ # exactly the turn this branch exists to protect.self._deferred_provider_speech_start = Trueelif event.type == "interrupted":# The SAME ambiguity, now while a reply is actually being@@ -5123,16 +5133,27 @@ class RealtimeVoiceSession:# ``speech_started`` is deliberately NOT deferred here: the# transports that emit it (OpenAI) mean it literally, and# their barge-in must stay instant.- if not self._deferred_provider_speech_start:- self._unconfirmed_interruptions += 1+ if not self._reply_is_in_flight():+ # Gemini Live emits ``interrupted`` for our own+ # send_text (steering, empty-turn re-ask) even when+ # nothing is playing. Deferring that arms a silence+ # backstop that later cuts the real reply (BUG-152).log.info(- "realtime[%s] deferred an unconfirmed provider "- "interruption; waiting for the user's own words "- "before cutting the reply",+ "realtime[%s] ignored a provider interruption "+ "with no reply in flight",self.session_id,)- self._deferred_provider_speech_start = True- self._arm_interruption_settle()+ else:+ if not self._deferred_provider_speech_start:+ self._unconfirmed_interruptions += 1+ log.info(+ "realtime[%s] deferred an unconfirmed provider "+ "interruption; waiting for the user's own words "+ "before cutting the reply",+ self.session_id,+ )+ self._deferred_provider_speech_start = True+ self._arm_interruption_settle()elif (event.type == "speech_started"and self._turn_held_for_pause()@@ -5211,6 +5232,10 @@ class RealtimeVoiceSession:# result may deliver now that the wire is quiet.self._schedule_late_delegate_flush()continue+ # A provider boundary — empty or not — means this+ # generation ended. The silence backstop is only for the+ # case where no boundary ever comes (BUG-152).+ self._cancel_interruption_settle()if self._output_language_retry_pending:if not self._output_language_retry_requested:await self._request_output_language_retry()@@ -5986,6 +6011,7 @@ class RealtimeVoiceSession:# 1008 right as turn 21's reply drained; the rebuild succeeded in# ~2 s but the user spoke into a swallowed microphone for 20 s).try:+ self._clear_deferred_interruption()await self._send_json({"type": "turn_complete"})except Exception: # noqa: BLE001, S110 — surface mirror is best-effortpass@@ -6622,6 +6648,20 @@ class RealtimeVoiceSession:)return True+ def _reply_is_in_flight(self) -> bool:+ """True when an assistant reply is audible, buffered, or transcribing."""+ return bool(+ self._output_active+ or self._output_samples_sent > 0+ or self._gate.pending_audio_ms > 0+ or "".join(self._output_transcript).strip()+ )++ def _clear_deferred_interruption(self) -> None:+ """Drop a deferred VAD edge: it did not cut this generation."""+ self._deferred_provider_speech_start = False+ self._cancel_interruption_settle()+def _cancel_interruption_settle(self) -> None:self._interruption_deferred_at = 0.0task = self._interruption_settle_task@@ -6634,12 +6674,15 @@ class RealtimeVoiceSession:Deferring is free while the answer keeps arriving — the edge cutnothing and the reply runs on. It is not free when the generation- really did end there: the gate's held PCM makes the 20 s stall- watchdog excuse the silence forever, so the turn would wait for a- boundary that is never coming. This task closes exactly that gap by- committing the interruption unchanged once the provider has been- silent for ``_INTERRUPTION_CONFIRM_WINDOW_S``. Re-armed per deferral- and cancelled with the turn (AP-19).+ really did end there with no later boundary: the gate's held PCM+ makes the 20 s stall watchdog excuse the silence forever, so the+ turn would wait for a boundary that is never coming. This task+ closes exactly that gap by committing the interruption unchanged+ once the provider has been silent for+ ``_INTERRUPTION_CONFIRM_WINDOW_S``. Continued production and any+ ``turn_complete`` cancel it instead, so expected silence after a+ finished reply cannot cut the speaker drain (BUG-152). Re-armed+ per deferral and cancelled with the turn (AP-19)."""self._interruption_deferred_at = time.monotonic()task = self._interruption_settle_task@@ -6676,6 +6719,11 @@ class RealtimeVoiceSession:# reply is recorded but not yet spoken — the 2026-07-16# forensic the delegate-window branch above exists for.return+ if self._empty_turn_reask_owns_turn(turn_id):+ # The re-ask is still waiting for native audio. Provider+ # silence here is the interrupt artifact of our own text,+ # not proof the generation ended.+ continueif time.monotonic() - self._interruption_deferred_at < (_INTERRUPTION_CONFIRM_WINDOW_S):@@ -7671,6 +7719,10 @@ class RealtimeVoiceSession:return Falseself._empty_turn_reask_turn_id = turn_idself._drop_provider_output_until_new_response = False+ # The empty ``interrupted`` of the steering/re-ask text itself often+ # armed the RT-09 settle ~1s earlier. That timer must not close this+ # turn while we wait for native audio (live 2026-08-19 16:07).+ self._clear_deferred_interruption()try:await send_text(_empty_turn_reask_prompt(@@ -7722,6 +7774,7 @@ class RealtimeVoiceSession:or self._output_samples_sent > 0or "".join(self._output_transcript).strip()):+ self._clear_deferred_interruption()returnif time.monotonic() >= deadline:break@@ -8048,6 +8101,12 @@ class RealtimeVoiceSession:Publishing needs a turn id; RESETTING never does (see``_reset_output_state``)."""+ # Drop any deferred VAD edge first. On the desktop+ # ``_send_json(turn_complete)`` blocks until the speaker queue+ # drains, and that silence is exactly what the settle task used+ # to treat as "the interrupt won" — it sent ``tts_cancel``+ # mid-drain (BUG-152).+ self._clear_deferred_interruption()if self._turn_id:await self._send_json({"type": "turn_complete"})await self._publish_turn_completed()@@ -9567,10 +9626,11 @@ class RealtimeVoiceSession:returncall_id = str(getattr(event, "call_id", "") or "")wire_name = str(getattr(event, "tool_name", "") or "")+ declared_name = canonical_tool_wire_name(wire_name)arguments = getattr(event, "tool_args", None)if not isinstance(arguments, dict):arguments = {}- if self._external_update is not None and wire_name != "end_call":+ if self._external_update is not None and declared_name != "end_call":# Background summaries are untrusted data for wording only. Even if# their content contains a prompt injection, they cannot act.await self._session.send_tool_result(@@ -9585,7 +9645,7 @@ class RealtimeVoiceSession:if (self._delegate_enabledand call_id- and wire_name == str(_DELEGATE_DECLARATION["name"])+ and declared_name == str(_DELEGATE_DECLARATION["name"])):provider_request = str(arguments.get("request", "") or "").strip()local_plan = self._plan_turn(self._last_user_text)@@ -9708,7 +9768,9 @@ class RealtimeVoiceSession:# arrives, so a slow one gets the instant-ack treatment — one line# after the short grace, at most once per turn.ack_task = asyncio.create_task(- self._native_tool_ack_after_grace(self._turn_id, wire_name),+ self._native_tool_ack_after_grace(+ self._turn_id, declared_name or wire_name+ ),name=f"rt-native-tool-ack-{self.session_id}",)try:@@ -10769,6 +10831,7 @@ class RealtimeVoiceSession:# close the turn locally so the surface leaves PROCESSING# (same local-boundary pattern as the held-turn_complete and# rebuild paths).+ self._clear_deferred_interruption()await self._send_json({"type": "turn_complete"})await self._publish_turn_completed()returndiff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pyindex f7bfb2484e..13a6e6beeb 100644--- a/jarvis/realtime/tools.py+++ b/jarvis/realtime/tools.py@@ -89,6 +89,25 @@ def _wire_name(name: str) -> str:return f"{normalized[:52]}_{digest}"+def canonical_tool_wire_name(name: str) -> str:+ """Strip a Gemini/Vertex tool-set prefix from a function-call name.++ Vertex Live groups ``function_declarations`` under an unnamed Tool and+ reports calls as ``{toolset}:{function}`` (live 2026-08-19 16:07:+ ``default:run_shell``). AI Studio and OpenAI send the bare declared+ name. Only an identifier prefix plus a legal wire-name suffix is+ stripped — URLs and other colons stay intact. The original name is+ still what ``send_tool_result`` must echo back on the wire.+ """+ raw = str(name or "").strip()+ if not raw or ":" not in raw:+ return raw+ prefix, suffix = raw.split(":", 1)+ if suffix and prefix.isidentifier() and _VALID_WIRE_NAME.fullmatch(suffix):+ return suffix+ return raw++def _json_safe(value: Any) -> Any:return json.loads(json.dumps(value, ensure_ascii=False, default=str))@@ -516,7 +535,8 @@ class RealtimeToolBridge:arguments: dict[str, Any],trace_id: UUID | None = None,) -> tuple[str, dict[str, Any]]:- name = self._wire_to_name.get(wire_name, "")+ name = self._declared_name_for_wire(wire_name)+ name, arguments = self._maybe_reroute_music(name, arguments)descriptor = self._descriptors.get(name)if descriptor is None:await self._publish_denied(wire_name, "unknown realtime tool")@@ -642,6 +662,66 @@ class RealtimeToolBridge:return await self._gateway.cancel_pending(trace_id)return bool(await self._executor.cancel_pending(trace_id))+ def _declared_name_for_wire(self, wire_name: str) -> str:+ """Map a provider function-call name onto a catalog tool name.++ Tries the wire name as sent, then a stripped tool-set prefix+ (``default:run_shell``), then the hashed form used for names+ that are not legal identifiers.+ """+ if not wire_name:+ return ""+ mapped = self._wire_to_name.get(wire_name, "")+ if mapped:+ return mapped+ canonical = canonical_tool_wire_name(wire_name)+ mapped = self._wire_to_name.get(canonical, "")+ if mapped:+ return mapped+ return self._wire_to_name.get(_wire_name(canonical), "")++ def _maybe_reroute_music(+ self, name: str, arguments: dict[str, Any]+ ) -> tuple[str, dict[str, Any]]:+ """Send an unnamed music call to the preferred/only connected service.++ Hybrid live models hold both music tools and pick by description+ (2026-08-19: preference YouTube Music, Spotify not connected, the+ model still called ``spotify``). Descriptions are a hint; this is+ the correctness boundary. A named service still wins. Never raises.+ """+ try:+ from jarvis.core.music_constants import MUSIC_PLUGIN_IDS+ from jarvis.core.music_service import (+ adapt_music_arguments,+ reroute_music_tool,+ )+ except Exception: # noqa: BLE001 — a routing nicety must never break a turn+ return name, arguments+ if name not in MUSIC_PLUGIN_IDS:+ return name, arguments+ try:+ target = reroute_music_tool(name, self._last_user_text)+ except Exception as exc: # noqa: BLE001+ log.debug("realtime music tool reroute skipped: %s", exc)+ return name, arguments+ if target == name or target not in self._descriptors:+ return name, arguments+ log.info(+ "realtime music tool rerouted %s -> %s",+ name,+ target,+ )+ args = arguments if isinstance(arguments, dict) else {}+ try:+ adapted = adapt_music_arguments(+ self._last_user_text, source=name, target=target, args=args+ )+ except Exception as exc: # noqa: BLE001+ log.debug("realtime music arg adapt skipped: %s", exc)+ adapted = args+ return target, adapted+def _validate_arguments(self,descriptor: SupervisorToolDescriptor,diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex a7a47a6c3f..3944446880 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -4949,6 +4949,210 @@ async def test_empty_turn_reask_keeps_native_audio_after_a_second_empty_boundaryawait sess.end(reason="test")+async def test_empty_turn_reask_survives_the_interrupt_settle_window(monkeypatch):+ """A 1s RT-09 settle must not kill the re-asked native reply.++ Live 2026-08-19 16:07 (vertex-live, "Was geht ab?"): steering closed+ empty, the re-ask went out, the first interrupt's 1s settle committed+ BEFORE native audio (1.14s), withheld the 2.9s greeting, and the user+ heard nothing. The watchdog owns that silence; native audio that still+ comes must be spoken.+ """ # i18n-allow: quoted live utterance+ import jarvis.realtime.session as session_module++ monkeypatch.setattr(session_module, "_INTERRUPTION_CONFIRM_WINDOW_S", 0.05)+ monkeypatch.setattr(session_module, "_INTERRUPTION_SETTLE_POLL_S", 0.02)++ user_text = "Hello there."+ native_reply = "Hello. I am ready."+ spoken_audio = AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ )++ class _DelayedNativeAfterReask(ScriptedTextTurnsSession):+ async def receive(self):+ for event in self._before_result:+ yield event+ await asyncio.sleep(0)+ while not self.text_inputs:+ await self._text_arrived.wait()+ self._text_arrived.clear()+ yield RealtimeEvent(type="interrupted")+ yield RealtimeEvent(type="turn_complete")+ await asyncio.sleep(0.18)+ yield RealtimeEvent(+ type="output_transcript_delta",+ text=native_reply,+ is_final=True,+ )+ yield RealtimeEvent(type="audio_delta", audio=spoken_audio)+ yield RealtimeEvent(type="turn_complete")++ class _DelayedNativeProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _DelayedNativeAfterReask(+ [+ RealtimeEvent(+ type="input_transcript",+ text=user_text,+ is_final=True,+ ),+ RealtimeEvent(type="interrupted"),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ return self.session++ brain = FakeBrain(replies=("never spoken",))+ provider = _DelayedNativeProvider([])+ jsons: list[dict] = []+ binaries: list[bytes] = []+ bus = FakeBus()+ sess = _session(+ provider,+ brain=brain,+ tool_mode="direct",+ jsons=jsons,+ binaries=binaries,+ bus=bus,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=3)++ assert brain.calls == [], "the settle must not start the Brain chain"+ assert binaries == [spoken_audio.pcm]+ completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]+ assert len(completed) == 1+ assert completed[0].jarvis_text == native_reply+ await sess.end(reason="test")+++async def test_empty_turn_reask_reply_survives_speaker_drain(monkeypatch):+ """A stale interrupt must not ``tts_cancel`` while the speaker drains.++ Live 2026-08-19 15:59: the native 3.6 s greeting was already playing when+ ``turn_complete`` blocked on desktop ``finish_turn``. One second of+ expected provider silence committed the earlier empty interrupt and the+ user heard half a sentence.+ """+ import jarvis.realtime.session as session_module++ monkeypatch.setattr(session_module, "_INTERRUPTION_CONFIRM_WINDOW_S", 0.05)+ user_text = "Hello there."+ native_reply = "Hello. I am ready."+ spoken_audio = AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ )+ brain = FakeBrain(replies=("never spoken",))+ provider = ScriptedTextTurnsProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text=user_text,+ is_final=True,+ ),+ RealtimeEvent(type="interrupted"),+ RealtimeEvent(type="turn_complete"),+ ],+ [+ RealtimeEvent(type="interrupted"),+ RealtimeEvent(type="turn_complete"),+ RealtimeEvent(+ type="output_transcript_delta",+ text=native_reply,+ is_final=True,+ ),+ RealtimeEvent(type="audio_delta", audio=spoken_audio),+ RealtimeEvent(type="turn_complete"),+ ],+ )+ jsons: list[dict] = []+ binaries: list[bytes] = []++ async def slow_send_json(message):+ jsons.append(message)+ if message.get("type") == "turn_complete":+ await asyncio.sleep(0.3)++ bus = FakeBus()+ sess = RealtimeVoiceSession(+ session_id="delegate-test",+ send_binary=lambda data: binaries.append(data) or asyncio.sleep(0),+ send_json=slow_send_json,+ provider=provider,+ config=_delegate_cfg("direct"),+ bus=bus,+ brain=brain,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=3)++ assert brain.calls == []+ assert binaries == [spoken_audio.pcm]+ assert not any(item.get("type") == "tts_cancel" for item in jsons)+ completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]+ assert len(completed) == 1+ assert completed[0].jarvis_text == native_reply+ await sess.end(reason="test")+++async def test_vertex_prefixed_native_tool_call_echoes_the_original_wire_name():+ """Vertex Live must get ``default:open_app`` back on the function response.++ Lookup strips the prefix; the wire still echoes the name the provider+ emitted, or Vertex rejects the tool response.+ """+ bridge = FakeToolBridge()+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="Open Calculator",+ is_final=True,+ ),+ RealtimeEvent(+ type="tool_call",+ call_id="call-1",+ tool_name="default:open_app",+ tool_args={"app_name": "Calculator"},+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = RealtimeVoiceSession(+ session_id="vertex-prefix-tool",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ tool_bridge=bridge,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert bridge.calls == [("default:open_app", {"app_name": "Calculator"})]+ assert provider.session.tool_results == [+ (+ "call-1",+ "default:open_app",+ {"success": True, "output": "opened", "error": None},+ )+ ]++@pytest.mark.asyncioasync def test_direct_mode_recovers_provider_turn_that_has_no_output(monkeypatch):"""A substantive user turn must never complete as successful silence.diff --git a/tests/unit/realtime/test_session_noise_interrupt.py b/tests/unit/realtime/test_session_noise_interrupt.pyindex bdfc110a27..cc11efee24 100644--- a/tests/unit/realtime/test_session_noise_interrupt.py+++ b/tests/unit/realtime/test_session_noise_interrupt.py@@ -56,16 +56,15 @@ def _assistant_text(jsons):return "".join(str(message.get("text") or "")for message in jsons- if message.get("type") == "transcript"- and message.get("role") == "assistant"+ if message.get("type") == "transcript" and message.get("role") == "assistant")-async def _run(provider, *, binaries, jsons):+async def _run(provider, *, binaries, jsons, send_json=None):sess = RealtimeVoiceSession(session_id="noise-interrupt",send_binary=lambda data: binaries.append(data) or asyncio.sleep(0),- send_json=lambda message: jsons.append(message) or asyncio.sleep(0),+ send_json=send_json or (lambda message: jsons.append(message) or asyncio.sleep(0)),provider=provider,config=_cfg(),bus=None,@@ -119,9 +118,7 @@ async def test_confirmed_barge_in_still_cuts_the_answer():)yield RealtimeEvent(type="interrupted")# Real words, moments later: this is a barge-in.- yield RealtimeEvent(- type="input_transcript", text="Hey, listen to me.", is_final=True- )+ yield RealtimeEvent(type="input_transcript", text="Hey, listen to me.", is_final=True)yield RealtimeEvent(type="turn_complete")binaries, jsons = [], []@@ -159,3 +156,116 @@ async def test_unconfirmed_interruption_is_committed_once_the_provider_stops():session_mod._INTERRUPTION_CONFIRM_WINDOW_S = originalassert any(item.get("type") == "tts_cancel" for item in jsons)+++async def test_empty_interrupt_before_a_reply_is_ignored():+ """Gemini Live fires ``interrupted`` for our own text with nothing playing.++ Live 2026-08-19 15:59: steering and the empty-turn re-ask each produced+ an empty ``interrupted``+``turn_complete`` before the real greeting.+ Deferring that armed a silence backstop that later cut the spoken reply.+ """++ async def script():+ yield RealtimeEvent(type="input_transcript", text=OPENING, is_final=True)+ yield RealtimeEvent(type="interrupted")+ yield RealtimeEvent(type="output_transcript_delta", text="It is sunny and warm.")+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(pcm=HEAD + TAIL, sample_rate=24_000, timestamp_ns=0),+ )+ yield RealtimeEvent(type="turn_complete")++ binaries, jsons = [], []+ provider = _scripted(script)+ sess = await _run(provider, binaries=binaries, jsons=jsons)++ assert binaries == [HEAD + TAIL]+ assert "It is sunny and warm." in _assistant_text(jsons)+ assert not any(item.get("type") == "tts_cancel" for item in jsons)+ assert sess._unconfirmed_interruptions == 0+++async def test_completed_reply_survives_the_interrupt_silence_window():+ """A cough mid-reply must not tts_cancel after the generation's own boundary."""++ from jarvis.realtime import session as session_mod++ async def script():+ yield RealtimeEvent(type="input_transcript", text=OPENING, is_final=True)+ yield RealtimeEvent(type="output_transcript_delta", text="It is sunny")+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(pcm=HEAD, sample_rate=24_000, timestamp_ns=0),+ )+ yield RealtimeEvent(type="interrupted")+ yield RealtimeEvent(type="output_transcript_delta", text=" and warm.")+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(pcm=TAIL, sample_rate=24_000, timestamp_ns=0),+ )+ yield RealtimeEvent(type="turn_complete")+ await asyncio.sleep(0.4)++ binaries, jsons = [], []+ provider = _scripted(script)+ original = session_mod._INTERRUPTION_CONFIRM_WINDOW_S+ session_mod._INTERRUPTION_CONFIRM_WINDOW_S = 0.05+ try:+ sess = await _run(provider, binaries=binaries, jsons=jsons)+ finally:+ session_mod._INTERRUPTION_CONFIRM_WINDOW_S = original++ assert binaries == [HEAD, TAIL]+ assert "and warm." in _assistant_text(jsons)+ assert not any(item.get("type") == "tts_cancel" for item in jsons)+ assert sess._unconfirmed_interruptions == 1+++async def test_stale_interrupt_cannot_cancel_speaker_drain():+ """Desktop ``finish_turn`` blocks on ``turn_complete``; that silence is expected.++ Live 2026-08-19 15:59: the 3.6 s greeting was still draining when the+ settle task treated 1 s of post-boundary provider silence as a confirmed+ barge-in and sent ``tts_cancel``. The user heard half a sentence.+ """++ from jarvis.realtime import session as session_mod++ async def script():+ yield RealtimeEvent(type="input_transcript", text=OPENING, is_final=True)+ yield RealtimeEvent(type="output_transcript_delta", text="It is sunny")+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(pcm=HEAD, sample_rate=24_000, timestamp_ns=0),+ )+ yield RealtimeEvent(type="interrupted")+ yield RealtimeEvent(type="output_transcript_delta", text=" and warm.")+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(pcm=TAIL, sample_rate=24_000, timestamp_ns=0),+ )+ yield RealtimeEvent(type="turn_complete")++ binaries, jsons = [], []++ async def slow_send_json(message):+ jsons.append(message)+ if message.get("type") == "turn_complete":+ await asyncio.sleep(0.3)++ provider = _scripted(script)+ original = session_mod._INTERRUPTION_CONFIRM_WINDOW_S+ session_mod._INTERRUPTION_CONFIRM_WINDOW_S = 0.05+ try:+ sess = await _run(provider, binaries=binaries, jsons=jsons, send_json=slow_send_json)+ finally:+ session_mod._INTERRUPTION_CONFIRM_WINDOW_S = original++ assert binaries == [HEAD, TAIL]+ assert "and warm." in _assistant_text(jsons)+ assert not any(item.get("type") == "tts_cancel" for item in jsons)+ assert sess._unconfirmed_interruptions == 1diff --git a/tests/unit/realtime/test_tools.py b/tests/unit/realtime/test_tools.pyindex c31272f377..33d61eb2f1 100644--- a/tests/unit/realtime/test_tools.py+++ b/tests/unit/realtime/test_tools.py@@ -121,6 +121,48 @@ async def test_available_tool_runs_only_through_tool_executor():assert executor.execute_calls[0][2]["config_snapshot"]["voice_confirm"] is True+async def test_vertex_toolset_prefix_resolves_to_the_declared_tool():+ """Vertex Live prefixes user-declared functions with the tool-set name.++ Live 2026-08-19 16:07: hybrid vertex-live called ``default:run_shell``.+ The bridge looked that name up verbatim, returned "Tool is not available+ in this session.", and the model spoke that error. The prefix is a+ transport artifact; the declared tool must still run.+ """+ from jarvis.realtime.tools import canonical_tool_wire_name++ assert canonical_tool_wire_name("default:run_shell") == "run_shell"+ assert canonical_tool_wire_name("open_app") == "open_app"+ assert canonical_tool_wire_name("default:jarvis_action") == "jarvis_action"++ bridge, tool, executor = _bridge()+ await bridge.handle_user_transcript("Open Calculator")++ name, result = await bridge.execute(+ wire_name="default:open_app", arguments={"app_name": "Calculator"}+ )++ assert name == "open_app"+ assert result == {"success": True, "output": "opened", "error": None}+ assert executor.execute_calls[0][0] is tool+++async def test_vertex_prefix_on_a_hashed_wire_name_still_runs():+ bridge, tool, executor = _bridge(name="call-contact")+ wire = bridge.declarations[0]["name"]+ await bridge.handle_user_transcript("Open Calculator")++ name, result = await bridge.execute(+ wire_name=f"default:{wire}", arguments={"app_name": "Calculator"}+ )++ assert name == "call-contact"+ assert result["success"] is True+ assert executor.execute_calls[0][0] is tool++@pytest.mark.asyncioasync def test_missing_required_argument_is_denied_before_executor():bridge, _tool, executor = _bridge()