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): stop recording hallucinated user transcripts as real turns
Ruben Lütke95e04d5f05db
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.pyindex e1500d19c0..b94fc87fda 100644--- a/jarvis/plugins/realtime/codex_subscription.py+++ b/jarvis/plugins/realtime/codex_subscription.py@@ -285,6 +285,9 @@ class _CodexSubscriptionRealtimeSession:self._closed = Falseself._last_input_item_id = ""self._assistant_delta_text = ""+ # The far end's own guess at what the user said. Kept as a live preview+ # and promoted to the recorded turn only if the local recognizer fails.+ self._server_user_preview = ""self._language = str(language or "en").strip().lower()self._active_codex_turn_id = ""self._handoff_interrupt_pending = False@@ -336,6 +339,27 @@ class _CodexSubscriptionRealtimeSession:if self._input_transcriber is not None:self._input_transcriber.feed(pcm, sample_rate)+ def _server_user_transcript_is_plausible(self) -> bool:+ """Was there microphone energy behind this server-side transcript?++ ChatGPT-Live transcribes the user itself, and like every recognizer it+ invents caption-style text on silence and on the echo of its own voice+ — observed live as "[exhale]", "blurred gray", "a_lee pixelated image",+ each recorded as something the user had said and answered in earnest.+ The test is word-agnostic (AP-27): the local endpointer already knows,+ from audio energy alone, whether anybody was speaking. Content rules+ cannot do this job — a hallucination is spelled like a sentence.+ """+ transcriber = self._input_transcriber+ if transcriber is None:+ # No endpointer, so no evidence either way; a deaf bar would be a+ # worse failure than an occasional invented line.+ return True+ checker = getattr(transcriber, "speech_recently", None)+ if not callable(checker):+ return True+ return bool(checker())+async def receive(self) -> AsyncIterator[_ProviderEvent]:# Stay below app-server's bounded subscription queue so a stalled# consumer propagates backpressure instead of silently buffering an@@ -448,8 +472,29 @@ class _CodexSubscriptionRealtimeSession:_cancel_completion()completion_emitted = Falseself._assistant_delta_text = ""+ self._server_user_preview = ""yield _ProviderEvent(type="speech_started")+ elif payload.kind == "transcript_failed":+ # The local recognizer could not deliver this+ # utterance. A turn the user really spoke must not+ # vanish, so the far end's preview is promoted — it+ # covers the same audio and passed the same energy+ # gate. Silence here would strand the whole turn.+ preview = self._server_user_preview+ self._server_user_preview = ""+ if preview:+ log.info(+ "Local recognizer delivered nothing; using the "+ "provider's own transcript for this turn"+ )+ yield _ProviderEvent(+ type="input_transcript",+ text=preview,+ is_final=True,+ item_id=self._last_input_item_id or None,+ )else:+ self._server_user_preview = ""yield _ProviderEvent(type="input_transcript",text=payload.text,@@ -558,6 +603,12 @@ class _CodexSubscriptionRealtimeSession:if not delta:continueif role == "user":+ if not self._server_user_transcript_is_plausible():+ log.debug(+ "Dropping a server user transcript delta that "+ "no microphone energy backs"+ )+ continue_cancel_completion()completion_emitted = Falseyield _ProviderEvent(@@ -583,12 +634,27 @@ class _CodexSubscriptionRealtimeSession:role = str(params.get("role", "") or "").lower()text = str(params.get("text", "") or "")if role == "user":+ if not self._server_user_transcript_is_plausible():+ log.info(+ "Ignoring a server user transcript that no "+ "microphone energy backs (%r)",+ text[:80],+ )+ continue_cancel_completion()completion_emitted = False+ # The local recognizer owns the FINAL text: it is the+ # one the user configured, with their dictionary and+ # bias prompt, and it is what every other Jarvis+ # feature hears. This stays a live preview unless that+ # recognizer reports it could not deliver.+ local_owns_final = self._input_transcriber is not None+ if local_owns_final:+ self._server_user_preview = textyield _ProviderEvent(type="input_transcript",text=text,- is_final=True,+ is_final=not local_owns_final,item_id=self._last_input_item_id or None,)elif role == "assistant":diff --git a/jarvis/realtime/input_transcription.py b/jarvis/realtime/input_transcription.pyindex 4aa0701328..f983cecf2d 100644--- a/jarvis/realtime/input_transcription.py+++ b/jarvis/realtime/input_transcription.py@@ -43,11 +43,18 @@ _MAX_UTTERANCE_MS = 20_000_MIN_VOICED_MS = 300+# How long after the microphone last carried real speech a server-side user+# transcript is still plausible. The far end transcribes with its own latency,+# so a genuine transcript trails the audio; a hallucinated one arrives while+# the user is silent or while the assistant itself is talking.+_SERVER_TRANSCRIPT_GRACE_MS = 2_000++@dataclass(frozen=True, slots=True)class InputTranscriptEvent:"""One normalized user-speech event for the provider event stream."""- kind: str # "speech_started" | "transcript"+ kind: str # "speech_started" | "transcript" | "transcript_failed"text: str = ""is_final: bool = False@@ -81,10 +88,28 @@ class LocalInputTranscriber:self._speech_ms = 0self._silence_ms = 0self._in_speech = False+ self._last_speech_end = 0.0self._tasks: set[asyncio.Task[None]] = set()self._closed = Falseself._unavailable_logged = False+ # -- voice activity ------------------------------------------------+ def speech_recently(self, grace_ms: int = _SERVER_TRANSCRIPT_GRACE_MS) -> bool:+ """Did the microphone actually carry speech just now?++ The answer is derived from audio ENERGY alone — never from the words+ of any transcript (AP-27). Server-side recognizers hallucinate+ caption-style text ("[exhale]", "pixelated image") on silence and on+ the echo of the assistant's own voice, and no spelling rule can+ separate those from a genuine short utterance. Their giveaway is+ physical: they arrive when nobody was making a sound.+ """+ if self._in_speech:+ return True+ if self._last_speech_end <= 0.0:+ return False+ return (time.monotonic() - self._last_speech_end) * 1000.0 <= grace_ms+# -- feeding -------------------------------------------------------def feed(self, pcm: bytes, sample_rate: int) -> None:"""Accept one microphone chunk; never blocks the audio path."""@@ -157,6 +182,9 @@ class LocalInputTranscriber:self._speech_ms = 0if voiced_ms < _MIN_VOICED_MS or not pcm:return+ # Only a qualifying utterance vouches for a server-side transcript; a+ # cough must not open the door that the energy gate just closed.+ self._last_speech_end = time.monotonic()task = asyncio.create_task(self._transcribe(pcm), name="realtime-local-input-transcribe")@@ -192,6 +220,7 @@ class LocalInputTranscriber:"the user's words stay idle",exc_info=True,)+ self._emit(InputTranscriptEvent(kind="transcript_failed"))returnfrom jarvis.core.protocols import AudioChunk # noqa: PLC0415@@ -205,9 +234,13 @@ class LocalInputTranscriber:result = await stt.transcribe(chunks())except Exception: # noqa: BLE001 - one failed utterance is not fatallog.warning("Local input transcription failed for one utterance", exc_info=True)+ self._emit(InputTranscriptEvent(kind="transcript_failed"))returntext = str(getattr(result, "text", "") or "").strip()if not text:+ # Real speech that produced no words: the far end's own transcript+ # of the same audio is now the best thing Jarvis has.+ self._emit(InputTranscriptEvent(kind="transcript_failed"))returnlog.info("realtime local input transcript (%.0f ms): %r",diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.pyindex 1410dd862d..f4a6515ec7 100644--- a/tests/unit/realtime/test_codex_subscription.py+++ b/tests/unit/realtime/test_codex_subscription.py@@ -583,9 +583,10 @@ async def test_notifications_normalize_audio_transcripts_and_boundaries() -> Non),])- session = await _provider(client).open_session(- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")- )+ # The user really was speaking, so their transcripts pass the energy gate.+ session = await _provider(+ client, input_transcriber_factory=lambda: _StubEndpointer(speaking=True)+ ).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))events = [event async for event in session.receive()]@@ -599,7 +600,10 @@ async def test_notifications_normalize_audio_transcripts_and_boundaries() -> Non"turn_complete","error",]- assert events[2].is_final is True+ # A live preview, not the recorded turn: with a local recognizer present it+ # owns the final text (see the server-transcript tests at the end of this+ # file for both halves of that rule).+ assert events[2].is_final is Falseassert events[2].item_id == "input-1"assert events[3].text == "hi"# A cleanly exhausted fake stream is still an unexpected transport death.@@ -899,9 +903,12 @@ async def test_normalization_queue_backpressures_and_pump_cleans_up() -> None:client = _Client()subscription = _CountingSubscription()client.subscription = subscription- session = await _provider(client).open_session(- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")- )+ # This subscription streams user transcripts forever, so the endpointer has+ # to report real speech - otherwise the energy gate rightly discards every+ # one of them and there is no backpressure left to measure.+ session = await _provider(+ client, input_transcriber_factory=lambda: _StubEndpointer(speaking=True)+ ).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))stream = session.receive()first = await anext(stream)@@ -1094,3 +1101,86 @@ async def test_ui_disconnect_after_answer_removes_answered_lease() -> None:assert (await registration.wait()).type == "release"assert await broker.pending_count() == 0assert await lease.answer("v=0\r\no=late-answer") is False+++class _StubEndpointer:+ """Stands in for the local endpointer's word-agnostic energy verdict."""++ def __init__(self, speaking: bool) -> None:+ self._speaking = speaking++ def speech_recently(self, grace_ms: int = 2000) -> bool: # noqa: ARG002+ return self._speaking++ def feed(self, pcm, sample_rate) -> None: # noqa: ANN001, ARG002 - protocol+ return None++ async def next_event(self): # noqa: ANN202 - delivers nothing in these tests+ await asyncio.sleep(3600)++ async def close(self) -> None:+ return None+++def _hallucination_client() -> "_Client":+ return _Client(+ [+ _Notification(+ "thread/realtime/transcript/delta",+ {"threadId": "thread-1", "role": "user", "delta": "a_lee "},+ ),+ _Notification(+ "thread/realtime/transcript/done",+ {+ "threadId": "thread-1",+ "role": "user",+ "text": "a_lee pixelated image",+ },+ ),+ ]+ )+++async def _user_transcripts(*, speaking: bool | None) -> list:+ transcriber = None if speaking is None else _StubEndpointer(speaking)+ session = await _provider(+ _hallucination_client(), input_transcriber_factory=lambda: transcriber+ ).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))+ events = [event async for event in session.receive()]+ await session.close()+ return [event for event in events if event.type == "input_transcript"]+++async def test_a_server_transcript_without_microphone_energy_never_becomes_a_turn():+ """The live defect: the user said "Hallo, was geht?" and Jarvis recorded+ "a_lee pixelated image" as their words, then answered it in earnest.+ ChatGPT-Live transcribes the user itself and, like every recognizer, writes+ caption-shaped text over silence and over the echo of its own voice. Only+ audio energy separates the two - a hallucination is spelled flawlessly+ (AP-27)."""+ assert await _user_transcripts(speaking=False) == []+++async def test_a_server_transcript_backed_by_speech_shows_up_live():+ """While the user really is speaking, the far end's transcript is the only+ live text there is - dropping it would leave the bar blank mid-sentence."""+ transcripts = await _user_transcripts(speaking=True)++ assert [event.text for event in transcripts] == [+ "a_lee ",+ "a_lee pixelated image",+ ]+ # The local recognizer - the user's own, with their dictionary and bias+ # prompt - owns the FINAL text, so these stay a live preview.+ assert not any(event.is_final for event in transcripts)+++async def test_without_a_local_recognizer_the_server_transcript_is_final():+ """A host with no usable recognizer still has to reach a routed turn, or+ the provider talks while every Jarvis integration sits idle."""+ finals = [event for event in await _user_transcripts(speaking=None) if event.is_final]++ assert [event.text for event in finals] == ["a_lee pixelated image"]diff --git a/tests/unit/realtime/test_input_transcription.py b/tests/unit/realtime/test_input_transcription.pyindex da8c41d9ca..12efbb7514 100644--- a/tests/unit/realtime/test_input_transcription.py+++ b/tests/unit/realtime/test_input_transcription.py@@ -136,3 +136,86 @@ async def test_a_failing_recognizer_never_kills_the_call() -> None:# No transcript follows, and closing still completes cleanly.await transcriber.close()assert await asyncio.wait_for(transcriber.next_event(), timeout=5.0) is None+++async def test_silence_never_vouches_for_a_server_transcript() -> None:+ """The energy gate the provider asks before trusting a server-side user+ transcript. ChatGPT-Live invented "[exhale]" and "a_lee pixelated image"+ while the user sat silent, and each was recorded as something they said."""+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _FakeSTT())++ assert transcriber.speech_recently() is False # nothing fed yet+ for _ in range(40):+ transcriber.feed(_quiet(), RATE)+ assert transcriber.speech_recently() is False+ await transcriber.close()+++async def test_real_speech_vouches_for_a_server_transcript() -> None:+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _FakeSTT())++ for _ in range(20): # mid-utterance+ transcriber.feed(_loud(), RATE)+ assert transcriber.speech_recently() is True++ for _ in range(40): # the silence that closes it+ transcriber.feed(_quiet(), RATE)+ # The far end transcribes with its own latency, so a genuine transcript+ # arrives shortly AFTER the audio stopped.+ assert transcriber.speech_recently() is True+ # ...but the vouching expires, so a transcript arriving much later in the+ # silence is no longer covered by it.+ await asyncio.sleep(0.05)+ assert transcriber.speech_recently(grace_ms=10) is False+ await transcriber.close()+++async def test_a_cough_does_not_vouch_for_a_server_transcript() -> None:+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _FakeSTT())++ for _ in range(8): # 160 ms — too short to be an utterance+ transcriber.feed(_loud(), RATE)+ for _ in range(40):+ transcriber.feed(_quiet(), RATE)+ assert transcriber.speech_recently() is False+ await transcriber.close()+++async def test_a_failed_recognizer_announces_itself() -> None:+ """Silence would strand the turn: the provider needs to know it must fall+ back to the far end's transcript (AP-30 - never fail without saying so)."""++ class _Broken:+ async def transcribe(self, audio): # noqa: ANN001 - protocol shape+ async for _ in audio:+ pass+ raise RuntimeError("recognizer exploded")++ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _Broken())+ for _ in range(40):+ transcriber.feed(_loud(), RATE)+ for _ in range(40):+ transcriber.feed(_quiet(), RATE)++ events = await _drain(transcriber, 2)+ assert events[0].kind == "speech_started"+ assert events[1].kind == "transcript_failed"+ await transcriber.close()+++async def test_an_empty_result_also_announces_itself() -> None:+ stt = _FakeSTT(" ")+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)+ for _ in range(40):+ transcriber.feed(_loud(), RATE)+ for _ in range(40):+ transcriber.feed(_quiet(), RATE)++ events = await _drain(transcriber, 2)+ assert events[1].kind == "transcript_failed"+ await transcriber.close()