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(realtime): one spoken order stays one turn when the provider cuts it short

rubenluetke10-beepa4f63840428a
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index e3153e0d49..aed8e44940 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -215,6 +215,44 @@ _EMBEDDED_SILENCE_LOG_MS = 400.0
# full scale — comfortably above the AP-27 silence-ghost RMS empirics, far
# below any audible speech).
_EMBEDDED_SILENCE_PEAK = 200
+# The MICROPHONE's own evidence that the user has not finished talking.
+#
+# A realtime provider commits the input turn on ITS server VAD, and its
+# transcript describes audio that is already seconds old. Between those two
+# moments the session had no signal at all: the Gemini adapter emits no
+# ``speech_started``, and the desktop's local Silero detector is armed only
+# while JARVIS speaks. So while the user talked, an idle-looking session
+# believed the floor was free.
+#
+# Live 2026-08-13 11:19:08 and 11:19:48 — two consecutive calls chopped ONE
+# spoken order into three turns each, every cut landing on a filler pause
+# ("...Like for example um our competitors when" | "and our what I estimate"),
+# and EVERY fragment dispatched an executor of its own: the same coding pane
+# was briefed twice with a quarter of the sentence, and the third fragment
+# ("Netflix") earned an invented confirmation. The semantic continuation
+# guard (``_continues_executing_order``, 2026-08-12) caught none of them —
+# it asks whether the WORDS read as a continuation, when the load-bearing
+# fact is that the user never stopped speaking.
+#
+# ~2.4 % of full scale: far above headset room noise, far below any voiced
+# syllable. A floor set too HIGH degrades to the pre-fix behaviour; too LOW
+# only delays a dispatch until the bounded cap below. Both ends fail safe.
+_USER_VOICE_PEAK = 800
+# How long after the last voiced input frame the user still owns the floor.
+# Long enough to bridge the hesitations inside one sentence, short enough
+# that a genuinely finished utterance dispatches without a perceptible wait.
+_USER_SPEAKING_HOLD_S = 0.7
+# Ceiling on how long the microphone may hold back a delegated dispatch. A
+# stuck-open floor (a noisy room, a hot mic) must cost a bounded delay, never
+# a turn that is never executed at all.
+_USER_SPEAKING_DISPATCH_CAP_S = 4.0
+# After the microphone finally goes quiet, the provider's transcript for the
+# LAST words is still in flight — Gemini's input transcription ran ~2.6 s
+# behind its own commit in the 2026-08-13 forensics. A dispatch that fires
+# inside that gap still executes an order missing its tail, so a wait that
+# was held by the microphone settles for this long before giving up on the
+# remaining words. Paid ONLY on a turn the provider already cut short.
+_UTTERANCE_TAIL_SETTLE_S = 2.5
# In-place transport rebuild (BUG-071). A provider server may drop the duplex
# WebSocket at any time mid-call (live incident 2026-07-17 10:44: Gemini Live
# closed with ``1006 abnormal closure`` right as a 69 s surface-TTS fallback
@@ -1842,6 +1880,10 @@ class RealtimeVoiceSession:
self._last_audio_emit_monotonic = 0.0
self._last_audio_emit_turn = ""
self._embedded_silence_ms = 0.0
+ # Monotonic stamp of the last microphone frame that carried voice.
+ # The one local answer to "is the user talking right now" while the
+ # provider owns turn detection (see _USER_VOICE_PEAK).
+ self._last_voiced_input_monotonic = 0.0
self._loop_lag = _LoopLagProbe()
# A write-only transport stall does not necessarily wake the provider
# receive iterator. Queue a rebuild request for the long-lived pump so
@@ -2768,6 +2810,23 @@ class RealtimeVoiceSession:
muted_s,
)
+ def _user_is_speaking(self) -> bool:
+ """True while the microphone still carries the user's voice.
+
+ The provider's transcript is EVIDENCE ABOUT THE PAST — it describes
+ audio the server committed seconds ago. This predicate is about the
+ present, and it is the only thing that can tell a finished utterance
+ from a hesitation in the middle of one (see _USER_VOICE_PEAK).
+
+ Never consulted while Jarvis speaks: without half-duplex the mic
+ hears our own output, and speaker echo must not read as the user
+ holding the floor.
+ """
+ stamp = self._last_voiced_input_monotonic
+ if not stamp or self._output_active:
+ return False
+ return (time.monotonic() - stamp) < _USER_SPEAKING_HOLD_S
+
async def handle_audio_frame(self, pcm_native: bytes) -> None:
if self._ended or self._session is None or not pcm_native:
return
@@ -2805,6 +2864,10 @@ class RealtimeVoiceSession:
return
if not pcm16:
return
+ if not self._output_active and _pcm16_peak(pcm16) >= _USER_VOICE_PEAK:
+ # Measured on the frame we are about to FORWARD, so the floor
+ # tracks exactly the audio the provider is judging.
+ self._last_voiced_input_monotonic = time.monotonic()
target_session = self._session
try:
await asyncio.wait_for(
@@ -2934,6 +2997,17 @@ class RealtimeVoiceSession:
``False`` means the caller must keep the classic TTS path. Refusing a
busy session is load-bearing: Gemini text input interrupts generation,
while OpenAI permits only one unambiguous response lifecycle at a time.
+
+ "Busy" includes A USER WHO IS TALKING. Every other probe below reads
+ Jarvis-side state, and none of them is true while the user speaks a
+ long request the provider has not committed yet — so a background
+ result from an EARLIER call was injected straight into the middle of
+ a sentence (live 2026-08-13 11:20:03.224, delivery_id from the
+ session that had already ended). On the Live API text input ends the
+ audio turn, so that injection is what closed the sentence: the
+ transcript landed 2.6 s later as "…That when you want to" and the
+ half-order was executed. Refusing here costs nothing — the caller
+ speaks the result through the classic TTS path instead.
"""
cleaned = str(text or "").strip()
self.remember_announcement_context(
@@ -2949,6 +3023,8 @@ class RealtimeVoiceSession:
or self._failed.is_set()
or not callable(send_text)
or self._external_update is not None
+ or self._user_speech_active
+ or self._user_is_speaking()
or self._turn_id
or self._turn_has_activity()
or self._output_active
@@ -3203,8 +3279,24 @@ class RealtimeVoiceSession:
# an orchestrator action that is still producing its
# answer.
self._deferred_provider_speech_start = False
- await self._begin_user_speech_turn()
- await self._barge_in(interrupt_provider=False)
+ if self._user_is_speaking():
+ # ...unless the microphone says the user never
+ # stopped. A server-VAD edge inside ONE continuous
+ # utterance is a hesitation, not a new request:
+ # splitting here is what turned a single spoken
+ # order into three turns and three executors
+ # (live 2026-08-13 11:19/11:20, _USER_VOICE_PEAK).
+ # Keep the turn; the text below appends to it.
+ log.info(
+ "realtime[%s] provider committed a boundary "
+ "while the user is still audibly speaking — "
+ "continuing the same turn instead of "
+ "splitting it",
+ self.session_id,
+ )
+ else:
+ await self._begin_user_speech_turn()
+ await self._barge_in(interrupt_provider=False)
input_item_id = str(getattr(event, "item_id", "") or "")
input_already_answered = bool(
input_item_id
@@ -3623,12 +3715,23 @@ class RealtimeVoiceSession:
if not self._response_requested_for_turn:
await self._speak_pending_action_status()
else:
- # This branch runs on a FINAL input transcript,
- # so the utterance is provably over — no
- # boundary wait needed.
+ # A FINAL input transcript normally proves the
+ # utterance is over, and the boundary wait is
+ # skipped. It proves nothing while the microphone
+ # still carries the user's voice: the provider
+ # committed a hesitation, and dispatching now
+ # briefs an executor with a quarter of the
+ # sentence (live 2026-08-13 11:20:05 — "Can you
+ # please prompt Terminal T5 … That when you want
+ # to" went to the pane as a complete order).
+ # Withholding the finality lets
+ # _await_stable_input_boundary hold the dispatch
+ # until the mic goes quiet, by which time the
+ # later finals have grown turn_state.user_text
+ # into the whole request.
self._start_deterministic_delegate(
self._last_user_text,
- input_final=True,
+ input_final=not self._user_is_speaking(),
turn_plan=turn_plan,
)
if (
@@ -7109,7 +7212,8 @@ class RealtimeVoiceSession:
Mirrors ``deliver_announcement``: only an idle, healthy session can be
given a response of its own without cutting into live speech or racing
- an in-flight response lifecycle.
+ an in-flight response lifecycle — including the microphone probe, or
+ a late result would cut into the very sentence the user is speaking.
"""
return not (
self._ended
@@ -7117,6 +7221,7 @@ class RealtimeVoiceSession:
or self._failed.is_set()
or self._external_update is not None
or self._user_speech_active
+ or self._user_is_speaking()
or self._turn_id
or self._turn_has_activity()
or self._output_active
@@ -7741,36 +7846,86 @@ class RealtimeVoiceSession:
"""
stability_s = _DELEGATE_INPUT_BOUNDARY_WAIT_S
poll_s = max(min(_DELEGATE_INPUT_BOUNDARY_POLL_S, stability_s / 2), 0.01)
- deadline = (
- time.monotonic() + stability_s * _DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS
- )
- stable_since = time.monotonic()
+ started = time.monotonic()
+ deadline = started + stability_s * _DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS
+ # The microphone outranks every provider boundary while it still
+ # carries the user's voice — but only for a bounded stretch, so a
+ # noisy room delays an order instead of swallowing it.
+ mic_deadline = started + _USER_SPEAKING_DISPATCH_CAP_S
+ stable_since = started
+ settle_deadline = 0.0
last_transcript = self._last_user_text
+ mic_holding = False
+ mic_held_ever = False
while True:
try:
await asyncio.wait_for(
turn_state.input_boundary_ready.wait(),
timeout=poll_s,
)
- return
+ if not (
+ self._user_is_speaking() and time.monotonic() < mic_deadline
+ ):
+ return
except TimeoutError:
pass
now = time.monotonic()
- if self._last_user_text != last_transcript:
- last_transcript = self._last_user_text
+ if self._user_is_speaking() and now < mic_deadline:
+ # Whatever the provider committed, the user is mid-sentence.
+ # Re-arm the stability window: the words already accepted are
+ # a fragment, and the later finals still to arrive grow
+ # ``turn_state.user_text`` into the whole request.
+ if not mic_holding:
+ mic_holding = True
+ mic_held_ever = True
+ log.info(
+ "realtime[%s] deterministic delegate: holding the "
+ "dispatch — the microphone still carries the user's "
+ "voice after the provider closed its input turn",
+ self.session_id,
+ )
stable_since = now
- elif turn_state.input_final or now - stable_since >= stability_s:
- # ``input_final`` is boundary evidence by construction (the
- # provider already responded to this input), so it needs no
- # further stability margin — only the poll granularity.
- log.info(
- "realtime[%s] deterministic delegate: provider input "
- "boundary missing after %.2fs of stable local "
- "transcript; dispatching",
- self.session_id,
- now - stable_since,
- )
- return
+ last_transcript = self._last_user_text
+ else:
+ if mic_holding:
+ mic_holding = False
+ settle_deadline = now + _UTTERANCE_TAIL_SETTLE_S
+ log.info(
+ "realtime[%s] deterministic delegate: user stopped "
+ "speaking after a %.2fs hold; settling for the tail "
+ "transcript",
+ self.session_id,
+ now - started,
+ )
+ if self._last_user_text != last_transcript:
+ last_transcript = self._last_user_text
+ stable_since = now
+ elif (
+ turn_state.input_final and not mic_held_ever
+ ) or now - stable_since >= stability_s:
+ # ``input_final`` is boundary evidence by construction (the
+ # provider already responded to this input), so it needs no
+ # further stability margin — only the poll granularity.
+ # It is NOT trusted once the microphone has contradicted
+ # it: that finality is exactly what was wrong.
+ log.info(
+ "realtime[%s] deterministic delegate: provider input "
+ "boundary missing after %.2fs of stable local "
+ "transcript; dispatching",
+ self.session_id,
+ now - stable_since,
+ )
+ return
+ elif mic_held_ever and now >= settle_deadline:
+ log.info(
+ "realtime[%s] deterministic delegate: tail transcript "
+ "never arrived within %.1fs; dispatching the %d words "
+ "the utterance has",
+ self.session_id,
+ _UTTERANCE_TAIL_SETTLE_S,
+ len(str(self._last_user_text or "").split()),
+ )
+ return
if now >= deadline:
log.warning(
"realtime[%s] deterministic delegate: input transcript "
diff --git a/tests/unit/realtime/test_utterance_continuation.py b/tests/unit/realtime/test_utterance_continuation.py
new file mode 100644
index 0000000000..ee4eab50de
--- /dev/null
+++ b/tests/unit/realtime/test_utterance_continuation.py
@@ -0,0 +1,249 @@
+"""One spoken order stays ONE turn when the provider cuts it mid-sentence.
+
+Live forensic 2026-08-13 11:19:08 and 11:19:48: two consecutive Gemini Live
+calls each chopped a single spoken request into three turns at ordinary
+hesitation pauses, and every fragment dispatched an executor of its own. The
+guards here pin the microphone evidence that the session was missing.
+"""
+
+from __future__ import annotations
+
+import array
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.brain.turn_planner import TurnPath, TurnPlan, TurnReason
+from jarvis.realtime import session as session_module
+from jarvis.realtime.protocol import RealtimeEvent
+from jarvis.realtime.session import RealtimeVoiceSession
+
+_FRAGMENT_ONE = "Prompt terminal five to do a deep dive"
+_FRAGMENT_TWO = "into the prompting latency"
+
+
+def _voiced_frame(peak: int = 6_000, samples: int = 320) -> bytes:
+ """One 20 ms 16 kHz frame loud enough to count as the user's voice."""
+ return array.array("h", [peak, -peak] * (samples // 2)).tobytes()
+
+
+def _silent_frame(samples: int = 320) -> bytes:
+ return array.array("h", [0] * samples).tobytes()
+
+
+class _OrderBrain:
+ """Orchestrator-path brain that records exactly what it was asked."""
+
+ conversation_language = "en"
+
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+ self.called = asyncio.Event()
+
+ def plan_turn(self, _text: str) -> TurnPlan:
+ return TurnPlan(
+ path=TurnPath.ORCHESTRATOR,
+ reasons=frozenset({TurnReason.LOCAL_STATE}),
+ requires_evidence=True,
+ )
+
+ async def __call__(self, text: str) -> str:
+ self.calls.append(text)
+ self.called.set()
+ return "Sent it to the pane."
+
+
+class _ChoppedUtteranceWire:
+ """Gemini-shaped wire that commits its input in the middle of a sentence."""
+
+ session_id = "chopped-utterance-wire"
+ supports_tool_updates = False
+ creates_responses_automatically = True
+ isolates_response_generations = True
+
+ def __init__(self) -> None:
+ self.text_inputs: list[str] = []
+ self.interrupts = 0
+ self.first_final = asyncio.Event()
+ self.release_tail = asyncio.Event()
+ self.closed = asyncio.Event()
+
+ async def receive(self):
+ yield RealtimeEvent(
+ type="input_transcript",
+ text=_FRAGMENT_ONE,
+ is_final=True,
+ item_id="fragment-1",
+ )
+ self.first_final.set()
+ await self.release_tail.wait()
+ # The server VAD's own "the user started again" edge, exactly as the
+ # live calls produced it while the delegate was still running.
+ yield RealtimeEvent(type="interrupted")
+ yield RealtimeEvent(
+ type="input_transcript",
+ text=_FRAGMENT_TWO,
+ is_final=True,
+ item_id="fragment-2",
+ )
+ await self.closed.wait()
+
+ async def send_audio(self, _chunk: Any) -> None:
+ return None
+
+ async def update_session(self, **_kwargs: Any) -> None:
+ return None
+
+ async def request_response(self, **_kwargs: Any) -> None:
+ return None
+
+ async def send_text(self, text: str) -> None:
+ self.text_inputs.append(text)
+
+ async def truncate(self, _audio_end_ms: int) -> None:
+ return None
+
+ async def interrupt(self, **_kwargs: Any) -> None:
+ self.interrupts += 1
+
+ async def send_tool_result(self, *_args: Any) -> None:
+ return None
+
+ async def close(self) -> None:
+ self.closed.set()
+
+
+class _ChoppedUtteranceProvider:
+ name = "chopped-utterance"
+ supports_realtime = True
+ input_sample_rate = 16_000
+ output_sample_rate = 24_000
+
+ def __init__(self) -> None:
+ self.session = _ChoppedUtteranceWire()
+
+ async def can_open_duplex_session(self) -> bool:
+ return True
+
+ async def open_session(self, _config: Any) -> _ChoppedUtteranceWire:
+ return self.session
+
+
+def _config() -> SimpleNamespace:
+ return SimpleNamespace(
+ brain=SimpleNamespace(reply_language="en", providers={}),
+ stt=SimpleNamespace(language="auto"),
+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),
+ latency=SimpleNamespace(enabled=False),
+ )
+
+
+def _build_session(
+ provider: Any, brain: Any, *, session_id: str
+) -> RealtimeVoiceSession:
+ return RealtimeVoiceSession(
+ session_id=session_id,
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _message: asyncio.sleep(0),
+ provider=provider,
+ config=_config(),
+ bus=None,
+ browser_sample_rate=16_000,
+ surface="desktop",
+ brain=brain,
+ )
+
+
+def _fast_windows(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Scale the real-time windows down so the test stays sub-second."""
+ monkeypatch.setattr(session_module, "_USER_SPEAKING_HOLD_S", 0.12)
+ monkeypatch.setattr(session_module, "_USER_SPEAKING_DISPATCH_CAP_S", 3.0)
+ monkeypatch.setattr(session_module, "_UTTERANCE_TAIL_SETTLE_S", 0.4)
+ monkeypatch.setattr(session_module, "_DELEGATE_INPUT_BOUNDARY_WAIT_S", 0.2)
+ monkeypatch.setattr(session_module, "_DELEGATE_INPUT_BOUNDARY_POLL_S", 0.02)
+
+
+async def test_voiced_frames_mark_the_user_as_speaking() -> None:
+ provider = _ChoppedUtteranceProvider()
+ session = _build_session(provider, _OrderBrain(), session_id="mic-probe")
+ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ try:
+ assert session._user_is_speaking() is False
+ await session.handle_audio_frame(_silent_frame())
+ assert session._user_is_speaking() is False
+ await session.handle_audio_frame(_voiced_frame())
+ assert session._user_is_speaking() is True
+ # Speaker echo must never read as the user holding the floor.
+ session._output_active = True
+ assert session._user_is_speaking() is False
+ session._output_active = False
+ await asyncio.sleep(session_module._USER_SPEAKING_HOLD_S + 0.05)
+ assert session._user_is_speaking() is False
+ finally:
+ await session.end(reason="test")
+
+
+async def test_announcement_is_refused_while_the_user_speaks() -> None:
+ """The 11:20:03 injection that closed a sentence it had no business ending."""
+ provider = _ChoppedUtteranceProvider()
+ session = _build_session(provider, _OrderBrain(), session_id="announce-guard")
+ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ try:
+ await session.handle_audio_frame(_voiced_frame())
+ assert session._user_is_speaking() is True
+ delivered = await session.deliver_announcement(
+ text="Sent to T5, with eight files attached.",
+ language="en",
+ spoken_kind="completion",
+ detail="delivery_id=previous-session:turn-0",
+ )
+ assert delivered is False
+ assert provider.session.text_inputs == []
+ assert session._session_is_at_rest() is False
+ finally:
+ await session.end(reason="test")
+
+
+async def test_mid_sentence_commit_keeps_one_turn_and_one_executor(
+ _fast_windows: None,
+) -> None:
+ provider = _ChoppedUtteranceProvider()
+ brain = _OrderBrain()
+ session = _build_session(provider, brain, session_id="chopped-order")
+
+ async def _hold_the_floor(stop: asyncio.Event) -> None:
+ while not stop.is_set():
+ await session.handle_audio_frame(_voiced_frame())
+ await asyncio.sleep(0.02)
+
+ stop_speaking = asyncio.Event()
+ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ floor = asyncio.create_task(_hold_the_floor(stop_speaking))
+ try:
+ await asyncio.wait_for(provider.session.first_final.wait(), timeout=1.0)
+ # The provider closed its input turn, but the user talks on: the
+ # delegate must not have run on the fragment.
+ await asyncio.sleep(0.25)
+ assert brain.calls == []
+
+ provider.session.release_tail.set()
+ await asyncio.sleep(0.15)
+ stop_speaking.set()
+ await floor
+
+ await asyncio.wait_for(brain.called.wait(), timeout=3.0)
+ finally:
+ stop_speaking.set()
+ if not floor.done():
+ floor.cancel()
+ await session.end(reason="test")
+
+ assert len(brain.calls) == 1, f"one order, one executor: {brain.calls}"
+ assert _FRAGMENT_ONE in brain.calls[0]
+ assert _FRAGMENT_TWO in brain.calls[0]