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.

feat(realtime): let Jarvis hear the user on transports that do not transcribe

Ruben Lütke0ce9ce7f6f68
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 2701ee6a91..e1500d19c0 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -267,6 +267,7 @@ class _CodexSubscriptionRealtimeSession:
thread_id: str,
answer_sdp: str,
audio_endpoint: Any = None,
+ input_transcriber: Any = None,
language: str = "en",
) -> None:
self._client = client
@@ -277,6 +278,10 @@ class _CodexSubscriptionRealtimeSession:
self.realtime_version = ""
# Owns the media path: ChatGPT-Live carries audio ONLY over WebRTC.
self._audio_endpoint = audio_endpoint
+ # ChatGPT-Live never transcribes the USER, so Jarvis does it locally.
+ # Without this the bar stays blank and every transcript-driven
+ # integration (delegate, wiki, project files, hang-up phrase) is deaf.
+ self._input_transcriber = input_transcriber
self._closed = False
self._last_input_item_id = ""
self._assistant_delta_text = ""
@@ -328,6 +333,8 @@ class _CodexSubscriptionRealtimeSession:
# the retired v1 protocol used is rejected outright ("Invalid value:
# 'input_audio.append'"). Microphone audio rides the media track.
self._audio_endpoint.send_pcm(pcm, sample_rate)
+ if self._input_transcriber is not None:
+ self._input_transcriber.feed(pcm, sample_rate)
async def receive(self) -> AsyncIterator[_ProviderEvent]:
# Stay below app-server's bounded subscription queue so a stalled
@@ -355,6 +362,29 @@ class _CodexSubscriptionRealtimeSession:
else:
await queue.put(("stream_end", None))
+ async def _pump_local_input() -> None:
+ """Feed locally recognized USER speech into the same event stream.
+
+ Other providers deliver these; ChatGPT-Live does not. Emitting
+ them here is what makes the bar show live text, the indicators
+ move, and every transcript-driven Jarvis integration work.
+ """
+ transcriber = self._input_transcriber
+ if transcriber is None:
+ return
+ try:
+ while True:
+ event = await transcriber.next_event()
+ if event is None:
+ return
+ await queue.put(("local_input", event))
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 - a deaf bar must not kill the call
+ log.warning(
+ "Local input transcription stream ended early", exc_info=True
+ )
+
async def _pump_media_audio() -> None:
"""Feed decoded RTP audio into the same normalized event stream.
@@ -406,9 +436,26 @@ class _CodexSubscriptionRealtimeSession:
_pump_media_audio(),
name=f"codex-realtime-media-{self._thread_id}",
)
+ input_task = asyncio.create_task(
+ _pump_local_input(),
+ name=f"codex-realtime-local-input-{self._thread_id}",
+ )
try:
while True:
queue_kind, payload = await queue.get()
+ if queue_kind == "local_input":
+ if payload.kind == "speech_started":
+ _cancel_completion()
+ completion_emitted = False
+ self._assistant_delta_text = ""
+ yield _ProviderEvent(type="speech_started")
+ else:
+ yield _ProviderEvent(
+ type="input_transcript",
+ text=payload.text,
+ is_final=payload.is_final,
+ )
+ continue
if queue_kind == "media_audio":
# Real provider audio keeps the turn alive exactly like the
# old sideband deltas did (quiescence timer, Orb state,
@@ -703,7 +750,7 @@ class _CodexSubscriptionRealtimeSession:
)
finally:
_cancel_completion()
- for pump in (pump_task, media_task):
+ for pump in (pump_task, media_task, input_task):
if not pump.done():
pump.cancel()
for task in tuple(timer_tasks):
@@ -712,6 +759,7 @@ class _CodexSubscriptionRealtimeSession:
await asyncio.gather(
pump_task,
media_task,
+ input_task,
*tuple(timer_tasks),
return_exceptions=True,
)
@@ -800,8 +848,12 @@ class _CodexSubscriptionRealtimeSession:
try:
await _close_subscription(self._subscription)
finally:
- if self._audio_endpoint is not None:
- await self._audio_endpoint.close()
+ try:
+ if self._input_transcriber is not None:
+ await self._input_transcriber.close()
+ finally:
+ if self._audio_endpoint is not None:
+ await self._audio_endpoint.close()
class CodexSubscriptionRealtimeProvider:
@@ -853,11 +905,13 @@ class CodexSubscriptionRealtimeProvider:
*,
client: Any = None,
audio_endpoint_factory: Any = None,
+ input_transcriber_factory: Any = None,
binary_path: str | None = None,
) -> None:
self._client = client
# Injected in tests; production builds the in-process WebRTC endpoint.
self._audio_endpoint_factory = audio_endpoint_factory
+ self._input_transcriber_factory = input_transcriber_factory
self._binary_path = str(binary_path or "").strip() or None
@classmethod
@@ -939,6 +993,26 @@ class CodexSubscriptionRealtimeProvider:
"Codex subscription realtime could not open a media path"
) from last_error
+ def _build_input_transcriber(self) -> Any:
+ """Local user-speech recognition, or ``None`` when unavailable.
+
+ ChatGPT-Live sends assistant transcripts only, so without this the
+ provider is deaf to Jarvis: the model talks, but the bar, the
+ indicators and every transcript-driven integration stay idle.
+ """
+ if self._input_transcriber_factory is not None:
+ return self._input_transcriber_factory()
+ try:
+ module = importlib.import_module("jarvis.realtime.input_transcription")
+ return module.LocalInputTranscriber(sample_rate=_INPUT_RATE)
+ except Exception: # noqa: BLE001 - the call still works, just deaf
+ log.warning(
+ "Local input transcription could not be started; the voice "
+ "answers but Jarvis-side transcript features stay idle",
+ exc_info=True,
+ )
+ return None
+
async def _open_session_once(
self, cfg: Any, ice_servers: Any
) -> _CodexSubscriptionRealtimeSession:
@@ -1026,6 +1100,7 @@ class CodexSubscriptionRealtimeProvider:
thread_id=thread_id,
answer_sdp=answer_sdp,
audio_endpoint=audio_endpoint,
+ input_transcriber=self._build_input_transcriber(),
language=str(getattr(cfg, "language", "en") or "en"),
)
# Identity FIRST: the model must know who it is and what this
diff --git a/jarvis/realtime/input_transcription.py b/jarvis/realtime/input_transcription.py
new file mode 100644
index 0000000000..4aa0701328
--- /dev/null
+++ b/jarvis/realtime/input_transcription.py
@@ -0,0 +1,244 @@
+"""Local user-speech transcription for realtime transports that lack it.
+
+Every Jarvis feature that reacts to what the USER said hangs off one event:
+``input_transcript``. The live bar text, the speaking indicators, the
+"auflegen" hang-up phrase, the echo guard, and — most importantly — the
+delegate that reaches the wiki, the project files and every Jarvis action.
+
+Most realtime providers transcribe user audio themselves. ChatGPT-Live does
+not: its notification stream carries assistant transcripts only (verified
+live — 14 assistant deltas, zero user deltas, no speech-start items), and its
+client-event vocabulary has no way to ask for one. Without this bridge that
+provider is deaf to Jarvis: the model answers, but Jarvis itself never learns
+what was said, so none of the integrations fire.
+
+So Jarvis transcribes the microphone audio it already owns, with the
+recognizer the user already configured, and emits the same events every
+other provider emits. "It is just another provider" then holds.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from dataclasses import dataclass
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+# Endpointing: deliberately simple and dependency-free. The far end runs its
+# own turn detection for the model's benefit; this endpointer only has to
+# decide when to hand one utterance to the recognizer.
+_SPEECH_RMS = 700.0
+_SILENCE_RMS = 500.0
+_SPEECH_START_MS = 120
+_SILENCE_END_MS = 700
+_PREROLL_MS = 300
+_MAX_UTTERANCE_MS = 20_000
+# Minimum VOICED audio — not buffer length. The buffer also holds pre-roll and
+# the trailing silence that closed the utterance, so measuring it would let a
+# cough or a keyboard knock buy a recognizer call and, worse, a transcript
+# that Jarvis would treat as something the user said.
+_MIN_VOICED_MS = 300
+
+
+@dataclass(frozen=True, slots=True)
+class InputTranscriptEvent:
+ """One normalized user-speech event for the provider event stream."""
+
+ kind: str # "speech_started" | "transcript"
+ text: str = ""
+ is_final: bool = False
+
+
+def _rms(pcm: bytes) -> float:
+ import numpy as np # noqa: PLC0415
+
+ if not pcm:
+ return 0.0
+ samples = np.frombuffer(pcm, dtype=np.int16)
+ if samples.size == 0:
+ return 0.0
+ return float(np.sqrt(np.mean(samples.astype(np.float32) ** 2)))
+
+
+class LocalInputTranscriber:
+ """Turn microphone PCM into ``input_transcript`` events."""
+
+ def __init__(self, *, sample_rate: int = 24_000, stt_factory: Any = None) -> None:
+ self._sample_rate = sample_rate
+ self._stt_factory = stt_factory
+ self._stt: Any = None
+ self._events: asyncio.Queue[InputTranscriptEvent | None] = asyncio.Queue(
+ maxsize=64
+ )
+ self._preroll: list[bytes] = []
+ self._preroll_ms = 0
+ self._utterance: list[bytes] = []
+ self._utterance_ms = 0
+ self._voiced_ms = 0
+ self._speech_ms = 0
+ self._silence_ms = 0
+ self._in_speech = False
+ self._tasks: set[asyncio.Task[None]] = set()
+ self._closed = False
+ self._unavailable_logged = False
+
+ # -- feeding -------------------------------------------------------
+ def feed(self, pcm: bytes, sample_rate: int) -> None:
+ """Accept one microphone chunk; never blocks the audio path."""
+ if self._closed or not pcm:
+ return
+ if sample_rate != self._sample_rate:
+ # The pipeline is fixed at one rate per session; a mismatch means
+ # a caller bug, and guessing would corrupt every duration below.
+ log.debug(
+ "Local input transcription ignoring a %d Hz chunk (session is %d Hz)",
+ sample_rate,
+ self._sample_rate,
+ )
+ return
+ duration_ms = int(len(pcm) / 2 / self._sample_rate * 1000)
+ if duration_ms <= 0:
+ return
+ level = _rms(pcm)
+
+ if not self._in_speech:
+ self._preroll.append(pcm)
+ self._preroll_ms += duration_ms
+ while self._preroll_ms > _PREROLL_MS and len(self._preroll) > 1:
+ dropped = self._preroll.pop(0)
+ self._preroll_ms -= int(
+ len(dropped) / 2 / self._sample_rate * 1000
+ )
+ if level >= _SPEECH_RMS:
+ self._speech_ms += duration_ms
+ if self._speech_ms >= _SPEECH_START_MS:
+ self._begin_utterance()
+ else:
+ self._speech_ms = 0
+ return
+
+ self._utterance.append(pcm)
+ self._utterance_ms += duration_ms
+ if level >= _SPEECH_RMS:
+ self._voiced_ms += duration_ms
+ if level < _SILENCE_RMS:
+ self._silence_ms += duration_ms
+ else:
+ self._silence_ms = 0
+ if (
+ self._silence_ms >= _SILENCE_END_MS
+ or self._utterance_ms >= _MAX_UTTERANCE_MS
+ ):
+ self._finish_utterance()
+
+ def _begin_utterance(self) -> None:
+ self._in_speech = True
+ # The frames that proved speech started are already voiced audio.
+ self._voiced_ms = self._speech_ms
+ self._speech_ms = 0
+ self._silence_ms = 0
+ self._utterance = list(self._preroll)
+ self._utterance_ms = self._preroll_ms
+ self._preroll = []
+ self._preroll_ms = 0
+ self._emit(InputTranscriptEvent(kind="speech_started"))
+
+ def _finish_utterance(self) -> None:
+ pcm = b"".join(self._utterance)
+ voiced_ms = self._voiced_ms
+ self._in_speech = False
+ self._utterance = []
+ self._utterance_ms = 0
+ self._voiced_ms = 0
+ self._silence_ms = 0
+ self._speech_ms = 0
+ if voiced_ms < _MIN_VOICED_MS or not pcm:
+ return
+ task = asyncio.create_task(
+ self._transcribe(pcm), name="realtime-local-input-transcribe"
+ )
+ self._tasks.add(task)
+ task.add_done_callback(self._tasks.discard)
+
+ # -- recognition ---------------------------------------------------
+ async def _ensure_stt(self) -> Any:
+ if self._stt is not None:
+ return self._stt
+ factory = self._stt_factory
+ if factory is None:
+
+ def factory() -> Any: # noqa: ANN202 - local default wiring
+ from jarvis.core.config import load_config # noqa: PLC0415
+ from jarvis.plugins.stt import build_stt_from_config # noqa: PLC0415
+
+ return build_stt_from_config(load_config().stt)
+
+ self._stt = await asyncio.to_thread(factory)
+ return self._stt
+
+ async def _transcribe(self, pcm: bytes) -> None:
+ started = time.monotonic()
+ try:
+ stt = await self._ensure_stt()
+ except Exception: # noqa: BLE001 - a missing recognizer must not kill the call
+ if not self._unavailable_logged:
+ self._unavailable_logged = True
+ log.warning(
+ "Local input transcription is unavailable; this provider's "
+ "voice still answers, but Jarvis-side features that need "
+ "the user's words stay idle",
+ exc_info=True,
+ )
+ return
+
+ from jarvis.core.protocols import AudioChunk # noqa: PLC0415
+
+ async def chunks(): # noqa: ANN202 - one-shot adapter
+ yield AudioChunk(
+ pcm=pcm, sample_rate=self._sample_rate, timestamp_ns=0, channels=1
+ )
+
+ try:
+ result = await stt.transcribe(chunks())
+ except Exception: # noqa: BLE001 - one failed utterance is not fatal
+ log.warning("Local input transcription failed for one utterance", exc_info=True)
+ return
+ text = str(getattr(result, "text", "") or "").strip()
+ if not text:
+ return
+ log.info(
+ "realtime local input transcript (%.0f ms): %r",
+ (time.monotonic() - started) * 1000,
+ text[:120],
+ )
+ self._emit(InputTranscriptEvent(kind="transcript", text=text, is_final=True))
+
+ def _emit(self, event: InputTranscriptEvent) -> None:
+ try:
+ self._events.put_nowait(event)
+ except asyncio.QueueFull: # noqa: S110 - a backed-up consumer already has plenty
+ log.debug("Local input transcript queue is full; dropping one event")
+
+ # -- consuming -----------------------------------------------------
+ async def next_event(self) -> InputTranscriptEvent | None:
+ return await self._events.get()
+
+ async def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ for task in tuple(self._tasks):
+ if not task.done():
+ task.cancel()
+ if self._tasks:
+ await asyncio.gather(*tuple(self._tasks), return_exceptions=True)
+ try:
+ self._events.put_nowait(None)
+ except asyncio.QueueFull: # noqa: S110 - the consumer will drain and see the end
+ pass
+
+
+__all__ = ["InputTranscriptEvent", "LocalInputTranscriber"]
diff --git a/tests/unit/realtime/test_input_transcription.py b/tests/unit/realtime/test_input_transcription.py
new file mode 100644
index 0000000000..da8c41d9ca
--- /dev/null
+++ b/tests/unit/realtime/test_input_transcription.py
@@ -0,0 +1,138 @@
+"""Local user-speech transcription for transports that do not supply it.
+
+ChatGPT-Live sends assistant transcripts only, so without these events the
+provider is deaf to Jarvis: the bar stays blank, the indicators never move,
+and every transcript-driven integration (delegate, wiki, project files,
+hang-up phrase) sits idle while the model happily talks.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import struct
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.realtime.input_transcription import LocalInputTranscriber
+
+RATE = 24_000
+CHUNK_SAMPLES = 480 # 20 ms
+
+
+def _loud(samples: int = CHUNK_SAMPLES) -> bytes:
+ return b"".join(
+ struct.pack("<h", int(9000 * math.sin(2 * math.pi * 180 * n / RATE)))
+ for n in range(samples)
+ )
+
+
+def _quiet(samples: int = CHUNK_SAMPLES) -> bytes:
+ return b"\x00\x00" * samples
+
+
+class _FakeSTT:
+ def __init__(self, text: str = "hallo welt") -> None:
+ self.text = text
+ self.calls = 0
+ self.seconds: list[float] = []
+
+ async def transcribe(self, audio): # noqa: ANN001 - protocol shape
+ self.calls += 1
+ total = 0
+ async for chunk in audio:
+ total += len(chunk.pcm)
+ self.seconds.append(total / 2 / RATE)
+ return SimpleNamespace(text=self.text)
+
+
+_EVENT_WAIT_S = 5.0
+
+
+async def _drain(transcriber: LocalInputTranscriber, expected: int):
+ events = []
+ for _ in range(expected):
+ events.append(
+ await asyncio.wait_for(transcriber.next_event(), timeout=_EVENT_WAIT_S)
+ )
+ return events
+
+
+async def test_speech_then_silence_yields_speech_start_and_transcript() -> None:
+ stt = _FakeSTT("Ben, durchsuche mein Wiki.")
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+
+ for _ in range(40): # 800 ms of speech
+ transcriber.feed(_loud(), RATE)
+ for _ in range(40): # 800 ms of silence closes the utterance
+ transcriber.feed(_quiet(), RATE)
+
+ events = await _drain(transcriber, 2)
+ assert events[0].kind == "speech_started"
+ assert events[1].kind == "transcript"
+ assert events[1].text == "Ben, durchsuche mein Wiki."
+ assert events[1].is_final is True
+ assert stt.calls == 1
+ await transcriber.close()
+
+
+async def test_a_blip_of_noise_never_becomes_a_transcript() -> None:
+ """A cough must not cost a recognizer call — or worse, become something
+ Jarvis believes the user said. The guard measures VOICED audio, because
+ the buffer also holds pre-roll and the silence that closed it: judging by
+ buffer length, 160 ms of noise looks like a whole sentence."""
+ stt = _FakeSTT()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+
+ for _ in range(8): # 160 ms of noise — real, but far too short to be speech
+ transcriber.feed(_loud(), RATE)
+ for _ in range(40):
+ transcriber.feed(_quiet(), RATE)
+ await asyncio.sleep(0.1)
+
+ assert stt.calls == 0
+ await transcriber.close()
+
+
+async def test_the_utterance_carries_its_own_onset() -> None:
+ """Pre-roll matters: without it the recognizer receives a sentence whose
+ first syllable was already spent proving that speech had started."""
+ stt = _FakeSTT()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+
+ for _ in range(50): # 1.0 s of speech
+ transcriber.feed(_loud(), RATE)
+ for _ in range(40):
+ transcriber.feed(_quiet(), RATE)
+ await _drain(transcriber, 2)
+
+ # Speech + pre-roll + the trailing silence that closed it.
+ assert stt.seconds and stt.seconds[0] > 1.0
+ await transcriber.close()
+
+
+async def test_a_failing_recognizer_never_kills_the_call() -> None:
+ 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)
+
+ first = await asyncio.wait_for(transcriber.next_event(), timeout=5.0)
+ assert first.kind == "speech_started"
+ # No transcript follows, and closing still completes cleanly.
+ await transcriber.close()
+ assert await asyncio.wait_for(transcriber.next_event(), timeout=5.0) is None