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): give a stalled voice turn a way out, and tell the surface what is happening
rubenluetke10-beepa321ca71e538
diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 26e3235b40..6fc1569073 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -1500,6 +1500,12 @@ class RealtimeSessionReady(Event):surface: str = ""input_sample_rate: int = 0output_sample_rate: int = 0+ #: The call's output language as a bare tag ("de" / "en" / "es" / any+ #: future supported locale), resolved by the ONE turn-language resolver.+ #: ``VoiceSessionStarted`` carries the same value but is published for the+ #: browser surface only, so on desktop this was the language nothing ever+ #: told the UI. Consumers render it; they never re-derive it.+ language: str = ""@dataclass(frozen=True, slots=True)diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.pyindex 1a0eeecc65..c0030e64f5 100644--- a/jarvis/realtime/protocol.py+++ b/jarvis/realtime/protocol.py@@ -23,6 +23,7 @@ RealtimeEventType = Literal["speech_started","interrupted","turn_complete",+ "usage","error",]@@ -54,6 +55,17 @@ class RealtimeEvent:# the Jarvis supervisor, never a provider tool call or response boundary.handoff_id: str | None = Noneprovider_turn_id: str | None = None+ # Token/second counters for one finished generation, folded per turn by the+ # orchestrator and forwarded to the recorder. Declared HERE because the+ # shipped API-billed adapters already emit ``type="usage"`` events with this+ # payload: a third-party adapter doing the same against this dataclass used+ # to raise AttributeError inside the receive pump.+ usage: dict[str, int] | None = None+ # True when JARVIS itself caused this event — an ``interrupted`` produced by+ # our own ``interrupt()`` rather than by the user speaking. Without it the+ # orchestrator reads its own cancellation as a barge-in and arms the+ # user-speech state against a user who never said anything.+ self_initiated: bool = False@dataclass(frozen=True, slots=True)@@ -118,6 +130,13 @@ class RealtimeSession(Protocol):declare it keep failing closed, which is the correct default for anythingthe model itself generates.+ Optional capability (probed with ``getattr``, defaulting to+ ``supports_direct_tools``): ``supports_tool_results``. A transport with no+ native function calling has no wire to carry a ``function_call_output``+ either, so ``send_tool_result`` on it can only raise. Callers probe this+ instead of calling and catching, because a swallowed raise is how a+ dropped tool result becomes invisible (AP-30).+A former optional ``renders_pinned_voice`` voice-identity capability(BUG-086 escalation) was removed 2026-07-21: routing delegate repliesto the surface TTS produced an audibly different voice on everydiff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.pyindex 4f001f50a3..d30d091fee 100644--- a/jarvis/realtime/scrub_gate.py+++ b/jarvis/realtime/scrub_gate.py@@ -110,6 +110,12 @@ class ScrubHoldGate:# (live forensic 2026-07-16 10:26).self._pending_since: float | None = Noneself.last_hold_ms = 0.0+ # Clearance granted to ONE injected, already-scrubbed utterance that+ # will never carry a model transcript (see ``trust_direct_speech``).+ # Scoped rather than sticky: it survives a ``drain()`` only until its+ # own audio has actually played.+ self._direct_speech_pending = False+ self._direct_speech_released_ms = 0.0@propertydef pending_audio_ms(self) -> float:@@ -243,7 +249,10 @@ class ScrubHoldGate:self._pending = []self._pending_audio_ms = 0.0self._cleared = False- self._released_ms += _duration_ms(out)+ released = _duration_ms(out)+ self._released_ms += released+ if self._direct_speech_pending:+ self._direct_speech_released_ms += releasedself._consume_hold_clock()return out@@ -260,11 +269,14 @@ class ScrubHoldGate:self._pending = []self._pending_audio_ms = 0.0self._cleared = False- self._released_ms += _duration_ms(out)+ released = _duration_ms(out)+ self._released_ms += released+ if self._direct_speech_pending:+ self._direct_speech_released_ms += releasedself._consume_hold_clock()return out- def trust_direct_speech(self) -> None:+ def trust_direct_speech(self, text: str = "") -> None:"""Clear the gate for audio rendering text Jarvis itself scrubbed.A delegate readback is injected through the provider's direct-speech@@ -275,13 +287,29 @@ class ScrubHoldGate:text-only".Re-gating this audio protects nothing: the text passed- ``scrub_for_voice`` before it was ever sent (ADR-0010). The trailing- kill switch is untouched — a later transcript that does leak still- sets ``_hard_leak`` and drops everything unplayed.+ ``scrub_for_voice`` before it was ever sent (ADR-0010) — which is also+ why the clearance cannot be re-derived later: AP-11 forbids an LLM call+ in the voice scrubber, and the model emits no transcript of its own for+ this audio. The trailing kill switch is untouched — a later transcript+ that does leak still sets ``_hard_leak`` and drops everything unplayed.++ The clearance is bound to THIS utterance (``_direct_speech_pending``):+ a ``drain()`` belonging to some OTHER response — on an+ automatic-response transport the model's own concurrent generation+ routinely ends between the injection and the first readback frame —+ must not revoke it. ``text`` is accepted for call-site clarity and for+ the debug line; the gate never re-scrubs it."""self._transcript_seen = Trueself._coverage_active = Trueself._cleared = True+ self._direct_speech_pending = True+ self._direct_speech_released_ms = 0.0+ if text:+ log.debug(+ "scrub gate trusts %d chars of injected direct speech",+ len(str(text)),+ )def fail_closed(self) -> bool:"""Drop a completed response that never produced any transcript."""@@ -343,11 +371,28 @@ class ScrubHoldGate:int(excess_ms),)self._released_ms += tail_ms+ if self._direct_speech_pending:+ self._direct_speech_released_ms += tail_msself._consume_hold_clock()return outdef drain(self) -> None:- """Barge-in / turn-end: discard buffered audio and reset per-turn state."""+ """Barge-in / turn-end: discard buffered audio and reset per-turn state.++ One exception, and it is the whole point of ``trust_direct_speech``:+ an injected, already-scrubbed utterance whose audio has not started+ playing yet keeps its clearance. On a transport that generates its own+ responses, the model's concurrent generation ends — and drains this+ gate — between the injection and the first readback frame; revoking+ there left the readback with no clearance and no model transcript, so+ the next boundary dropped the whole answer as ``no_transcript``. The+ action had already run and the user heard nothing.+ """+ keep_direct_speech = bool(+ self._direct_speech_pending+ and self._direct_speech_released_ms <= 0.0+ and not self._hard_leak+ )self._pending.clear()self._pending_audio_ms = 0.0self._cleared = False@@ -361,6 +406,13 @@ class ScrubHoldGate:self._released_ms = 0.0self._covered_chars = 0self._coverage_active = False+ self._direct_speech_pending = False+ self._direct_speech_released_ms = 0.0+ if keep_direct_speech:+ self._direct_speech_pending = True+ self._transcript_seen = True+ self._coverage_active = True+ self._cleared = Truedef _duration_ms(chunks: tuple[AudioChunk, ...] | list[AudioChunk]) -> float:diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 47576a2990..c8675f1ef8 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -70,6 +70,25 @@ _AUDIO_SEND_TIMEOUT_S = 2.0# call that went deaf is visible for its whole duration, not only at onset._HALF_DUPLEX_MUTE_ALERT_S = 6.0_HALF_DUPLEX_MUTE_REPEAT_S = 10.0+# Per-turn stall backstop. A provider can stop emitting ENTIRELY — no audio, no+# transcript, no boundary, no error — and the receive iterator then simply never+# yields again. Nothing else in this module bounds that: the pump awaits the+# iterator without a timeout and the desktop supervisor awaits wait_finished()+# without one either, so an adapter that latches goes unnoticed until the user+# kills the call. This watchdog is armed fresh for EACH turn and cancelled at+# every boundary (AP-19: never a process-global counter — BUG-032 was exactly+# that bug, a watchdog that fired between units of work). 20 s is deliberately+# above the 15 s untranscribed-audio bound so a slow-but-alive reply is never+# cut; a turn silent for longer than that is stuck, not busy.+_TURN_STALL_TIMEOUT_S = 20.0+_TURN_STALL_POLL_S = 0.5+# Withheld provider output used to leave no trace anywhere (AP-30): a turn could+# be dropped in full and the log looked like a healthy call. Report it, bounded.+_OUTPUT_DROP_LOG_INTERVAL_S = 2.0+# Answered input-item ids retained for duplicate suppression. Per transport+# (cleared on rebuild) and bounded, so a long call cannot grow one entry per+# utterance forever.+_ANSWERED_INPUT_ID_MAX = 64_TOOL_TRANSCRIPT_WAIT_S = 3.0# Grace window for the model to finish its goodbye after an end_call tool# call; if the provider never sends turn_complete, hang up anyway.@@ -1008,6 +1027,17 @@ class RealtimeVoiceSession:# the condition is visible instead of invisible (AP-30).self._half_duplex_muted_since: float | None = Noneself._half_duplex_mute_reported = 0.0+ # Per-turn stall watchdog (see _TURN_STALL_TIMEOUT_S). Armed by+ # _ensure_turn_started, cancelled by _reset_turn_tracking, so its+ # lifetime is exactly one turn and it can never fire between turns.+ self._turn_stall_task: asyncio.Task[None] | None = None+ self._turn_activity_at = 0.0+ # Rate limiter + reason for the "provider output is being dropped" log.+ self._output_drop_reported = 0.0+ self._output_drop_count = 0+ # Frames discarded because a transport rebuild is pending. Reported so a+ # stuck marker cannot silently swallow the microphone (AP-30).+ self._rebuild_drop_reported = 0.0brain_config = getattr(self._config, "brain", None)reply_language = str(@@ -1525,6 +1555,19 @@ class RealtimeVoiceSession:if offer_sdp:self._transport_offer_sdp = offer_sdpif self._session is None:+ # A cold subscription transport legitimately spends tens of+ # seconds here (app-server spawn, account verification, WebRTC+ # negotiation). Announcing the attempt BEFORE the wait is the+ # difference between a surface that can show progress and one+ # that shows dead air for the whole budget.+ await self._send_json(+ {+ "type": "audio_starting",+ "provider": self.active_provider,+ "language": self._language,+ "handshake_budget_s": self._declared_handshake_budget_s(),+ }+ )await self._open()self._in_resampler = StreamingPcm16Resampler(self.browser_sample_rate, self._input_sample_rate@@ -1533,6 +1576,11 @@ class RealtimeVoiceSession:"type": "audio_ready","provider": self.active_provider,"model": self._active_model,+ # The call's output language, from the ONE resolver+ # (jarvis/core/turn_language.py via _resolve_lang) — never a+ # per-layer default and never a de/en-only guess. Bare tag+ # ("de" / "en" / "es" / any future supported locale).+ "language": self._language,"requires_webrtc_answer": bool(getattr(self._provider, "requires_webrtc_offer", False)),@@ -1545,6 +1593,7 @@ class RealtimeVoiceSession:if answer_sdp:ready["webrtc_answer_sdp"] = answer_sdpawait self._send_json(ready)+ await self._announce_language()if self._surface == "browser" and not self._browser_session_started:await self._publish_browser_session_started()self._browser_session_started = True@@ -1561,6 +1610,40 @@ class RealtimeVoiceSession:elif kind == "audio_stop":await self.end(reason=HANGUP_CLIENT_STOP)+ def _declared_handshake_budget_s(self) -> float:+ """Longest handshake any still-eligible provider declares it needs.++ A capability read across the candidates this session actually holds+ (AP-21), never a provider-name check, and never below the shared+ default so a surface can use it directly as a progress budget.+ """+ declared = [float(_PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S)]+ for provider in self._providers:+ if not self._provider_is_available(provider):+ continue+ declared.append(+ float(getattr(provider, "handshake_budget_s", 0.0) or 0.0)+ )+ return max(declared)++ async def _announce_language(self) -> None:+ """Tell every surface which language this call is speaking.++ One field, one producer: ``_language`` is whatever+ ``resolve_output_language`` returned (pin -> stickiness -> detected+ input -> DEFAULT_LOCALE). Surfaces render it; they never re-derive it.+ """+ try:+ await self._send_json(+ {"type": "language", "language": self._language}+ )+ except Exception: # noqa: BLE001 — a surface may already be gone+ log.debug(+ "realtime[%s] language announcement failed",+ self.session_id,+ exc_info=True,+ )+def _active_provider_selection(self, provider: Any) -> tuple[str, str]:provider_id = str(getattr(provider, "name", "") or "")providers = getattr(getattr(self._config, "brain", None), "providers", None)@@ -1811,7 +1894,20 @@ class RealtimeVoiceSession:if self._ended or self._session is None or not pcm_native:returnif self._session is self._transport_rebuild_pending:+ # Deliberate: the transport is being swapped and this frame cannot+ # land anywhere. Silence here was indistinguishable from a healthy+ # call when the marker got stuck, so say it — bounded (AP-30).+ now = time.monotonic()+ if now - self._rebuild_drop_reported >= _HALF_DUPLEX_MUTE_REPEAT_S:+ self._rebuild_drop_reported = now+ log.warning(+ "realtime[%s] dropping microphone frames while a transport "+ "rebuild is pending — nothing the user says is reaching "+ "the provider",+ self.session_id,+ )return+ self._rebuild_drop_reported = 0.0if self._half_duplex and self._output_active:self._note_half_duplex_mute()return@@ -2115,6 +2211,22 @@ class RealtimeVoiceSession:# A normal receive-side rebuild may have won the race.# Discard that old session's queued write-stall signal# and keep the current transport pass alive.+ #+ # Releasing the marker here is load-bearing: it is the+ # ONLY other thing that gates handle_audio_frame, and+ # _rebuild_transport — the only other place that clears+ # it — is precisely the path this branch skips. Left+ # standing it silently discarded every later microphone+ # frame for the rest of the call.+ if self._transport_rebuild_pending is target_session:+ self._transport_rebuild_pending = None+ log.info(+ "realtime[%s] discarded a stale transport "+ "rebuild request (%s); the microphone stays "+ "open",+ self.session_id,+ detail,+ )if transport_task in done:return await transport_taskcontinue@@ -2132,6 +2244,10 @@ class RealtimeVoiceSession:"""try:async for event in self._session.receive():+ # Any event at all proves the transport is still producing, so+ # the per-turn stall watchdog measures exactly one thing: total+ # provider silence inside an open turn.+ self._note_turn_activity()if event.type == "input_transcript":transcript = _dictionary_corrected(str(event.text or "").strip())transcription_failed = bool(event.error)@@ -2199,8 +2315,13 @@ class RealtimeVoiceSession:and input_item_id in self._response_requested_input_ids)if event.is_final and input_already_answered:- log.debug(- "realtime[%s] ignored duplicate final input item %s",+ # A swallowed user utterance is never a debug-level+ # event: if the id space ever collides, this is the+ # only trace that turn 2 vanished (AP-30).+ log.info(+ "realtime[%s] ignored a final input item this turn "+ "already answered (item=%s); if the user is "+ "waiting, the provider reused an item id",self.session_id,input_item_id,)@@ -2264,6 +2385,10 @@ class RealtimeVoiceSession:self._gate = ScrubHoldGate(new_language)if self._tool_bridge is not None:self._tool_bridge.set_language(new_language)+ # The surfaces label the call with this; a flip+ # that only the session knows about leaves every+ # indicator stuck on the opening language.+ await self._announce_language()if input_observed:self._mark_latency_named("REALTIME_INPUT_COMMITTED",@@ -2441,7 +2566,11 @@ class RealtimeVoiceSession:and input_observedand self._delegate_required_for_turn):- self._start_deterministic_delegate(self._last_user_text)+ # This branch runs on a FINAL input transcript, so the+ # utterance is provably over — no boundary wait needed.+ self._start_deterministic_delegate(+ self._last_user_text, input_final=True+ )if (event.is_finaland input_observed@@ -2476,6 +2605,17 @@ class RealtimeVoiceSession:self._response_requested_for_turn = Trueif input_item_id:self._response_requested_input_ids.add(input_item_id)+ if (+ len(self._response_requested_input_ids)+ > _ANSWERED_INPUT_ID_MAX+ ):+ # Bounded: a long call must not accumulate one+ # entry per utterance for its whole lifetime.+ self._response_requested_input_ids = set(+ tuple(self._response_requested_input_ids)[+ -_ANSWERED_INPUT_ID_MAX:+ ]+ )elif event.type == "handoff_requested":# Client-managed handoffs are a provider control boundary,# never a public response boundary and never a direct tool@@ -2552,6 +2692,7 @@ class RealtimeVoiceSession:delegate_state.bridge_transcript_parts.append(event.text)continueif self._must_withhold_provider_output():+ self._note_output_withheld("transcript")self._gate.drain()continueawait self._ensure_turn_started()@@ -2632,8 +2773,8 @@ class RealtimeVoiceSession:)for chunk in self._gate.release_available():await self._emit_audio(chunk)- elif event.type == "usage" and event.usage is not None:- for key, value in event.usage.items():+ elif event.type == "usage" and getattr(event, "usage", None):+ for key, value in dict(event.usage).items():if isinstance(value, int) and value > 0:self._turn_usage[key] = (self._turn_usage.get(key, 0) + value@@ -2665,6 +2806,7 @@ class RealtimeVoiceSession:delegate_state.bridge_audio_chunks.append(event.audio)continueif self._must_withhold_provider_output():+ self._note_output_withheld("audio")self._gate.drain()continueawait self._ensure_turn_started()@@ -2704,6 +2846,22 @@ class RealtimeVoiceSession:reason="output transcript exceeded safe audio buffer",fallback_text=trusted_reply or None,)+ elif event.type == "interrupted" and getattr(+ event, "self_initiated", False+ ):+ # Jarvis's own interrupt() echoing back as a provider+ # event. Every site that issues one (barge-in, the handoff+ # cut, the delegate boundary cut, the unsafe-output cancel)+ # already drained the gate and armed its own withhold, so+ # there is nothing left to do — while treating it as a+ # barge-in armed _user_speech_active against a user who+ # never spoke, blocking announcements, late action results+ # and the readback watchdog until the next real transcript.+ log.debug(+ "realtime[%s] ignored a self-initiated provider "+ "interruption",+ self.session_id,+ )elif event.type in {"speech_started", "interrupted"} and (self._pending_delegate_needs_endpoint_protection()or self._delegate_readback_awaits_first_audio()@@ -3385,12 +3543,15 @@ class RealtimeVoiceSession:# turn boundary for no reason.self._advised_reconnect_detail = Noneself._gate = ScrubHoldGate(self._language)- self._output_active = False- self._output_samples_sent = 0- self._response_requested_for_turn = False- self._user_speech_active = False+ self._reset_output_state(reason="transport rebuild")self._drop_provider_output_until_new_response = Falseself._drop_provider_output_until_user_turn = False+ # Input-item ids are scoped to the DEAD transport. A fresh provider+ # session may restart its numbering, and a collision here silently+ # swallows the next real utterance at the duplicate-item guard — the+ # user speaks and no turn ever opens. The set is per-transport, so it+ # is retired with the transport.+ self._response_requested_input_ids.clear()log.warning("realtime[%s] transport died mid-call (%s) — rebuilding the ""provider session in place (%d/%d in the current %.0f s window)",@@ -3415,6 +3576,7 @@ class RealtimeVoiceSession:"type": "audio_ready","provider": self.active_provider,"model": self._active_model,+ "language": self._language,"requires_webrtc_answer": bool(getattr(self._provider, "requires_webrtc_offer", False)),@@ -3428,6 +3590,7 @@ class RealtimeVoiceSession:if answer_sdp:ready["webrtc_answer_sdp"] = answer_sdpawait self._send_json(ready)+ await self._announce_language()except Exception: # noqa: BLE001, S110 — surface refresh is best-effortpassreturn True@@ -3702,6 +3865,7 @@ class RealtimeVoiceSession:provider=self.active_provider,model=self._active_model,surface=self._surface,+ language=self._language,input_sample_rate=self._input_sample_rate,output_sample_rate=int(getattr(self._provider, "output_sample_rate", 24_000) or 24_000@@ -3775,9 +3939,142 @@ class RealtimeVoiceSession:self._current_turn_index = self._turn_indexself._turn_index += 1self._latency_tracker = self._create_latency_tracker(trace_id)+ self._arm_turn_stall_watchdog()if self._external_update is None:await self._publish_turn_started()+ def _note_turn_activity(self) -> None:+ """Record that the provider is still producing something for this turn."""+ self._turn_activity_at = time.monotonic()++ def _cancel_turn_stall_watchdog(self) -> None:+ task = self._turn_stall_task+ self._turn_stall_task = None+ if task is not None and not task.done():+ task.cancel()++ def _arm_turn_stall_watchdog(self) -> None:+ """Start the one watchdog that owns THIS turn.++ Re-armed per turn on purpose (AP-19): a shared counter that survives a+ boundary fires against the next turn's fresh answer, which is exactly+ BUG-032. Cancelled in ``_reset_turn_tracking``, so its lifetime cannot+ outlive the turn that created it.+ """+ self._cancel_turn_stall_watchdog()+ self._note_turn_activity()+ turn_id = self._turn_id+ if not turn_id:+ return+ self._turn_stall_task = asyncio.create_task(+ self._watch_turn_for_stall(turn_id),+ name=f"rt-turn-stall-{self.session_id}",+ )++ def _turn_stall_is_excusable(self, turn_id: str) -> bool:+ """Whether silence right now is legitimate rather than a wedge."""+ return bool(+ self._ended+ or self._failed.is_set()+ or self._hangup_reason+ or self._session is None+ # A delegated Brain turn is allowed to be silent: it has its own+ # budget (_DELEGATE_TIMEOUT_S) and its own readback watchdog.+ or self._turn_has_pending_delegate(turn_id)+ or self._has_pending_delegate_from_earlier_turn()+ # The user is audibly mid-utterance; the provider owes nothing yet.+ or self._user_speech_active+ # Audio is flowing, so the transport is demonstrably alive.+ or self._output_active+ or self._output_samples_sent > 0+ )++ async def _watch_turn_for_stall(self, turn_id: str) -> None:+ """Break a turn that produced nothing at all, and say why out loud.++ The provider iterator has no timeout and neither does the surface's+ ``wait_finished()``, so an adapter that stops emitting entirely — no+ audio, no transcript, no boundary, no error — leaves the call open+ forever with the microphone held shut by half-duplex. This is the+ independent backstop for that: it never trusts the transport to+ report its own death.+ """+ try:+ while True:+ await asyncio.sleep(_TURN_STALL_POLL_S)+ if self._turn_id != turn_id:+ return+ if self._turn_stall_is_excusable(turn_id):+ self._note_turn_activity()+ continue+ silent_s = time.monotonic() - self._turn_activity_at+ if silent_s < _TURN_STALL_TIMEOUT_S:+ continue+ await self._recover_stalled_turn(turn_id, silent_s)+ return+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — the backstop must never end the call+ log.warning(+ "realtime[%s] turn stall watchdog failed for turn %s",+ self.session_id,+ turn_id,+ exc_info=True,+ )++ async def _recover_stalled_turn(self, turn_id: str, silent_s: float) -> None:+ """Close a wedged turn honestly: say what happened, then reopen the mic."""+ from jarvis.voice.action_phrases import action_phrase # noqa: PLC0415++ pending_update = self._external_update+ log.warning(+ "realtime[%s] turn %s produced no audio, transcript, tool call or "+ "boundary for %.1fs (provider=%s, response_requested=%s, "+ "output_withheld=%s) — closing it locally so the microphone "+ "reopens; the transport stopped emitting without reporting it",+ self.session_id,+ turn_id,+ silent_s,+ self.active_provider or "unknown",+ self._response_requested_for_turn,+ self._must_withhold_provider_output(),+ )+ await self._publish_error(+ "RealtimeTurnStalled",+ (+ f"The realtime provider produced nothing for {silent_s:.0f}s "+ "on an open turn; the turn was closed locally."+ ),+ recoverable=True,+ )+ # Say something TRUE. A stalled turn is not "something went wrong" in+ # the abstract — the request was received and simply never answered,+ # which is what action_timeout states, in every supported language.+ # An out-of-band readback that never rendered is spoken verbatim+ # instead: its text is already scrubbed and is the honest content.+ if pending_update is not None and pending_update.source_text:+ spoken = pending_update.source_text+ language = pending_update.language+ else:+ language = self._language+ spoken = action_phrase("action_timeout", language)+ if not self._output_transcript:+ self._output_transcript.append(spoken)+ # _external_update is deliberately left standing: _publish_turn_completed+ # consumes it and records the readback on its own SpeechSpoken track.+ try:+ await self._send_json(self._surface_speech_message(spoken))+ except Exception: # noqa: BLE001 — the reset below matters more+ log.warning(+ "realtime[%s] could not voice the stalled-turn notice",+ self.session_id,+ exc_info=True,+ )+ # Withholding armed by this dead turn must not deafen the next one.+ self._drop_provider_output_until_new_response = False+ self._gate.drain()+ await self._complete_surface_turn()+def _create_latency_tracker(self, trace_id: Any) -> Any | None:"""Build optional telemetry without making it a voice dependency."""try:@@ -4288,16 +4585,46 @@ class RealtimeVoiceSession:self._external_update = Noneself._reset_turn_tracking()- async def _complete_surface_turn(self) -> None:- """Publish one idempotent surface boundary and reset turn state."""- if not self._turn_id:- return- await self._send_json({"type": "turn_complete"})- await self._publish_turn_completed()+ def _reset_output_state(self, *, reason: str) -> None:+ """Clear every per-response duplex flag — on EVERY path that ends one.++ Half-duplex mutes the microphone while ``_output_active`` stands+ (``handle_audio_frame``), and on a transport whose speech-start edges+ are derived from that same microphone the flag is SELF-SUSTAINING:+ while it is set, none of the events that would clear it can be+ observed. So this reset must never sit behind a condition. It used to:+ ``_complete_surface_turn`` returned early when the turn id had already+ been cleared by an earlier local boundary, skipping every line below+ and leaving the call permanently deaf with only the six-second+ half-duplex warning as a trace.++ The two ``_drop_provider_output_*`` flags are deliberately NOT cleared+ here: they exist to withhold a LATE provider rendering that arrives+ after its turn closed, so a turn boundary is precisely when they must+ survive. They are released by real user input and by the delivery+ paths that own them.+ """+ if self._output_active or self._output_samples_sent:+ log.debug(+ "realtime[%s] output state reset (%s)", self.session_id, reason+ )self._output_active = Falseself._output_samples_sent = 0self._response_requested_for_turn = Falseself._user_speech_active = False+ self._half_duplex_muted_since = None+ self._half_duplex_mute_reported = 0.0++ async def _complete_surface_turn(self) -> None:+ """Publish one idempotent surface boundary and reset turn state.++ Publishing needs a turn id; RESETTING never does (see+ ``_reset_output_state``).+ """+ if self._turn_id:+ await self._send_json({"type": "turn_complete"})+ await self._publish_turn_completed()+ self._reset_output_state(reason="surface turn boundary")self._turn_final_text = ""self._schedule_late_delegate_flush()@@ -4354,6 +4681,11 @@ class RealtimeVoiceSession:)def _reset_turn_tracking(self) -> None:+ # The stall watchdog belongs to exactly one turn. Cancelling it here —+ # the single choke point every boundary passes through — is what keeps+ # it from surviving into the next unit of work and aborting a fresh+ # answer (AP-19 / BUG-032).+ self._cancel_turn_stall_watchdog()self._turn_id = ""self._turn_trace_id = Noneself._latency_tracker = None@@ -4484,14 +4816,59 @@ class RealtimeVoiceSession:return refreturn None+ def _session_takes_tool_results(self) -> bool:+ """Whether this transport can carry a tool result back to the model.++ Capability, never a provider name (AP-21). A transport with no native+ function calling has no ``function_call_output`` wire either, so+ ``send_tool_result`` on it can only raise — and a raise caught and+ logged at DEBUG is how a dropped result becomes invisible (AP-30).+ """+ session = self._session+ if session is None:+ return False+ explicit = getattr(session, "supports_tool_results", None)+ if explicit is not None:+ return bool(explicit)+ return bool(getattr(session, "supports_direct_tools", True))+def _must_withhold_provider_output(self) -> bool:"""Drop untrusted output during delegation and after barge-in."""- return bool(- self._drop_provider_output_until_new_response- or self._drop_provider_output_until_user_turn- or self._must_withhold_delegate_output()- or self._delegate_surface_fallback_spoken()+ return bool(self._output_withhold_reason())++ def _output_withhold_reason(self) -> str:+ """Name the guard currently withholding provider output, or ``""``.++ Each of these is individually correct, but together they can silence a+ whole turn — and until now they did it without leaving a single trace,+ so a silent call and a healthy one looked identical in the log.+ """+ if self._drop_provider_output_until_new_response:+ return "awaiting a new response after a barge-in or delegation"+ if self._drop_provider_output_until_user_turn:+ return "awaiting the user's next turn after a surface fallback"+ if self._must_withhold_delegate_output():+ return "a delegated action owns this turn"+ if self._delegate_surface_fallback_spoken():+ return "the surface already spoke this turn's reply"+ return ""++ def _note_output_withheld(self, kind: str) -> None:+ """Report, bounded, that provider output is being dropped (AP-30)."""+ self._output_drop_count += 1+ now = time.monotonic()+ if now - self._output_drop_reported < _OUTPUT_DROP_LOG_INTERVAL_S:+ return+ self._output_drop_reported = now+ log.info(+ "realtime[%s] withholding provider %s (%d event(s) so far this "+ "window): %s",+ self.session_id,+ kind,+ self._output_drop_count,+ self._output_withhold_reason() or "unknown",)+ self._output_drop_count = 0def _track_delegate_task(self, turn_id: str, task: asyncio.Task[None]@@ -4968,7 +5345,7 @@ class RealtimeVoiceSession:await self._session.send_tool_result(call_id, wire_name, result)async def _handle_end_call(self, event: Any) -> None:- if self._session is not None:+ if self._session is not None and self._session_takes_tool_results():try:await self._session.send_tool_result(str(getattr(event, "call_id", "") or ""),@@ -4976,7 +5353,12 @@ class RealtimeVoiceSession:{"success": True},)except Exception: # noqa: BLE001 — still hang up on a dead wire- log.debug("end_call tool result send failed", exc_info=True)+ log.warning(+ "realtime[%s] end_call acknowledgement could not be sent; "+ "hanging up anyway",+ self.session_id,+ exc_info=True,+ )self._end_after_turn = Trueif self._end_call_timer is None or self._end_call_timer.done():self._end_call_timer = asyncio.create_task(@@ -4984,8 +5366,16 @@ class RealtimeVoiceSession:name=f"rt-end-call-{self.session_id}",)- def _start_deterministic_delegate(self, user_text: str) -> None:- """Start one orchestrator-owned Brain turn for local-evidence input."""+ def _start_deterministic_delegate(+ self, user_text: str, *, input_final: bool = False+ ) -> None:+ """Start one orchestrator-owned Brain turn for local-evidence input.++ ``input_final`` says the DISPATCHING path already saw the utterance+ close. On a transport whose input transcription is local there is no+ provider input boundary to wait for at all, so without this every such+ turn paid the full stability window before the Brain was even asked.+ """turn_id = self._turn_idif not turn_id:return@@ -4994,6 +5384,7 @@ class RealtimeVoiceSession:_DelegateTurnState(deterministic=True),)turn_state.deterministic = True+ turn_state.input_final = turn_state.input_final or bool(input_final)turn_state.user_text = str(user_text or "").strip()if turn_state.dispatch_started or turn_state.result_complete:return@@ -5042,14 +5433,27 @@ class RealtimeVoiceSession:# Provider-voiced text must NOT estimate its playback horizon —# its real audio advances the echo guard on the way out.self._register_spoken_reference(spoken)+ # This refusal is OUR text, already scrubbed. The withhold that+ # the user's own speech edge armed applies to model output, not+ # to it — leaving it armed made _emit_audio drop the refusal+ # silently, so the user heard nothing at all.+ self._drop_provider_output_until_new_response = False+ self._drop_provider_output_until_user_turn = Falseawait send_speech(spoken)if getattr(self._session, "direct_speech_is_authoritative", False):# Trusted verbatim speech carries no model transcript for# the scrub gate to vet; without this the refusal is# dropped at the turn boundary and the user hears silence.- self._gate.trust_direct_speech()+ self._gate.trust_direct_speech(spoken)for chunk in self._gate.release_available():await self._emit_audio(chunk)+ # Both branches must leave the same state behind. Returning+ # here without a boundary left the turn open with _output_active+ # standing, which on a half-duplex surface is a permanently+ # deaf microphone.+ if not self._output_transcript:+ self._output_transcript.append(spoken)+ await self._complete_surface_turn()returnexcept Exception: # noqa: BLE001 — the surface still speaks itlog.warning(@@ -5060,8 +5464,7 @@ class RealtimeVoiceSession:)self._register_spoken_reference(spoken, estimate_playback=True)await self._send_json(self._surface_speech_message(spoken))- await self._send_json({"type": "turn_complete"})- await self._publish_turn_completed()+ await self._complete_surface_turn()async def _await_provider_response_boundary(self, turn_state: _DelegateTurnState@@ -5433,6 +5836,18 @@ class RealtimeVoiceSession:self._arm_stale_readback_guard(trusted_reply)await self._send_json(self._surface_speech_message(trusted_reply))return+ if turn_state.pending_tool_calls and not self._session_takes_tool_results():+ # Should be unreachable (a transport with no native tools can+ # never accumulate calls), but silence here would strand the+ # answer entirely. Drop the calls loudly and speak the result.+ log.warning(+ "realtime[%s] %d native tool result(s) cannot be delivered: "+ "this transport has no function-call wire — speaking the "+ "result instead",+ self.session_id,+ len(turn_state.pending_tool_calls),+ )+ turn_state.pending_tool_calls.clear()if turn_state.pending_tool_calls:for call_id, wire_name in tuple(turn_state.pending_tool_calls):await self._session.send_tool_result(@@ -5453,7 +5868,7 @@ class RealtimeVoiceSession:# Without this the whole answer is dropped at the turn# boundary as "output transcript missing" — the action# ran and the user heard nothing.- self._gate.trust_direct_speech()+ self._gate.trust_direct_speech(trusted_reply)for chunk in self._gate.release_available():await self._emit_audio(chunk)else:@@ -5797,6 +6212,7 @@ class RealtimeVoiceSession:async def _emit_audio(self, chunk: Any) -> None:if self._must_withhold_provider_output():+ self._note_output_withheld("audio")returnpcm = bytes(getattr(chunk, "pcm", b"") or b"")if not pcm:@@ -5918,6 +6334,7 @@ class RealtimeVoiceSession:returnself._ended = Trueself._loop_lag.stop()+ self._cancel_turn_stall_watchdog()self._cancel_tool_transcript_wait()if self._end_call_timer is not None and not self._end_call_timer.done():self._end_call_timer.cancel()diff --git a/tests/unit/realtime/test_protocol.py b/tests/unit/realtime/test_protocol.pyindex 8c8e3e3b6a..1775e39205 100644--- a/tests/unit/realtime/test_protocol.py+++ b/tests/unit/realtime/test_protocol.py@@ -47,3 +47,31 @@ def test_session_config_history_defaults_empty():# The first open of a call carries no history; only a mid-call reopen# (transport rebuild / cross-family fallback) seeds it (BUG-088).assert RealtimeSessionConfig().history == ()+++def test_event_declares_the_usage_payload_the_adapters_already_emit():+ """The shipped API-billed adapters emit ``type="usage"`` with a payload.++ The contract described neither the event type nor the field, so an adapter+ built against this dataclass — rather than against a private one — raised+ AttributeError inside the receive pump the moment it reported usage.+ """+ from jarvis.realtime.protocol import RealtimeEvent, RealtimeEventType++ assert "usage" in RealtimeEventType.__args__+ assert RealtimeEvent(type="audio_delta").usage is None+ event = RealtimeEvent(type="usage", usage={"input_tokens": 12})+ assert event.usage == {"input_tokens": 12}+++def test_event_can_mark_a_self_initiated_interruption():+ """Jarvis's own interrupt() must be distinguishable from a barge-in.++ Without the flag the orchestrator reads its own cancellation as "the user+ started speaking" and arms the user-speech state against a user who never+ said anything.+ """+ from jarvis.realtime.protocol import RealtimeEvent++ assert RealtimeEvent(type="interrupted").self_initiated is False+ assert RealtimeEvent(type="interrupted", self_initiated=True).self_initiateddiff --git a/tests/unit/realtime/test_scrub_gate.py b/tests/unit/realtime/test_scrub_gate.pyindex 8f922fd9ed..c4a743ad0b 100644--- a/tests/unit/realtime/test_scrub_gate.py+++ b/tests/unit/realtime/test_scrub_gate.py@@ -476,3 +476,61 @@ async def test_trust_direct_speech_keeps_the_trailing_kill_switch():)assert gate.hard_leak_pending() is Trueassert await gate.push_audio(_chunk(4)) == []+++async def test_drain_keeps_direct_speech_trust_until_its_audio_played():+ """A boundary belonging to ANOTHER response must not revoke the clearance.++ On a transport that generates its own responses, the model's concurrent+ generation ends — and drains this gate — between the injection of a+ trusted delegate readback and its first audible frame. Revoking there left+ the readback with no clearance and no model transcript of its own, so the+ next boundary dropped the whole answer as "no_transcript": the action had+ already run and the user heard nothing.+ """+ gate = ScrubHoldGate(language="en")+ gate.trust_direct_speech("The settings are open.")++ # The other response's boundary lands before any readback audio arrives.+ gate.drain()++ # The readback is still trusted, so its audio flows instead of being held.+ assert await gate.push_audio(_chunk(4))+ assert gate.fail_closed() is False+ assert gate.hard_leak_pending() is False+++async def test_drain_revokes_direct_speech_trust_once_it_has_played():+ """The exception is scoped: it survives ONE boundary, not the session.++ Once the injected utterance has actually been heard, a drain is an+ ordinary barge-in/turn end for it and the gate returns to fail-closed for+ everything the model produces afterwards.+ """+ gate = ScrubHoldGate(language="en")+ gate.trust_direct_speech("The settings are open.")+ assert await gate.push_audio(_chunk(4)) # the readback became audible++ gate.drain()++ # Model audio after that boundary is gated again, with no transcript yet.+ assert await gate.push_audio(_chunk(4)) == []+ assert gate.fail_closed() is True+++async def test_drain_never_carries_a_hard_leak_forward():+ """A revoked-by-leak injection must not be resurrected by the exception."""+ gate = ScrubHoldGate(language="en")+ gate.trust_direct_speech("The settings are open.")+ await gate.feed_transcript(+ "Traceback (most recent call last):\n File x\nValueError: y\n\n"+ )+ assert gate.hard_leak_pending() is True++ gate.drain()++ assert gate.hard_leak_pending() is False+ assert await gate.push_audio(_chunk(4)) == []diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 3eba838ce3..fd4e57694a 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -6296,3 +6296,435 @@ async def test_a_new_order_still_reaches_the_orchestrator_while_one_runs():assert refusals == [], "a new order must never be refused as a repeat"gate.set()await sess.end(reason="test")+++# ---------------------------------------------------------------------------+# Subscription-transport parity: the capability tuple no other fake carries.+#+# The ChatGPT-subscription voice ships with creates_responses_automatically ++# isolates_response_generations + NO native tools + authoritative direct speech+# + a rebuildable transport, on a half-duplex desktop surface. Every fake above+# tests one of those in isolation; the wedges live in the COMBINATION, because+# on that transport the microphone is both the thing half-duplex mutes and the+# only source of the speech edges that would unmute it.+# ---------------------------------------------------------------------------+++class SubscriptionLikeSession(FakeSession):+ """A queue-driven session with the live subscription capability tuple."""++ supports_tool_updates = False+ supports_direct_tools = False+ creates_responses_automatically = True+ isolates_response_generations = True+ direct_speech_is_authoritative = True+ rebuild_on_transport_death = True++ def __init__(self, events=None):+ super().__init__(list(events or []))+ self.queue: asyncio.Queue = asyncio.Queue()+ self.spoken = []++ async def receive(self):+ for event in self._events:+ yield event+ await asyncio.sleep(0)+ while True:+ event = await self.queue.get()+ if event is None:+ return+ yield event++ async def send_speech(self, text):+ self.spoken.append(text)++ async def send_tool_result(self, call_id, name, result):+ # The real transport has no function-call wire and can only raise.+ raise RuntimeError("this transport does not execute tools directly")+++class SubscriptionLikeProvider(FakeProvider):+ name = "subscription-like"+ supports_direct_tools = False+ handshake_budget_s = 45.0++ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = SubscriptionLikeSession(self._events)+ return self.session+++def _pcm_chunk(samples=240):+ return AudioChunk(+ pcm=b"\x10\x20" * samples, sample_rate=24_000, timestamp_ns=0+ )+++def _half_duplex_session(provider, *, brain=None, jsons=None, binaries=None):+ """A desktop-shaped session: half-duplex, exactly like the live surface."""+ return RealtimeVoiceSession(+ session_id="subscription-test",+ send_binary=(+ (lambda data: binaries.append(data) or asyncio.sleep(0))+ if binaries is not None+ else (lambda _data: asyncio.sleep(0))+ ),+ send_json=(+ (lambda m: jsons.append(m) or asyncio.sleep(0))+ if jsons is not None+ else (lambda _m: asyncio.sleep(0))+ ),+ provider=provider,+ config=_delegate_cfg("delegate"),+ brain=brain,+ half_duplex=True,+ surface="desktop",+ )+++async def _microphone_reaches(sess, session) -> bool:+ """Whether a microphone frame still gets through to the transport."""+ before = len(session.sent_audio)+ await sess.handle_audio_frame(b"\x00\x01" * 480)+ return len(session.sent_audio) > before+++async def test_subscription_capability_tuple_survives_three_turns():+ """Turn 2 and 3 must work exactly like turn 1.++ The reported failure was "transcription only works for the first run, then+ it listens forever". Every per-response flag has to be back at rest after+ each boundary, and — the load-bearing part — the microphone has to still+ reach the transport, because on this provider a muted microphone also+ starves the only source of the next turn's speech edges.+ """+ provider = SubscriptionLikeProvider([])+ jsons = []+ sess = _half_duplex_session(provider, jsons=jsons)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ session = provider.session++ for index in range(3):+ await session.queue.put(RealtimeEvent(type="speech_started"))+ await session.queue.put(+ RealtimeEvent(+ type="input_transcript",+ text=f"question number {index}",+ is_final=True,+ )+ )+ await session.queue.put(+ RealtimeEvent(type="output_transcript_delta", text="Here you go.")+ )+ await session.queue.put(+ RealtimeEvent(type="audio_delta", audio=_pcm_chunk())+ )+ await session.queue.put(RealtimeEvent(type="turn_complete"))+ await _wait_until(+ lambda i=index: len(+ [m for m in jsons if m.get("type") == "turn_complete"]+ )+ > i+ )+ # The boundary settles across two awaits: the surface message goes out+ # first, then the record is published, and only then is the duplex+ # state reset (the record reads _output_samples_sent, so it cannot be+ # reordered). Let it settle rather than racing it.+ try:+ await _wait_until(lambda: sess._output_active is False)+ except TimeoutError:+ pass # fall through to the explicit assertion below+ assert sess._output_active is False, f"turn {index + 1} stayed speaking"+ assert sess._output_samples_sent == 0+ assert sess._response_requested_for_turn is False+ assert sess._user_speech_active is False+ assert sess._transport_rebuild_pending is None+ assert await _microphone_reaches(sess, session), (+ f"the microphone was still muted after turn {index + 1}"+ )++ # The transport declares rebuild_on_transport_death, so ENDING the+ # stream would only make the pump reopen it. End the call instead.+ await sess.end(reason="test")+++async def test_a_boundary_after_a_local_completion_still_reopens_the_microphone():+ """The turn-id guard used to swallow the whole reset.++ ``_complete_surface_turn`` returned early when an earlier local path had+ already cleared the turn id, so ``_output_active`` — the flag half-duplex+ mutes the microphone on — was never cleared. On this transport that is+ terminal: the muted microphone starves the local endpointer, so no speech+ edge, no transcript and no further boundary can ever arrive to clear it.+ """+ provider = SubscriptionLikeProvider([])+ sess = _half_duplex_session(provider)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ session = provider.session++ await session.queue.put(+ RealtimeEvent(type="input_transcript", text="hello", is_final=True)+ )+ await session.queue.put(+ RealtimeEvent(type="output_transcript_delta", text="Hi there.")+ )+ await session.queue.put(+ RealtimeEvent(type="audio_delta", audio=_pcm_chunk())+ )+ await _wait_until(lambda: sess._output_active)++ # A local path closes the turn without touching the duplex flags — this is+ # what _begin_user_speech_turn and the old decline path both did.+ await sess._publish_turn_completed()+ assert sess._turn_id == ""+ assert sess._output_active is True+ assert not await _microphone_reaches(sess, session)++ await session.queue.put(RealtimeEvent(type="turn_complete"))+ await _wait_until(lambda: sess._output_active is False)+ assert await _microphone_reaches(sess, session)++ # The transport declares rebuild_on_transport_death, so ENDING the+ # stream would only make the pump reopen it. End the call instead.+ await sess.end(reason="test")+++async def test_a_silent_provider_turn_is_closed_locally_and_said_out_loud(+ monkeypatch,+):+ """A transport that stops emitting must not hold the call open forever.++ The receive iterator has no timeout and neither does the surface's+ wait_finished(), so an adapter that latches emits nothing at all — no+ audio, no transcript, no boundary, no error — and the call sits with the+ microphone shut until the user kills it. The watchdog is the independent+ backstop: it never trusts the transport to report its own death.+ """+ import jarvis.realtime.session as session_module++ monkeypatch.setattr(session_module, "_TURN_STALL_TIMEOUT_S", 0.2)+ monkeypatch.setattr(session_module, "_TURN_STALL_POLL_S", 0.02)++ provider = SubscriptionLikeProvider([])+ jsons = []+ sess = _half_duplex_session(provider, jsons=jsons)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ session = provider.session++ await session.queue.put(+ RealtimeEvent(+ type="input_transcript", text="what time is it", is_final=True+ )+ )+ await _wait_until(lambda: sess._turn_id != "")+ # ...and now the transport simply goes quiet.++ await _wait_until(+ lambda: any(m.get("type") == "turn_complete" for m in jsons)+ )+ spoken = [m for m in jsons if m.get("type") == "error_spoken"]+ assert spoken, "a stalled turn must be reported out loud, never silently"+ assert spoken[0]["text"].strip(), "the notice must carry real words"+ assert sess._output_active is False+ assert sess._response_requested_for_turn is False+ assert sess._drop_provider_output_until_new_response is False+ assert await _microphone_reaches(sess, session)++ # The transport declares rebuild_on_transport_death, so ENDING the+ # stream would only make the pump reopen it. End the call instead.+ await sess.end(reason="test")+++async def test_the_stall_watchdog_never_fires_between_turns(monkeypatch):+ """AP-19 / BUG-032: a watchdog that outlives its unit of work aborts the+ NEXT one. This one is armed per turn and cancelled at every boundary, so+ an idle session between turns must stay completely quiet."""+ import jarvis.realtime.session as session_module++ monkeypatch.setattr(session_module, "_TURN_STALL_TIMEOUT_S", 0.15)+ monkeypatch.setattr(session_module, "_TURN_STALL_POLL_S", 0.02)++ provider = SubscriptionLikeProvider([])+ jsons = []+ sess = _half_duplex_session(provider, jsons=jsons)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ session = provider.session++ await session.queue.put(+ RealtimeEvent(type="input_transcript", text="hello", is_final=True)+ )+ await session.queue.put(+ RealtimeEvent(type="output_transcript_delta", text="Hi there.")+ )+ await session.queue.put(+ RealtimeEvent(type="audio_delta", audio=_pcm_chunk())+ )+ await session.queue.put(RealtimeEvent(type="turn_complete"))+ await _wait_until(+ lambda: any(m.get("type") == "turn_complete" for m in jsons)+ )++ # Idle for many watchdog windows with no turn open.+ await asyncio.sleep(0.6)+ assert sess._turn_stall_task is None or sess._turn_stall_task.done()+ assert not [m for m in jsons if m.get("type") == "error_spoken"], (+ "the watchdog fired between turns"+ )++ # The transport declares rebuild_on_transport_death, so ENDING the+ # stream would only make the pump reopen it. End the call instead.+ await sess.end(reason="test")+++async def test_a_discarded_rebuild_request_releases_the_microphone_marker():+ """The pending-rebuild marker gates handle_audio_frame all by itself.++ Only ``_rebuild_transport`` cleared it — precisely the path a discarded+ request skips — so a request that lost its race left every later+ microphone frame silently dropped for the rest of the call.+ """+ provider = SubscriptionLikeProvider([])+ sess = _half_duplex_session(provider)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ session = provider.session++ # A queued advised rebuild that the pump will refuse (the session is no+ # longer rebuildable by the time it is dequeued).+ sess._transport_rebuild_pending = session+ sess._failed.set()+ sess._transport_rebuild_requests.put_nowait((session, "advised reconnect"))++ await _wait_until(lambda: sess._transport_rebuild_pending is None)+ assert await _microphone_reaches(sess, session)++ await sess.end(reason="test")+++async def test_a_handoff_declined_through_provider_speech_closes_its_turn():+ """Both decline branches must leave the same state behind.++ The provider-speech branch returned without a boundary, and the withhold+ armed by the user's own speech edge then made _emit_audio drop the refusal+ audio too — so the user heard nothing and the turn stayed open with+ _output_active standing.+ """+ provider = SubscriptionLikeProvider([])+ jsons = []+ # brain=None => no deterministic delegate, and this transport cannot+ # declare tools either, so the handoff has nowhere to go.+ sess = _half_duplex_session(provider, jsons=jsons)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ session = provider.session++ await session.queue.put(RealtimeEvent(type="speech_started"))+ await session.queue.put(+ RealtimeEvent(+ type="handoff_requested",+ text="Open the settings view.",+ handoff_id="handoff-1",+ )+ )+ await _wait_until(lambda: bool(session.spoken))+ assert session.spoken, "the refusal must be voiced by the provider"+ await _wait_until(+ lambda: any(m.get("type") == "turn_complete" for m in jsons)+ )++ assert sess._drop_provider_output_until_new_response is False, (+ "the refusal is our own scrubbed text; the model withhold must not "+ "swallow it"+ )+ assert sess._output_active is False+ assert sess._response_requested_for_turn is False+ assert await _microphone_reaches(sess, session)++ # The transport declares rebuild_on_transport_death, so ENDING the+ # stream would only make the pump reopen it. End the call instead.+ await sess.end(reason="test")+++async def test_a_transport_rebuild_retires_the_answered_input_ids():+ """Input-item ids belong to the transport that issued them.++ A fresh provider session may restart its numbering, and a collision makes+ the duplicate-input guard swallow the next real utterance: the user speaks+ and no turn ever opens.+ """+ provider = SubscriptionLikeProvider([])+ sess = _half_duplex_session(provider)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ first = provider.session+ sess._response_requested_input_ids.add("item_0")++ assert await sess._rebuild_transport(detail="test rebuild") is True++ assert provider.session is not first+ assert sess._response_requested_input_ids == set()+ assert sess._transport_rebuild_pending is None+ await sess.end(reason="test")+++async def test_the_surface_is_told_the_call_language_and_the_start_budget():+ """The UI had no way to learn either.++ ``VoiceSessionStarted`` carries the language but is published for the+ browser surface only; ``audio_ready`` carried none at all, and a cold+ subscription handshake was pure dead air with no declared budget to show.+ One producer, one field name, one value.+ """+ provider = SubscriptionLikeProvider([])+ jsons = []+ sess = _half_duplex_session(provider, jsons=jsons)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})++ starting = next(m for m in jsons if m.get("type") == "audio_starting")+ ready = next(m for m in jsons if m.get("type") == "audio_ready")+ announced = next(m for m in jsons if m.get("type") == "language")++ assert ready["language"] == sess._language+ assert announced["language"] == sess._language+ assert starting["language"] == sess._language+ # The interim notice precedes the handshake it is announcing.+ assert jsons.index(starting) < jsons.index(ready)+ assert starting["handshake_budget_s"] >= provider.handshake_budget_s++ await sess.end(reason="test")+++async def test_a_self_initiated_interruption_is_not_read_as_user_speech():+ """Jarvis's own interrupt() echoing back must not arm the user-speech state.++ Every site that issues one already drained the gate and armed its own+ withhold; treating the echo as a barge-in blocked announcements, late+ action results and the readback watchdog against a user who never spoke.+ """+ provider = SubscriptionLikeProvider([])+ sess = _half_duplex_session(provider)+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ session = provider.session++ await session.queue.put(+ RealtimeEvent(type="interrupted", self_initiated=True)+ )+ await session.queue.put(+ RealtimeEvent(type="input_transcript", text="marker", is_final=True)+ )+ await _wait_until(lambda: sess._last_user_text == "marker")++ assert sess._user_speech_active is False+ assert session.interrupts == 0, (+ "a self-initiated interruption must not be answered with another one"+ )++ # The transport declares rebuild_on_transport_death, so ENDING the+ # stream would only make the pump reopen it. End the call instead.+ await sess.end(reason="test")