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): a native tool call releases the live model after 15 s instead of holding the voice mute
rubenluetke10-beep983cb0cd755d
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex a056c580d1..ed02bf08db 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -635,6 +635,19 @@ _CAPABILITY_LIMITED_DELEGATE_BRIDGE_DELAY_S = 1.0# (3 s since 2026-08-18, ADR-0033). Kept as a module attribute so tests can# pin it low._INSTANT_ACK_GRACE_S = SHORT_GRACE_S+# Hard ceiling for ONE native tool call in the live voice path. A native call+# blocks the live model until its result arrives (ADR-0035 §3), so an unbounded+# wait IS a mute call: live 2026-08-22 20:01:52 a ``youtube_music`` play sat+# 199 s on a stuck background-player host — instant ack at 3 s, then nothing+# until 20:05:12 — while every other tool of the day finished in under 3 s+# (``REALTIME_TOOL_COMPLETED`` durations: search_web 2.1–2.9 s, run-skill+# <30 ms, youtube_music 2.6 s when the player answered). Past this ceiling the+# model gets an honest "still running" result and answers; the tool keeps+# running to completion in the background (an action mid-flight is never+# cancelled) and its late outcome is logged and recorded, not dropped. The+# ceiling is generous on purpose: the slowest honest path by design (YouTube+# Music's cold-start confirm, ~9 s plus a window show) still fits under it.+_NATIVE_TOOL_DEADLINE_S = 15.0# 20 messages, not 8: a failed screen action typically costs the user several# correction turns, and each background completion adds a context note. With 8,# the original task was trimmed out exactly when the recovery turn needed it@@ -10991,7 +11004,47 @@ class RealtimeVoiceSession:for parameter in parameters):execute_kwargs["trace_id"] = self._turn_trace_id- original_name, result = await execute(**execute_kwargs)+ tool_task = asyncio.ensure_future(execute(**execute_kwargs))+ try:+ # ``shield``: the deadline releases the LIVE MODEL, never+ # the tool — an action mid-flight runs to completion and+ # reports late (see ``_on_late_native_tool_result``).+ original_name, result = await asyncio.wait_for(+ asyncio.shield(tool_task), timeout=_NATIVE_TOOL_DEADLINE_S+ )+ except TimeoutError:+ original_name = declared_name or wire_name+ log.warning(+ "realtime[%s] native tool %s still running after %.0fs; "+ "releasing the live model with a pending result, the "+ "tool finishes in the background",+ self.session_id,+ original_name,+ _NATIVE_TOOL_DEADLINE_S,+ )+ self._mark_latency_named(+ "REALTIME_TOOL_COMPLETED",+ detail=(+ f"tool={original_name};success=False;pending=True;"+ f"duration_ms={round((time.monotonic() - started_at) * 1000)}"+ ),+ )+ tool_task.add_done_callback(+ lambda done, _name=original_name, _t0=started_at: (+ self._on_late_native_tool_result(_name, _t0, done)+ )+ )+ result = {+ "success": False,+ "pending": True,+ "error": (+ "This tool is still running after "+ f"{_NATIVE_TOOL_DEADLINE_S:.0f} seconds and will finish "+ "in the background. Tell the user in one short sentence "+ "that it is taking longer than usual; do not call it "+ "again in this turn and do not claim it is done."+ ),+ }except Exception: # noqa: BLE001 -- a failed tool must not kill duplex audiolog.warning("realtime tool execution failed: %s", wire_name, exc_info=True)await self._publish_error(@@ -11006,8 +11059,10 @@ class RealtimeVoiceSession:}if result.get("success"):self._executed_tool_names.add(original_name)- elif result.get("confirmation_required"):- pass # a pending confirmation is neither a failure nor a denial+ elif result.get("confirmation_required") or result.get("pending"):+ # A pending confirmation or a tool released at the deadline is+ # neither a failure nor a denial; the late outcome books itself.+ passelif result.get("blocked") or (# The string probe stays as the fallback for a custom bridge# that predates the ``blocked`` flag; the flag is the truth@@ -11018,14 +11073,19 @@ class RealtimeVoiceSession:self._native_tool_denied += 1else:self._native_tool_failures += 1- self._direct_tool_results.append((original_name, dict(result)))- self._mark_latency_named(- "REALTIME_TOOL_COMPLETED",- detail=(- f"tool={original_name};success={bool(result.get('success'))};"- f"duration_ms={round((time.monotonic() - started_at) * 1000)}"- ),- )+ if not result.get("pending"):+ # A released call is still running: it is neither a result the+ # readback fallback may speak nor "unfinished work" the recovery+ # would ask the model to redo (that is how a second play call+ # would be born). Its outcome books itself when it lands.+ self._direct_tool_results.append((original_name, dict(result)))+ self._mark_latency_named(+ "REALTIME_TOOL_COMPLETED",+ detail=(+ f"tool={original_name};success={bool(result.get('success'))};"+ f"duration_ms={round((time.monotonic() - started_at) * 1000)}"+ ),+ )finally:self._native_tools_in_flight = max(0, self._native_tools_in_flight - 1)if not ack_task.done():@@ -11093,6 +11153,57 @@ class RealtimeVoiceSession:except Exception: # noqa: BLE001 — a failed ack must not hurt the calllog.debug("realtime[%s] native-tool ack send failed", self.session_id, exc_info=True)+ def _on_late_native_tool_result(+ self, name: str, started_at: float, done: asyncio.Future[Any]+ ) -> None:+ """Book the outcome of a native tool that outlived its deadline.++ The live model already answered with the pending result; what the tool+ finally did still lands in the log, the failure counter and the+ latency record. Deliberately NOT in the per-turn evidence+ (``_executed_tool_names`` / ``_direct_tool_results``): those are+ cleared and read per turn, and by now the user may be mid-way through+ an unrelated one — a late music result must never become that turn's+ readback. Nothing is spoken here either: the tool's own effect (music+ playing, a window opening) is the user-visible outcome, and a second+ voice turn for it would interrupt whatever the user is doing by then.+ """+ elapsed_ms = round((time.monotonic() - started_at) * 1000)+ if done.cancelled():+ log.info(+ "realtime[%s] late native tool %s was cancelled after %d ms",+ self.session_id, name, elapsed_ms,+ )+ return+ exc = done.exception()+ if exc is not None:+ log.warning(+ "realtime[%s] late native tool %s failed after %d ms: %s",+ self.session_id, name, elapsed_ms, exc,+ )+ self._native_tool_failures += 1+ return+ try:+ original_name, result = done.result()+ except Exception: # noqa: BLE001 — an odd bridge return shape is logged, never raised here+ log.warning(+ "realtime[%s] late native tool %s returned an unreadable result",+ self.session_id, name, exc_info=True,+ )+ return+ success = bool(isinstance(result, dict) and result.get("success"))+ log.info(+ "realtime[%s] late native tool %s finished after %d ms (success=%s) — "+ "the live model was released at %.0fs",+ self.session_id, original_name, elapsed_ms, success, _NATIVE_TOOL_DEADLINE_S,+ )+ if not success and not (isinstance(result, dict) and result.get("blocked")):+ self._native_tool_failures += 1+ self._mark_latency_named(+ "REALTIME_TOOL_COMPLETED",+ detail=f"tool={original_name};success={success};late=True;duration_ms={elapsed_ms}",+ )+async def _handle_end_call(self, event: Any) -> None:if self._session is not None and self._session_takes_tool_results():try:diff --git a/tests/unit/realtime/test_native_tool_deadline.py b/tests/unit/realtime/test_native_tool_deadline.pynew file mode 100644index 0000000000..7b11548d0b--- /dev/null+++ b/tests/unit/realtime/test_native_tool_deadline.py@@ -0,0 +1,204 @@+"""A native tool call can never hold the live voice past its deadline.++Live 2026-08-22 20:01:52 (gemini-live): ``youtube_music`` sat 199 s on a+stuck background-player host. The instant ack spoke at 3 s, then the call+stayed mute until 20:05:12 because a native call blocks the live model until+its result arrives (ADR-0035 §3) and nothing bounded that wait. Pinned here:++* past ``_NATIVE_TOOL_DEADLINE_S`` the model receives an honest ``pending``+ result and is released — the tool itself is NOT cancelled, it runs to+ completion in the background;+* the late outcome is booked (log, failure counter, latency record) but never+ enters the per-turn evidence (``_executed_tool_names`` /+ ``_direct_tool_results``), which a later turn reads as its own;+* a tool that answers within the deadline is untouched — same result, no+ pending flag, counted as executed.+"""+from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.realtime import session as session_module+from jarvis.realtime.session import RealtimeVoiceSession++RATE = 24_000+++class _Wire:+ session_id = "deadline-wire"+ supports_tool_updates = True+ creates_responses_automatically = True+ isolates_response_generations = True++ def __init__(self) -> None:+ self.tool_results: list[tuple[str, str, dict[str, Any]]] = []++ async def send_tool_result(self, call_id: str, name: str, payload: dict[str, Any]) -> None:+ self.tool_results.append((call_id, name, payload))++ async def send_json(self, *_args: Any) -> None:+ return None+++class _Provider:+ name = "deadline-provider"+ supports_realtime = True+ supports_direct_tools = True+ input_sample_rate = RATE+ output_sample_rate = RATE++ async def can_open_duplex_session(self) -> bool:+ return True++ async def open_session(self, _config: Any) -> _Wire:+ return _Wire()+++class _SlowBridge:+ """A bridge whose tool takes ``delay_s`` and then reports ``result``."""++ declarations: tuple[dict[str, Any], ...] = ()++ def __init__(self, delay_s: float, result: dict[str, Any] | None = None) -> None:+ self.delay_s = delay_s+ self.result = result or {"success": True, "output": "played", "error": None}+ self.calls: list[tuple[str, dict[str, Any]]] = []+ self.finished = asyncio.Event()++ def set_language(self, _language: str) -> None:+ return None++ async def handle_user_transcript(self, _text: str) -> None:+ return None++ async def execute(+ self, *, wire_name: str, arguments: dict[str, Any]+ ) -> tuple[str, dict[str, Any]]:+ self.calls.append((wire_name, arguments))+ await asyncio.sleep(self.delay_s)+ self.finished.set()+ return wire_name, dict(self.result)++ async def close(self) -> None:+ return None+++def _config() -> SimpleNamespace:+ return SimpleNamespace(+ brain=SimpleNamespace(reply_language="en", providers={}),+ stt=SimpleNamespace(language="auto"),+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="hybrid"),+ latency=SimpleNamespace(enabled=False),+ )+++def _session(bridge: _SlowBridge) -> tuple[RealtimeVoiceSession, _Wire]:+ session = RealtimeVoiceSession(+ session_id="native-tool-deadline",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ providers=[_Provider()],+ config=_config(),+ bus=None,+ surface="desktop",+ half_duplex=True,+ browser_sample_rate=RATE,+ tool_bridge=bridge,+ brain=SimpleNamespace(conversation_language="en"),+ )+ wire = _Wire()+ session._session = wire+ session._language = "en"+ session._turn_id = "turn-1"+ session._last_user_text = "play some music"+ return session, wire+++def _event(name: str = "youtube_music") -> SimpleNamespace:+ return SimpleNamespace(call_id="call-1", tool_name=name, tool_args={"action": "play"})+++async def test_a_tool_past_the_deadline_releases_the_model_with_a_pending_result(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(session_module, "_NATIVE_TOOL_DEADLINE_S", 0.2)+ monkeypatch.setattr(session_module, "_INSTANT_ACK_GRACE_S", 60.0)+ bridge = _SlowBridge(delay_s=0.6)+ session, wire = _session(bridge)++ started = asyncio.get_running_loop().time()+ await session._handle_tool_call(_event())+ elapsed = asyncio.get_running_loop().time() - started++ assert elapsed < 0.5, f"the model waited {elapsed:.2f}s — the deadline did not release it"+ assert len(wire.tool_results) == 1+ _call_id, name, payload = wire.tool_results[0]+ assert name == "youtube_music"+ assert payload["success"] is False+ assert payload["pending"] is True+ assert "still running" in payload["error"]+ # Released, not counted as a failure or a denial — and not as executed+ # either: nothing has happened yet.+ assert session._native_tool_failures == 0+ assert session._native_tool_denied == 0+ assert "youtube_music" not in session._executed_tool_names+ assert not bridge.finished.is_set(), "the tool must keep running, not be cancelled"++ # The tool runs to completion in the background and books its late outcome+ # without touching the per-turn evidence.+ await asyncio.wait_for(bridge.finished.wait(), timeout=2.0)+ await asyncio.sleep(0) # let the done-callback run+ assert session._native_tool_failures == 0+ assert "youtube_music" not in session._executed_tool_names+ assert session._direct_tool_results == []+++async def test_a_late_failure_is_counted_once_it_arrives(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(session_module, "_NATIVE_TOOL_DEADLINE_S", 0.2)+ monkeypatch.setattr(session_module, "_INSTANT_ACK_GRACE_S", 60.0)+ bridge = _SlowBridge(+ delay_s=0.5, result={"success": False, "output": None, "error": "player gone"}+ )+ session, wire = _session(bridge)++ await session._handle_tool_call(_event())+ assert wire.tool_results[0][2]["pending"] is True+ assert session._native_tool_failures == 0++ await asyncio.wait_for(bridge.finished.wait(), timeout=2.0)+ await asyncio.sleep(0)+ assert session._native_tool_failures == 1+++async def test_a_tool_within_the_deadline_is_untouched(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(session_module, "_NATIVE_TOOL_DEADLINE_S", 2.0)+ monkeypatch.setattr(session_module, "_INSTANT_ACK_GRACE_S", 60.0)+ bridge = _SlowBridge(delay_s=0.05)+ session, wire = _session(bridge)++ await session._handle_tool_call(_event())++ assert len(wire.tool_results) == 1+ payload = wire.tool_results[0][2]+ assert payload == {"success": True, "output": "played", "error": None}+ assert "pending" not in payload+ assert "youtube_music" in session._executed_tool_names+ assert session._direct_tool_results == [("youtube_music", payload)]+ assert session._native_tool_failures == 0+++def test_the_deadline_leaves_room_for_the_slowest_honest_tool() -> None:+ """YouTube Music's cold-start confirm is ~9 s by design plus a window show;+ the ceiling must sit above it, and well below the turn-stall watchdog."""+ assert 12.0 <= session_module._NATIVE_TOOL_DEADLINE_S < session_module._TURN_STALL_TIMEOUT_S