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
feat(browser-voice): B2 slice 1 — BrowserVoiceSession backend core
Ruben Lütke52ba4afd4229
diff --git a/jarvis/browser_voice/__init__.py b/jarvis/browser_voice/__init__.pynew file mode 100644index 0000000000..887e0ce343--- /dev/null+++ b/jarvis/browser_voice/__init__.py@@ -0,0 +1,8 @@+"""Browser-microphone/speaker voice bridge (B2, DEEP-DIVE-AUDIT-2026-06-19).++The headless / €5-VPS voice path: a browser's AudioWorklet streams raw int16 PCM+over a WebSocket, the server runs the same STT -> Brain -> TTS turn loop the+telephony bridge uses (stdlib audioop only, NEVER sounddevice), and streams the+TTS PCM straight back as binary WS frames for Web Audio playback. This closes the+cloud-first gap where a browser user on a headless server could only text-chat.+"""diff --git a/jarvis/browser_voice/audio.py b/jarvis/browser_voice/audio.pynew file mode 100644index 0000000000..10b9ff7547--- /dev/null+++ b/jarvis/browser_voice/audio.py@@ -0,0 +1,24 @@+"""Stdlib-only codec/endpoint helpers for the browser-voice bridge.++This is a thin RE-EXPORT of the telephony bridge's audio layer — the same+``audioop``-based ``Resampler`` + the torch-free ``EnergyEndpointer`` — so the+browser path inherits any fix there for free and the dependency graph stays+readable. NEVER imports sounddevice / pyaudio: the browser owns the mic/speaker.+"""+from __future__ import annotations++from jarvis.telephony.audio import (+ STT_SAMPLE_RATE,+ TTS_SAMPLE_RATE,+ EnergyEndpointer,+ Resampler,+ resample_pcm16,+)++__all__ = [+ "EnergyEndpointer",+ "Resampler",+ "resample_pcm16",+ "STT_SAMPLE_RATE",+ "TTS_SAMPLE_RATE",+]diff --git a/jarvis/browser_voice/session.py b/jarvis/browser_voice/session.pynew file mode 100644index 0000000000..d6a216a0ba--- /dev/null+++ b/jarvis/browser_voice/session.py@@ -0,0 +1,245 @@+"""Per-connection browser-microphone voice session (B2).++Ports ``jarvis.telephony.session.TelephonyCallSession`` to browser audio. Raw+int16 PCM frames arrive over a WebSocket from an AudioWorklet (at the browser's+sample rate), are resampled to 16 kHz, endpointed by the torch-free+``EnergyEndpointer``, transcribed (STT), routed to the brain, scrubbed for voice,+synthesized (TTS, 24 kHz int16) and the audio bytes are streamed straight back as+binary WS frames for Web Audio playback.++Transport-decoupled like the telephony session: ``send_binary`` / ``send_json``+are injected async callables, so this is fully testable with fakes and a sink —+no socket, no models, no API key. Stdlib-only on the audio path: it NEVER imports+sounddevice, so a headless €5 VPS reaches the full voice experience.++Pipeline per turn (mirrors the mic + phone paths, AD-OE seams):++ inbound int16 PCM @ browser rate+ -> Resampler(browser_rate -> 16 kHz)+ -> EnergyEndpointer (VAD): accumulate until end-of-turn+ -> STT.transcribe_pcm(pcm, 16000) -> text+ -> ... brain turn ...+ -> scrub_for_voice (regex only, AP-11)+ -> TTS.synthesize(scrubbed) -> 24 kHz int16 PCM+ -> send_binary(pcm) per chunk (+ tts_start / tts_end control frames)+"""+from __future__ import annotations++import asyncio+import logging+import time+from collections.abc import Awaitable, Callable+from typing import Any++from jarvis.brain.output_filter import scrub_for_voice+from jarvis.browser_voice.audio import (+ STT_SAMPLE_RATE,+ TTS_SAMPLE_RATE,+ EnergyEndpointer,+ Resampler,+)++log = logging.getLogger("jarvis.browser_voice")++SendBinary = Callable[[bytes], Awaitable[None]]+SendJson = Callable[[dict[str, Any]], Awaitable[None]]+++class BrowserVoiceSession:+ """One browser microphone/speaker session over a ``/ws/audio`` socket.++ Args:+ session_id: opaque id for logging.+ send_binary: async sink for raw TTS PCM frames -> the browser.+ send_json: async sink for JSON control frames -> the browser.+ stt: object exposing ``transcribe_pcm(pcm, sample_rate=16000)``.+ brain: object exposing ``generate_stream(text) -> AsyncIterator[str]``.+ tts: object exposing ``synthesize(text, language_code=...) ->+ AsyncIterator[AudioChunk]`` (``.pcm`` int16, ``.sample_rate``).+ browser_sample_rate: the AudioWorklet capture rate (usually 48000).+ language_code: BCP-47 language pin for TTS.+ max_session_seconds: hard cap (advisory; the route enforces it).+ bus: optional EventBus (best-effort; unused on the hot path).+ """++ def __init__(+ self,+ *,+ session_id: str,+ send_binary: SendBinary,+ send_json: SendJson,+ stt: Any,+ brain: Any,+ tts: Any,+ browser_sample_rate: int = 48_000,+ language_code: str = "de-DE",+ max_session_seconds: int = 1800,+ bus: Any = None,+ ) -> None:+ self.session_id = session_id+ self._send_binary = send_binary+ self._send_json = send_json+ self._stt = stt+ self._brain = brain+ self._tts = tts+ self.browser_sample_rate = int(browser_sample_rate or STT_SAMPLE_RATE)+ self.language_code = language_code or "de-DE"+ self.max_session_seconds = max_session_seconds+ self._bus = bus++ self._in_resampler = Resampler(self.browser_sample_rate, STT_SAMPLE_RATE)+ self._endpointer = EnergyEndpointer(sample_rate=STT_SAMPLE_RATE)++ self._started_at = time.time()+ self._turns = 0+ self._speaking = False+ self._processing = False+ self._tts_task: asyncio.Task[None] | None = None+ self._turn_task: asyncio.Task[None] | None = None+ self._ended = False++ # -- public properties -------------------------------------------------++ @property+ def turns(self) -> int:+ return self._turns++ @property+ def ended(self) -> bool:+ return self._ended++ @property+ def duration_s(self) -> float:+ return time.time() - self._started_at++ # -- inbound audio -----------------------------------------------------++ async def handle_audio_frame(self, pcm_native: bytes) -> None:+ """Process one inbound binary WS frame (raw int16 at the browser rate)."""+ if self._ended or not pcm_native:+ return+ try:+ if self.browser_sample_rate == STT_SAMPLE_RATE:+ pcm16 = bytes(pcm_native)+ else:+ pcm16 = self._in_resampler.process(bytes(pcm_native))+ except Exception: # noqa: BLE001 — malformed/odd-length frame, drop it+ return+ utterance = self._endpointer.push(pcm16)+ if utterance is not None and not self._processing:+ # Run the turn off the inbound-frame path so we keep draining audio.+ self._turn_task = asyncio.create_task(self._run_turn(utterance))++ async def handle_control(self, msg: dict[str, Any]) -> None:+ """Process a JSON control frame from the browser."""+ kind = str(msg.get("type", ""))+ if kind == "audio_start":+ rate = int(msg.get("sample_rate", self.browser_sample_rate) or self.browser_sample_rate)+ if rate != self.browser_sample_rate:+ self.browser_sample_rate = rate+ self._in_resampler = Resampler(rate, STT_SAMPLE_RATE)+ lang = msg.get("language")+ if isinstance(lang, str) and lang:+ self.language_code = lang+ await self._send_json({"type": "audio_ready"})+ elif kind == "barge_in":+ await self._barge_in()+ elif kind == "audio_stop":+ await self.end(reason="client_stop")++ # -- turn loop ---------------------------------------------------------++ async def _run_turn(self, utterance_pcm16: bytes) -> None:+ if self._ended:+ return+ self._processing = True+ try:+ transcript = await self._transcribe(utterance_pcm16)+ text = (transcript or "").strip()+ if not text:+ return+ log.info("browser_voice[%s] user: %s", self.session_id, text)+ await self._send_json({"type": "transcript", "text": text, "is_final": True})++ response = await self._think(text)+ spoken = scrub_for_voice(response, language=self._lang_short()).cleaned+ if not spoken.strip():+ return+ self._tts_task = asyncio.create_task(self._speak(spoken))+ try:+ await self._tts_task+ except asyncio.CancelledError:+ pass # barge-in cancelled playback mid-stream — normal+ # A turn is "complete" once the response was (at least partly) spoken,+ # mirroring the telephony session's count semantics.+ self._turns += 1+ except Exception: # noqa: BLE001 — a turn failure must never kill the session+ log.warning("browser_voice[%s] turn failed", self.session_id, exc_info=True)+ finally:+ self._processing = False++ async def _transcribe(self, pcm16: bytes) -> str:+ result = await self._stt.transcribe_pcm(pcm16, sample_rate=STT_SAMPLE_RATE)+ return getattr(result, "text", "") or ""++ async def _think(self, text: str) -> str:+ chunks: list[str] = []+ async for chunk in self._brain.generate_stream(text):+ if chunk:+ chunks.append(chunk)+ return "".join(chunks)++ async def _speak(self, text: str) -> int:+ """Synthesize ``text`` and stream the raw PCM straight back as binary WS+ frames. The browser plays them via Web Audio at ``TTS_SAMPLE_RATE`` — no+ server resample (off-rate chunks are normalized to that rate). Returns+ the number of binary frames sent. Cancellable: a barge-in cancels the+ underlying task mid-stream.+ """+ from jarvis.browser_voice.audio import resample_pcm16 # noqa: PLC0415 — off-rate fallback++ self._speaking = True+ sent = 0+ try:+ await self._send_json({"type": "tts_start", "sample_rate": TTS_SAMPLE_RATE})+ async for chunk in self._tts.synthesize(text, language_code=self.language_code):+ pcm = getattr(chunk, "pcm", b"")+ rate = int(getattr(chunk, "sample_rate", TTS_SAMPLE_RATE) or TTS_SAMPLE_RATE)+ if not pcm:+ continue+ if rate != TTS_SAMPLE_RATE:+ pcm = resample_pcm16(pcm, rate, TTS_SAMPLE_RATE)+ await self._send_binary(pcm)+ sent += 1+ await self._send_json({"type": "tts_end"})+ finally:+ self._speaking = False+ return sent++ # -- barge-in / lifecycle ---------------------------------------------++ async def _barge_in(self) -> None:+ """Cancel in-flight TTS playback (the browser owns its playback queue)."""+ if self._tts_task is not None and not self._tts_task.done():+ self._tts_task.cancel()+ self._speaking = False++ async def end(self, *, reason: str = "") -> None:+ """End the session: cancel playback, mark ended."""+ if self._ended:+ return+ self._ended = True+ if self._tts_task is not None and not self._tts_task.done():+ self._tts_task.cancel()+ if self._turn_task is not None and not self._turn_task.done():+ self._turn_task.cancel()+ log.info(+ "browser_voice[%s] ended: reason=%s turns=%d dur=%.1fs",+ self.session_id,+ reason,+ self._turns,+ self.duration_s,+ )++ def _lang_short(self) -> str:+ return (self.language_code or "de-DE").split("-", 1)[0].lower()diff --git a/tests/unit/browser_voice/__init__.py b/tests/unit/browser_voice/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/browser_voice/test_session.py b/tests/unit/browser_voice/test_session.pynew file mode 100644index 0000000000..853f7fb1f3--- /dev/null+++ b/tests/unit/browser_voice/test_session.py@@ -0,0 +1,189 @@+"""B2 BrowserVoiceSession — the headless/VPS browser-microphone voice path.++Mirrors tests/unit/telephony/test_session.py: drive synthetic PCM16 through the+session with the telephony Fakes (no models, no socket, no sounddevice) and+assert the STT->Brain->TTS turn streams raw PCM back + the JSON control frames.++Seam-level only — the browser AudioWorklet capture + Web Audio playback are+browser-only and NOT unit-testable here; this proves the server session loop.+"""+from __future__ import annotations++import asyncio+import math+import struct++from jarvis.browser_voice.audio import STT_SAMPLE_RATE+from jarvis.browser_voice.session import BrowserVoiceSession+from jarvis.core.protocols import AudioChunk+from tests.fakes.fake_telephony_stack import FakeBrain, FakeSTT, FakeTTS+++class _SlowTTS:+ """A TTS that yields 24 kHz chunks with a real delay between them, so+ `_speak` stays mid-stream long enough to test barge-in / end deterministically."""++ name = "slow-tts"+ supports_streaming = True++ def __init__(self, chunks: int = 20, delay: float = 0.02) -> None:+ self._chunks = chunks+ self._delay = delay+ self.calls: list[tuple[str, str]] = []++ async def synthesize(self, text, language_code="de-DE", voice=None):+ self.calls.append((text, language_code))+ for _ in range(self._chunks):+ await asyncio.sleep(self._delay)+ yield AudioChunk(pcm=b"\x01\x00" * 240, sample_rate=24_000, timestamp_ns=0, channels=1)+++def _pcm16_frame(amp: int, ms: int = 20, rate: int = STT_SAMPLE_RATE, freq: int = 300) -> bytes:+ """One raw int16 mono PCM frame at `rate` (what the browser AudioWorklet sends)."""+ n = rate * ms // 1000+ if amp == 0:+ return b"\x00\x00" * n+ return b"".join(+ struct.pack("<h", int(amp * math.sin(2 * math.pi * freq * i / rate)))+ for i in range(n)+ )+++class _Sink:+ def __init__(self) -> None:+ self.binary: list[bytes] = []+ self.json: list[dict] = []++ async def send_binary(self, data: bytes) -> None:+ self.binary.append(bytes(data))++ async def send_json(self, msg: dict) -> None:+ self.json.append(msg)++ def json_of(self, kind: str) -> list[dict]:+ return [m for m in self.json if m.get("type") == kind]+++def _make_session(sink, *, stt=None, brain=None, tts=None, rate=STT_SAMPLE_RATE, **kw):+ params = dict(+ session_id="bv1",+ send_binary=sink.send_binary,+ send_json=sink.send_json,+ stt=stt or FakeSTT(["Wie spät ist es?"]),+ brain=brain or FakeBrain("Es ist vierzehn Uhr."),+ tts=tts or FakeTTS(ms_per_char=2),+ browser_sample_rate=rate,+ language_code="de-DE",+ )+ params.update(kw)+ return BrowserVoiceSession(**params)+++async def _drive_one_utterance(session, rate=STT_SAMPLE_RATE) -> None:+ """Feed silence -> speech -> silence so the endpointer fires one turn, then+ await the spawned turn task (mirrors the telephony driving helper)."""+ session._endpointer.silence_ms = 100+ session._endpointer.min_speech_ms = 60+ for _ in range(2):+ await session.handle_audio_frame(_pcm16_frame(0, rate=rate))+ for _ in range(8):+ await session.handle_audio_frame(_pcm16_frame(15000, rate=rate))+ for _ in range(10):+ await session.handle_audio_frame(_pcm16_frame(0, rate=rate))+ for _ in range(200):+ await asyncio.sleep(0)+ if session.turns >= 1:+ break+ await asyncio.sleep(0.01)+++async def _drive_until_speaking(session) -> None:+ session._endpointer.silence_ms = 100+ session._endpointer.min_speech_ms = 60+ for _ in range(2):+ await session.handle_audio_frame(_pcm16_frame(0))+ for _ in range(8):+ await session.handle_audio_frame(_pcm16_frame(15000))+ for _ in range(10):+ await session.handle_audio_frame(_pcm16_frame(0))+ for _ in range(60):+ await asyncio.sleep(0)+ if session._speaking:+ break+ await asyncio.sleep(0.01)+++async def test_full_turn_streams_binary_tts_back():+ sink = _Sink()+ session = _make_session(sink)+ await _drive_one_utterance(session)+ assert session.turns == 1+ assert len(sink.binary) > 0 # raw PCM frames streamed back to the browser+ assert all(isinstance(b, bytes) and b for b in sink.binary)+ assert sink.json_of("tts_start") and sink.json_of("tts_end")+++async def test_transcript_control_frame_sent():+ sink = _Sink()+ session = _make_session(sink, stt=FakeSTT(["Hallo Jarvis"]))+ await _drive_one_utterance(session)+ tr = sink.json_of("transcript")+ assert tr and tr[0]["text"] == "Hallo Jarvis" and tr[0]["is_final"] is True+++async def test_brain_receives_transcript():+ sink = _Sink()+ brain = FakeBrain("ok")+ session = _make_session(sink, stt=FakeSTT(["Wie geht es dir?"]), brain=brain)+ await _drive_one_utterance(session)+ assert "Wie geht es dir?" in brain.prompts+++async def test_empty_transcript_skips_turn():+ sink = _Sink()+ session = _make_session(sink, stt=FakeSTT([""]))+ await _drive_one_utterance(session)+ assert session.turns == 0+ assert sink.binary == []+++async def test_audio_start_sets_rate_and_language():+ sink = _Sink()+ session = _make_session(sink, rate=16_000)+ await session.handle_control(+ {"type": "audio_start", "sample_rate": 48_000, "language": "en-US"}+ )+ assert session.browser_sample_rate == 48_000+ assert session.language_code == "en-US"+ assert sink.json_of("audio_ready")+++async def test_resamples_48k_to_16k_for_stt():+ sink = _Sink()+ stt = FakeSTT(["x"])+ session = _make_session(sink, stt=stt, rate=48_000)+ await _drive_one_utterance(session, rate=48_000)+ assert stt.calls and all(sr == STT_SAMPLE_RATE for (_n, sr) in stt.calls)+++async def test_barge_in_cancels_tts():+ sink = _Sink()+ session = _make_session(sink, tts=_SlowTTS()) # yields with a real delay+ await _drive_until_speaking(session)+ assert session._speaking+ await session.handle_control({"type": "barge_in"})+ await asyncio.sleep(0)+ task = session._tts_task+ assert task is None or task.cancelled() or task.done()+ assert session._speaking is False+++async def test_end_cancels_tasks():+ sink = _Sink()+ session = _make_session(sink, tts=_SlowTTS())+ await _drive_until_speaking(session)+ await session.end(reason="test")+ assert session.ended+ await asyncio.sleep(0)+ task = session._tts_task+ assert task is None or task.cancelled() or task.done()