Skip to content

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.

fix(live): make native live calls safe for the local voice engine

rubenluetke10-beepb383f743f179
diff --git a/jarvis/live/native.py b/jarvis/live/native.py
index 7acf2099c1..b04cffcf4b 100644
--- a/jarvis/live/native.py
+++ b/jarvis/live/native.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import base64
+import json
import logging
import time
from dataclasses import replace
@@ -13,16 +14,92 @@ from uuid import uuid4
from jarvis.core.paths import user_data_dir
from jarvis.core.runtime_refs import get_supervisor_tool_gateway
+from jarvis.core.tool_budget import VOICE_TOOL_BUDGET_S
from jarvis.live.product import PRODUCT_BRIEF
from jarvis.live.runtime import claim, register, unregister
from jarvis.live.session import LiveVoiceSession
from jarvis.live.state import LiveLedger, TranscriptFragment
from jarvis.live.tools import LiveTools, take_images
from jarvis.realtime.audio import StreamingPcm16Resampler
-from jarvis.realtime.protocol import RealtimeSessionConfig
+from jarvis.realtime.protocol import RealtimeSessionConfig, RealtimeUnavailableError
log = logging.getLogger(__name__)
+# How long a provider's readiness probe may take before the call is refused
+# (release SLO: an honest refusal within one second, spoken and visible).
+_DUPLEX_PROBE_BUDGET_S = 1.0
+# Spoken only when the provider gives no reason of its own (or its probe hangs).
+_DUPLEX_REFUSAL_FALLBACK = "The selected voice engine cannot take a call right now."
+# Ceiling for ONE native tool call before the live model is released with an
+# honest "still running" result; the tool itself keeps running. Ported from
+# ``_NATIVE_TOOL_DEADLINE_S`` in ``jarvis/realtime/session.py``. A module
+# attribute so tests can pin it low.
+_TOOL_DEADLINE_S = VOICE_TOOL_BUDGET_S
+# Session built-ins of ``LiveTools``: always declared, whatever the budget.
+_SESSION_TOOLS = frozenset({"end_call", "discover_tools", "call_tool", "confirm_action"})
+# Under a declaration budget (a provider's ``tool_declaration_budget_tokens``
+# or ``[voice].realtime_tool_declaration_budget_tokens``, the smaller wins), at
+# most this many catalog tools are declared directly; every other tool stays
+# reachable through discover_tools/call_tool. A small local model pays a full
+# LLM round per discovery step, so the frequent tools come first.
+_DIRECT_TOOL_LIMIT = 12
+_DIRECT_TOOL_PREFERENCE = (
+ "workspace-orchestrate",
+ "find-app-action",
+ "run-app-action",
+ "search_web",
+ "open_app",
+ "take_appshot",
+ "screen_snapshot",
+ "google_calendar",
+ "gmail",
+ "youtube_music",
+ "spotify",
+ "home_assistant",
+ "wiki-recall",
+ "product_help",
+)
+
+
+def _declared_name(declaration: dict) -> str:
+ """The canonical tool name behind a declaration (catalog tools are aliased)."""
+ name = str(declaration.get("name", ""))
+ if name in _SESSION_TOOLS:
+ return name
+ return str(declaration.get("description", "")).split(": ", 1)[0]
+
+
+def _fit_declarations(declarations: list[dict], budget_chars: int) -> tuple[dict, ...]:
+ """Session built-ins plus a curated direct set that fits ``budget_chars``."""
+ session = [d for d in declarations if d.get("name") in _SESSION_TOOLS]
+ rank = {name: index for index, name in enumerate(_DIRECT_TOOL_PREFERENCE)}
+ catalog = sorted(
+ (d for d in declarations if d.get("name") not in _SESSION_TOOLS),
+ key=lambda d: rank.get(_declared_name(d), len(rank)),
+ )
+ used = sum(len(json.dumps(d)) for d in session)
+ direct: list[dict] = []
+ for declaration in catalog:
+ if len(direct) >= _DIRECT_TOOL_LIMIT:
+ break
+ size = len(json.dumps(declaration))
+ if used + size > budget_chars:
+ continue
+ used += size
+ direct.append(declaration)
+ return (*session, *direct)
+
+
+def _log_late_probe(task: asyncio.Future) -> None:
+ """Retrieve a readiness probe that outlived its refusal, so nothing is lost."""
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ log.warning("Native voice readiness probe failed after the refusal: %s", exc)
+ else:
+ log.info("Native voice readiness probe answered late: %s", task.result())
+
class NativeLiveVoiceSession(LiveVoiceSession):
"""Reuse native turn mechanics, without the legacy heuristic delegate loop."""
@@ -42,8 +119,11 @@ class NativeLiveVoiceSession(LiveVoiceSession):
claim(self.session_id)
self._initial_seed = self._take_initial_context()
settings = getattr(self._config.brain, "providers", {}).get(self.active_provider)
- tier = self._config.brain.realtime
- model = getattr(tier, "model", "") or getattr(settings, "model", "") or ""
+ # The active provider's own model only. ``[brain.realtime].model``
+ # belongs to whichever card last wrote it (the OpenAI Live card)
+ # and survives a provider switch, so Gemini or the local engine
+ # was handed another provider's model id. Empty = adapter default.
+ model = getattr(settings, "model", "") or ""
self._active_model = model
language_rule = (
"Use the user's language and follow explicit language changes. "
@@ -78,12 +158,10 @@ class NativeLiveVoiceSession(LiveVoiceSession):
history=tuple(
{"role": item["role"], "text": item["delta"]} for item in self._initial_seed
),
- tools=tuple(
- {key: value for key, value in declaration.items() if key != "type"}
- for declaration in self._tools.declarations()
- ),
+ tools=self._tool_declarations(),
)
self._native_config = cfg
+ await self._refuse_unless_duplex_ready()
from jarvis.live.recovery import connection_permit
await connection_permit()
@@ -140,6 +218,102 @@ class NativeLiveVoiceSession(LiveVoiceSession):
await self.end(reason="error")
raise
+ def _declaration_budget_tokens(self) -> int:
+ """The smaller of the config bound and the provider's own budget; 0 = none.
+
+ Same rule as ``RealtimeVoiceSession._declaration_budget_chars``: the
+ provider's budget is a capability (AP-21), never a name check.
+ """
+ configured = int(
+ getattr(
+ getattr(self._config, "voice", None),
+ "realtime_tool_declaration_budget_tokens",
+ 0,
+ )
+ or 0
+ )
+ declared = int(getattr(self._provider, "tool_declaration_budget_tokens", 0) or 0)
+ budgets = [budget for budget in (configured, declared) if budget > 0]
+ return min(budgets) if budgets else 0
+
+ def _tool_declarations(self) -> tuple[dict, ...]:
+ assert self._tools is not None
+ declarations = [
+ {key: value for key, value in declaration.items() if key != "type"}
+ for declaration in self._tools.declarations()
+ ]
+ budget = self._declaration_budget_tokens()
+ if budget <= 0:
+ return tuple(declarations)
+ fitted = _fit_declarations(declarations, budget * 4)
+ # AP-30: a trimmed tool set looks exactly like a complete one.
+ log.info(
+ "Native voice declares %d of %d tools under a %d-token budget for %s; "
+ "the rest stay reachable through discover_tools",
+ len(fitted),
+ len(declarations),
+ budget,
+ self.active_provider,
+ )
+ return fitted
+
+ async def _refuse_unless_duplex_ready(self) -> None:
+ """Refuse within a second, in the provider's own words, when it cannot talk.
+
+ A provider without the probe is assumed ready. A probe that outlives
+ the budget keeps running in the background: it may be starting an
+ engine, which must not be torn in half.
+ """
+ probe = getattr(self._provider, "can_open_duplex_session", None)
+ if not callable(probe):
+ return
+ check = asyncio.ensure_future(probe())
+ try:
+ ready = bool(await asyncio.wait_for(asyncio.shield(check), _DUPLEX_PROBE_BUDGET_S))
+ except TimeoutError:
+ check.add_done_callback(_log_late_probe)
+ ready = False
+ except Exception:
+ log.warning("Native voice readiness probe failed", exc_info=True)
+ ready = False
+ if ready:
+ return
+ reason = (
+ str(getattr(self._provider, "duplex_unavailable_reason", "") or "").strip()
+ or _DUPLEX_REFUSAL_FALLBACK
+ )
+ self._detail = reason
+ log.warning("Native voice refused to start (%s): %s", self.active_provider, reason)
+ try:
+ await self._send_json(
+ {
+ "type": "error_spoken",
+ "text": reason,
+ "detail": reason,
+ "language": self._language,
+ "spoken_kind": "reply",
+ "provider": self.active_provider,
+ }
+ )
+ except Exception: # noqa: BLE001 — the refusal still propagates
+ log.warning("Native voice refusal notice could not be sent", exc_info=True)
+ raise RealtimeUnavailableError(reason)
+
+ async def _interrupt_reply(self) -> None:
+ """Barge-in: stop the provider's reply and flush what the browser holds."""
+ interrupt = getattr(self._connection, "interrupt", None)
+ if callable(interrupt):
+ try:
+ await interrupt()
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ log.warning(
+ "Native voice interrupt failed; flushing playback anyway", exc_info=True
+ )
+ self.playback_active = False
+ await self._emit_indicator({"type": "audio_clear"})
+
async def handle_audio_frame(self, pcm: bytes) -> None:
if (
self._connection is not None
@@ -184,7 +358,20 @@ class NativeLiveVoiceSession(LiveVoiceSession):
}
)
- async def _request_native_response(self) -> None:
+ async def _request_native_response(self, language: str = "") -> None:
+ # The turn's language is decided once (``turn_language``); a provider
+ # that can take it per session hears it before it answers.
+ update = getattr(self._connection, "update_session", None)
+ if language and callable(update):
+ try:
+ await update(language=language)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ if not self._closing:
+ log.warning(
+ "Native voice language update failed; answering anyway", exc_info=True
+ )
try:
await self._connection.request_response()
except asyncio.CancelledError:
@@ -258,7 +445,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):
)
self._tools.language = self._language
if not getattr(self._connection, "creates_responses_automatically", True):
- task = asyncio.create_task(self._request_native_response())
+ task = asyncio.create_task(self._request_native_response(self._language))
self._control_tasks.add(task)
task.add_done_callback(self._control_tasks.discard)
if role == "assistant" or event.is_final:
@@ -298,8 +485,11 @@ class NativeLiveVoiceSession(LiveVoiceSession):
self._jobs.add(task)
task.add_done_callback(self._jobs.discard)
elif event.type in {"interrupted", "speech_started"}:
+ barge_in = event.type == "speech_started" and (self._speaking or self.playback_active)
self._speaking = False
self._thinking = False
+ if barge_in:
+ await self._interrupt_reply()
await self._emit_indicator({"type": "tts_cancel"})
elif event.type == "turn_complete":
self._transcript.finish("assistant")
@@ -343,12 +533,23 @@ class NativeLiveVoiceSession(LiveVoiceSession):
async def _call(self, event: Any, revision: int) -> None:
assert self._tools is not None
try:
- result = await self._tools.execute(
- f"{self._wire_epoch}:{event.call_id or uuid4()}",
- event.tool_name,
- event.tool_args or {},
- revision,
+ work = asyncio.ensure_future(
+ self._tools.execute(
+ f"{self._wire_epoch}:{event.call_id or uuid4()}",
+ event.tool_name,
+ event.tool_args or {},
+ revision,
+ )
)
+ try:
+ # ``shield``: the deadline releases the LIVE MODEL, never the
+ # tool; an action mid-flight finishes and keeps its receipt.
+ result = await asyncio.wait_for(asyncio.shield(work), _TOOL_DEADLINE_S)
+ except asyncio.CancelledError:
+ work.cancel() # cancelling the call still cancels its tool, as before
+ raise
+ except TimeoutError:
+ result = self._release_slow_tool(work, str(event.tool_name or ""))
images = take_images(result)
if self._closing:
return
@@ -369,6 +570,46 @@ class NativeLiveVoiceSession(LiveVoiceSession):
except Exception:
log.exception("Native tool call failed; receipt retained")
+ def _release_slow_tool(self, work: asyncio.Future, name: str) -> dict:
+ """Answer the model honestly while the tool runs on in the background."""
+ started = time.monotonic()
+ log.warning(
+ "Native tool %s still running after %.0fs; releasing the live model with a "
+ "pending result, the tool finishes in the background",
+ name,
+ _TOOL_DEADLINE_S,
+ )
+ # Kept in ``_jobs``: a call that ends now still waits for its receipt.
+ self._jobs.add(work)
+ work.add_done_callback(self._jobs.discard)
+
+ def _late(done: asyncio.Future) -> None:
+ waited_ms = round((time.monotonic() - started) * 1000)
+ if done.cancelled():
+ log.info("Late native tool %s was cancelled", name)
+ elif done.exception() is not None:
+ log.warning("Late native tool %s failed: %s", name, done.exception())
+ else:
+ outcome = done.result()
+ log.info(
+ "Late native tool %s finished %d ms after its release (success=%s)",
+ name,
+ waited_ms,
+ bool(isinstance(outcome, dict) and outcome.get("success")),
+ )
+
+ work.add_done_callback(_late)
+ return {
+ "success": False,
+ "pending": True,
+ "error": (
+ f"This tool is still running after {_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."
+ ),
+ }
+
async def handle_control(self, message: dict) -> None:
if self._closing:
return
diff --git a/jarvis/plugins/realtime/local_voice.py b/jarvis/plugins/realtime/local_voice.py
index 76c58c602e..47d1ceacdb 100644
--- a/jarvis/plugins/realtime/local_voice.py
+++ b/jarvis/plugins/realtime/local_voice.py
@@ -382,6 +382,9 @@ class LocalVoiceProvider:
input_sample_rate = _INPUT_RATE
output_sample_rate = _OUTPUT_RATE
handshake_budget_s = 5.0
+ # Plan 4.6: a small local model gets a curated direct tool set within ~2K
+ # tokens; everything else goes through discover_tools/call_tool.
+ tool_declaration_budget_tokens = 2_000
_engine: ClassVar[_Engine | None] = None
diff --git a/tests/fakes/fake_native_voice.py b/tests/fakes/fake_native_voice.py
new file mode 100644
index 0000000000..73bcc5f180
--- /dev/null
+++ b/tests/fakes/fake_native_voice.py
@@ -0,0 +1,219 @@
+"""In-memory providers for ``NativeLiveVoiceSession`` (Gemini Live and the local engine).
+
+Two shapes share one file because ``jarvis/live/native.py`` serves both, and
+every fix there needs a regression test on each:
+
+* :func:`gemini_like_provider` creates its responses itself at the end of the
+ user's turn (``creates_responses_automatically=True``), declares no tool
+ budget and no refusal sentence of its own, like ``GeminiLiveProvider``.
+* :func:`local_voice_like_provider` waits for ``request_response``, declares a
+ 2K-token tool budget and explains a refusal in ``duplex_unavailable_reason``,
+ like ``LocalVoiceProvider``.
+
+No network, audio device, model or worker process is involved.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from jarvis.core.protocols import SupervisorToolDescriptor, ToolResult
+
+
+class FakeNativeConnection:
+ """One scripted native session; every call the session makes is recorded in order."""
+
+ def __init__(self, *, creates_responses_automatically: bool, model: str = "") -> None:
+ self.creates_responses_automatically = creates_responses_automatically
+ self.isolates_response_generations = True
+ self.supports_tool_results = True
+ self.model = model
+ self.calls: list[tuple[str, Any]] = []
+ self.tool_results: list[tuple[str, str, dict[str, Any]]] = []
+ self.tool_result_sent = asyncio.Event()
+ self.closed = False
+ self._events: asyncio.Queue[Any] = asyncio.Queue()
+
+ def push(self, event: Any) -> None:
+ self._events.put_nowait(event)
+
+ def names(self) -> list[str]:
+ return [name for name, _ in self.calls]
+
+ async def receive(self):
+ while True:
+ event = await self._events.get()
+ if event is None:
+ return
+ yield event
+
+ async def send_audio(self, chunk: Any) -> None:
+ self.calls.append(("send_audio", chunk))
+
+ async def send_text(self, text: str) -> None:
+ self.calls.append(("send_text", text))
+
+ async def update_session(self, **changes: Any) -> None:
+ self.calls.append(("update_session", changes))
+
+ async def request_response(self, *, required_tool: str | None = None) -> None:
+ self.calls.append(("request_response", required_tool))
+
+ async def interrupt(self, **kwargs: Any) -> None:
+ self.calls.append(("interrupt", kwargs))
+
+ async def truncate(self, audio_end_ms: int) -> None:
+ self.calls.append(("truncate", audio_end_ms))
+
+ async def send_tool_result(self, call_id: str, name: str, result: dict[str, Any]) -> None:
+ self.calls.append(("send_tool_result", call_id))
+ self.tool_results.append((call_id, name, result))
+ self.tool_result_sent.set()
+
+ async def close(self) -> None:
+ if not self.closed:
+ self.closed = True
+ self._events.put_nowait(None)
+
+
+class FakeNativeProvider:
+ """A native-tool provider that records the session config it was opened with."""
+
+ supports_realtime = True
+ native_tool_orchestration = True
+ browser_audio = True
+ credential_candidates: tuple[tuple[str, str | None], ...] = ()
+
+ def __init__(
+ self,
+ name: str,
+ *,
+ creates_responses_automatically: bool,
+ input_sample_rate: int,
+ output_sample_rate: int = 24_000,
+ ready: bool = True,
+ refusal_reason: str | None = None,
+ probe_delay_s: float = 0.0,
+ tool_declaration_budget_tokens: int = 0,
+ ) -> None:
+ self.name = name
+ self.input_sample_rate = input_sample_rate
+ self.output_sample_rate = output_sample_rate
+ self.tool_declaration_budget_tokens = tool_declaration_budget_tokens
+ self._creates = creates_responses_automatically
+ self._ready = ready
+ self._refusal_reason = refusal_reason
+ self._probe_delay_s = probe_delay_s
+ self.probes = 0
+ self.opened_with: list[Any] = []
+ self.connection: FakeNativeConnection | None = None
+ if refusal_reason is not None:
+ self.duplex_unavailable_reason = ""
+
+ async def can_open_duplex_session(self) -> bool:
+ self.probes += 1
+ if self._probe_delay_s:
+ await asyncio.sleep(self._probe_delay_s)
+ if self._refusal_reason is not None:
+ self.duplex_unavailable_reason = "" if self._ready else self._refusal_reason
+ return self._ready
+
+ async def open_session(self, cfg: Any) -> FakeNativeConnection:
+ self.opened_with.append(cfg)
+ self.connection = FakeNativeConnection(
+ creates_responses_automatically=self._creates, model=str(cfg.model or "")
+ )
+ return self.connection
+
+
+def gemini_like_provider(**overrides: Any) -> FakeNativeProvider:
+ options: dict[str, Any] = {
+ "creates_responses_automatically": True,
+ "input_sample_rate": 16_000,
+ }
+ options.update(overrides)
+ return FakeNativeProvider("gemini-live", **options)
+
+
+def local_voice_like_provider(**overrides: Any) -> FakeNativeProvider:
+ options: dict[str, Any] = {
+ "creates_responses_automatically": False,
+ "input_sample_rate": 16_000,
+ "refusal_reason": "The local voice is still loading (stt, 40 %).",
+ "tool_declaration_budget_tokens": 2_000,
+ }
+ options.update(overrides)
+ return FakeNativeProvider("local-voice", **options)
+
+
+class FakeToolGateway:
+ """Supervisor tool gateway with a configurable catalog and blockable tools."""
+
+ def __init__(self, descriptors: tuple[SupervisorToolDescriptor, ...] = ()) -> None:
+ self._descriptors = descriptors or (
+ SupervisorToolDescriptor(
+ "search_web",
+ "Search the web.",
+ {"type": "object", "properties": {"query": {"type": "string"}}},
+ "safe",
+ ),
+ )
+ self.gates: dict[str, asyncio.Event] = {}
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+ self.finished: list[str] = []
+
+ def catalog(self) -> tuple[SupervisorToolDescriptor, ...]:
+ return self._descriptors
+
+ def hold(self, name: str) -> asyncio.Event:
+ """Block ``name`` until the returned event is set."""
+ self.gates[name] = asyncio.Event()
+ return self.gates[name]
+
+ async def execute(self, name: str, arguments: dict[str, Any], request: Any) -> ToolResult:
+ del request
+ self.calls.append((name, arguments))
+ gate = self.gates.get(name)
+ if gate is not None:
+ await gate.wait()
+ self.finished.append(name)
+ return ToolResult(True, {"verified": True})
+
+ async def execute_confirmed(self, trace: Any, request: Any) -> ToolResult:
+ del trace, request
+ return ToolResult(True, {"verified": True})
+
+ async def cancel_pending(self, trace: Any, *, reason: str = "voice_vetoed") -> bool:
+ del trace, reason
+ return True
+
+
+def catalog_of(count: int, *, schema_padding: int = 200) -> tuple[SupervisorToolDescriptor, ...]:
+ """``count`` generic tools plus the curated names, each with a sizable schema."""
+ names = [
+ "search_web",
+ "workspace-orchestrate",
+ "youtube_music",
+ "google_calendar",
+ *(f"tool-{index:02d}" for index in range(count)),
+ ]
+ return tuple(
+ SupervisorToolDescriptor(
+ name,
+ f"Does {name}. " + "x" * schema_padding,
+ {"type": "object", "properties": {"value": {"type": "string"}}},
+ "safe",
+ )
+ for name in names
+ )
+
+
+__all__ = [
+ "FakeNativeConnection",
+ "FakeNativeProvider",
+ "FakeToolGateway",
+ "catalog_of",
+ "gemini_like_provider",
+ "local_voice_like_provider",
+]
diff --git a/tests/unit/live/test_native_live_fixes.py b/tests/unit/live/test_native_live_fixes.py
new file mode 100644
index 0000000000..9ecb2f7b5d
--- /dev/null
+++ b/tests/unit/live/test_native_live_fixes.py
@@ -0,0 +1,382 @@
+"""Plan 4.4 fixes in ``jarvis/live/native.py``, each on Gemini- and local-voice-like wires.
+
+``NativeLiveVoiceSession`` serves Gemini Live and the Jarvis-owned local voice
+engine, so every behaviour here is pinned on both connection shapes from
+``tests/fakes/fake_native_voice.py``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.live import native, runtime
+from jarvis.live.native import NativeLiveVoiceSession
+from jarvis.live.state import LiveLedger
+from jarvis.live.tools import LiveTools
+from jarvis.realtime.protocol import RealtimeEvent, RealtimeUnavailableError
+from tests.fakes.fake_native_voice import (
+ FakeNativeConnection,
+ FakeToolGateway,
+ catalog_of,
+ gemini_like_provider,
+ local_voice_like_provider,
+)
+
+PROVIDERS = {
+ "gemini-like": gemini_like_provider,
+ "local-voice-like": local_voice_like_provider,
+}
+both_providers = pytest.mark.parametrize("make_provider", PROVIDERS.values(), ids=PROVIDERS)
+_LOCAL_REASON = "The local voice is still loading (stt, 40 %)."
+
+
+def _config(*, providers=None, realtime=None, budget=0, reply_language="auto"):
+ return SimpleNamespace(
+ brain=SimpleNamespace(
+ reply_language=reply_language,
+ providers=providers or {},
+ realtime=realtime,
+ ),
+ voice=SimpleNamespace(realtime_tool_declaration_budget_tokens=budget),
+ )
+
+
+class _Call:
+ """A session driven through the real ``_start`` with fake provider and tools."""
+
+ def __init__(self, provider, config, gateway):
+ self.provider = provider
+ self.frames: list[dict] = []
+
+ async def send_json(frame):
+ self.frames.append(frame)
+
+ async def send_binary(_data):
+ return None
+
+ self.session = NativeLiveVoiceSession(
+ session_id="native-test",
+ send_json=send_json,
+ send_binary=send_binary,
+ providers=[provider],
+ config=config,
+ )
+
+ async def start(self) -> None:
+ await self.session.handle_control({"type": "audio_start", "sample_rate": 48000})
+
+ def sent(self, kind: str) -> list[dict]:
+ return [frame for frame in self.frames if frame.get("type") == kind]
+
+
+def call(monkeypatch, tmp_path):
+ monkeypatch.setattr(runtime, "_active", {})
+ monkeypatch.setattr(runtime, "_opening", set())
+ monkeypatch.setattr(native, "user_data_dir", lambda: tmp_path)
+
+ def _build(provider, config=None, gateway=None):
+ gateway = gateway or FakeToolGateway()
+ monkeypatch.setattr(native, "get_supervisor_tool_gateway", lambda: gateway)
+ return _Call(provider, config or _config(), gateway)
+
+ return _build
+
+
+def _in_call(provider, tmp_path, *, gateway=None):
+ """A session already in a call: connection, ledger and tools in place."""
+ frames: list[dict] = []
+
+ async def send_json(frame):
+ frames.append(frame)
+
+ async def send_binary(_data):
+ return None
+
+ session = NativeLiveVoiceSession(
+ session_id="native-live",
+ send_json=send_json,
+ send_binary=send_binary,
+ providers=[provider],
+ config=_config(),
+ )
+ connection = FakeNativeConnection(creates_responses_automatically=provider._creates, model="m")
+ ledger = LiveLedger(tmp_path / f"{provider.name}.sqlite3")
+ session._connection = connection
+ session._ledger = ledger
+ session._tools = LiveTools(
+ gateway or FakeToolGateway(), ledger, "native-live", language="en", backend_model=""
+ )
+ return session, connection, frames
+
+
+async def _settle(session) -> None:
+ """Let the response/language tasks the session spawned run to completion."""
+ for _ in range(5):
+ await asyncio.sleep(0)
+ await asyncio.gather(*session._control_tasks, return_exceptions=True)
+
+
+# 1. Readiness probe before open_session ---------------------------------------
+
+
+@both_providers
+async def test_not_ready_provider_is_refused_in_its_own_words(call, make_provider):
+ live = call(make_provider(ready=False))
+ began = time.monotonic()
+ with pytest.raises(RealtimeUnavailableError) as refused:
+ await live.start()
+ assert time.monotonic() - began < 1.0
+ assert live.provider.opened_with == [] # nothing opened, nothing billed
+ expected = (
+ _LOCAL_REASON if live.provider.name == "local-voice" else native._DUPLEX_REFUSAL_FALLBACK
+ )
+ assert str(refused.value) == expected
+ assert live.session.failure_detail == expected
+ spoken = live.sent("error_spoken")
+ assert [frame["text"] for frame in spoken] == [expected]
+ assert spoken[0]["provider"] == live.provider.name
+ assert live.sent("audio_ready") == []
+
+
+@both_providers
+async def test_slow_readiness_probe_is_refused_within_a_second(call, make_provider):
+ live = call(make_provider(probe_delay_s=3.0))
+ began = time.monotonic()
+ with pytest.raises(RealtimeUnavailableError):
+ await live.start()
+ assert time.monotonic() - began < 1.5
+ assert live.provider.opened_with == []
+ assert len(live.sent("error_spoken")) == 1
+
+
+@both_providers
+async def test_ready_provider_opens_after_one_probe(call, make_provider):
+ live = call(make_provider())
+ await live.start()
+ try:
+ assert live.provider.probes == 1
+ assert len(live.provider.opened_with) == 1
+ assert live.sent("error_spoken") == []
+ assert len(live.sent("audio_ready")) == 1
+ finally:
+ await live.session.end()
+
+
+# 2. The active provider's own model --------------------------------------------
+
+
+@both_providers
+async def test_model_comes_from_the_active_provider_never_the_realtime_tier(call, make_provider):
+ provider = make_provider()
+ # The OpenAI Live card wrote [brain.realtime]; a switch kept its model.
+ tier = SimpleNamespace(provider=provider.name, model="gpt-realtime")
+ own = SimpleNamespace(model="own-model", voice="")
+ live = call(provider, _config(providers={provider.name: own}, realtime=tier))
+ await live.start()
+ try:
+ assert provider.opened_with[0].model == "own-model"
+ assert live.sent("audio_ready")[0]["model"] == "own-model"
+ finally:
+ await live.session.end()
+
+
+@both_providers
+async def test_no_own_model_means_the_adapter_default_not_another_providers(call, make_provider):
+ provider = make_provider()
+ tier = SimpleNamespace(provider="openai-live", model="gpt-realtime")
+ live = call(provider, _config(realtime=tier))
+ await live.start()
+ try:
+ assert provider.opened_with[0].model == ""
+ finally:
+ await live.session.end()
+
+
+# 3. Barge-in -------------------------------------------------------------------
+
+
+@both_providers
+async def test_speech_while_jarvis_speaks_interrupts_and_flushes_playback(tmp_path, make_provider):
+ session, connection, frames = _in_call(make_provider(), tmp_path)
+ try:
+ session._speaking = True
+ await session._native_event(RealtimeEvent(type="speech_started"))
+ assert connection.names() == ["interrupt"]
+ kinds = [frame["type"] for frame in frames]
+ assert "audio_clear" in kinds and "tts_cancel" in kinds
+ assert kinds.index("audio_clear") < kinds.index("tts_cancel")
+ assert not session._speaking and not session.playback_active
+ finally:
+ session._ledger.close()
+
+
+@both_providers
+async def test_browser_still_playing_counts_as_speaking(tmp_path, make_provider):
+ session, connection, frames = _in_call(make_provider(), tmp_path)
+ try:
+ session.playback_active = True # model finished, browser still plays
+ await session._native_event(RealtimeEvent(type="speech_started"))
+ assert connection.names() == ["interrupt"]
+ assert any(frame["type"] == "audio_clear" for frame in frames)
+ finally:
+ session._ledger.close()
+
+
+@both_providers
+async def test_speech_while_silent_does_not_interrupt(tmp_path, make_provider):
+ session, connection, frames = _in_call(make_provider(), tmp_path)
+ try:
+ await session._native_event(RealtimeEvent(type="speech_started"))
+ await session._native_event(RealtimeEvent(type="interrupted"))
+ assert "interrupt" not in connection.names()
+ assert all(frame["type"] != "audio_clear" for frame in frames)
+ finally:
+ session._ledger.close()
+
+
+# 4. Tool deadline ----------------------------------------------------------------
+
+
+@both_providers
+async def test_slow_tool_releases_the_model_with_an_honest_pending_result(
+ tmp_path, monkeypatch, make_provider
+):
+ monkeypatch.setattr(native, "_TOOL_DEADLINE_S", 0.05)
+ gateway = FakeToolGateway()
+ release = gateway.hold("search_web")
+ session, connection, _frames = _in_call(make_provider(), tmp_path, gateway=gateway)
+ try:
+ await session._native_event(
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c1",
+ tool_name="call_tool",
+ tool_args={"name": "search_web", "arguments_json": "{}"},
+ )
+ )
+ await asyncio.wait_for(connection.tool_result_sent.wait(), 1.0)
+ _, _, result = connection.tool_results[0]
+ assert result["pending"] is True and result["success"] is False
+ assert "still running" in result["error"]
+ assert gateway.finished == [] # the tool itself was not cancelled
+ assert session._has_pending_work() # its receipt is still owed
+ release.set()
+ for _ in range(50):
+ if not session._has_pending_work():
+ break
+ await asyncio.sleep(0.01)
+ assert gateway.finished == ["search_web"]
+ assert not session._has_pending_work()
+ assert len(connection.tool_results) == 1 # the late result is not re-sent
+ finally:
+ session._ledger.close()
+
+
+@both_providers
+async def test_fast_tool_answers_with_its_real_result(tmp_path, make_provider):
+ session, connection, _frames = _in_call(make_provider(), tmp_path)
+ try:
+ await session._native_event(
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c1",
+ tool_name="call_tool",
+ tool_args={"name": "search_web", "arguments_json": "{}"},
+ )
+ )
+ await asyncio.wait_for(connection.tool_result_sent.wait(), 1.0)
+ _, _, result = connection.tool_results[0]
+ assert result["success"] is True and "pending" not in result
+ finally:
+ session._ledger.close()
+
+
+# 5. Declaration budget -------------------------------------------------------------
+
+
+@both_providers
+async def test_declarations_respect_the_providers_budget(call, make_provider):
+ provider = make_provider()
+ gateway = FakeToolGateway(catalog_of(30))
+ live = call(provider, gateway=gateway)
+ await live.start()
+ try:
+ tools = provider.opened_with[0].tools
+ names = [tool["name"] for tool in tools]
+ for builtin in ("end_call", "discover_tools", "call_tool", "confirm_action"):
+ assert builtin in names
+ described = [tool["description"].split(": ", 1)[0] for tool in tools[4:]]
+ if provider.tool_declaration_budget_tokens:
+ assert len(json.dumps(tools)) <= provider.tool_declaration_budget_tokens * 4
+ assert len(described) <= native._DIRECT_TOOL_LIMIT
+ # The curated frequent tools come first, in preference order.
+ assert described[:4] == [
+ "workspace-orchestrate",
+ "search_web",
+ "google_calendar",
+ "youtube_music",
+ ]
+ else:
+ # Gemini keeps the whole catalog LiveTools declares.
+ assert len(described) == 34
+ finally:
+ await live.session.end()
+
+
+@both_providers
+async def test_config_budget_bounds_a_provider_without_its_own(call, make_provider):
+ provider = make_provider(tool_declaration_budget_tokens=0)
+ live = call(provider, _config(budget=1_000), gateway=FakeToolGateway(catalog_of(30)))
+ await live.start()
+ try:
+ assert len(json.dumps(provider.opened_with[0].tools)) <= 4_000
+ finally:
+ await live.session.end()
+
+
+# 6. Per-turn language ----------------------------------------------------------------
+
+
+@both_providers
+async def test_turn_language_reaches_the_provider_before_the_response(tmp_path, make_provider):
+ provider = make_provider()
+ session, connection, _frames = _in_call(provider, tmp_path)
+ try:
+ await session._native_event(
+ RealtimeEvent(
+ type="input_transcript",
+ text="Wie wird das Wetter morgen in Berlin?", # i18n-allow: German speech fixture
+ is_final=True,
+ )
+ )
+ await _settle(session)
+ assert session._language == "de"
+ if connection.creates_responses_automatically:
+ # Gemini answers on its own; no extra steering turn is injected.
+ assert connection.names() == []
+ else:
+ assert connection.calls == [
+ ("update_session", {"language": "de"}),
+ ("request_response", None),
+ ]
+ finally:
+ session._ledger.close()