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 2 — /ws/audio route + server wiring; address slice-1 review
Ruben Lütkeac7642846255
diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pynew file mode 100644index 0000000000..6fbf1e8892--- /dev/null+++ b/jarvis/browser_voice/route.py@@ -0,0 +1,145 @@+"""FastAPI ``/ws/audio`` route for the browser-microphone voice bridge (B2 slice 2).++A per-connection WebSocket that receives raw int16 PCM (binary frames) + JSON+control frames from the browser and runs a :class:`BrowserVoiceSession`+(STT -> Brain -> TTS, no sounddevice). Mirrors the telephony ``/media`` route's+provider resolution (shared STT/TTS + a per-connection brain, with a test-factory+seam) and the ``/ws`` AP-20 receive-loop discipline: a ``RuntimeError`` on an+unclean disconnect is terminal — ``break``, never ``continue``.+"""+from __future__ import annotations++import json+import logging+from typing import Any+from uuid import uuid4++from fastapi import APIRouter, WebSocket, WebSocketDisconnect++from jarvis.core import config as cfg_mod++log = logging.getLogger("jarvis.browser_voice.route")++router = APIRouter()++# BCP-47 from the brain.reply_language pin (de/en/es) — falls back to de-DE.+_LANG_MAP = {"de": "de-DE", "en": "en-US", "es": "es-ES"}+++def _browser_voice_enabled(cfg: Any) -> bool:+ """Default ON: a VPS browser user gets voice unless [browser_voice] disables it."""+ bv = getattr(cfg, "browser_voice", None)+ if bv is None:+ return True+ return bool(getattr(bv, "enabled", True))+++def _resolve_language(cfg: Any) -> str:+ pin = getattr(getattr(cfg, "brain", None), "reply_language", "") or ""+ if not pin or pin == "auto":+ return "de-DE"+ return _LANG_MAP.get(pin, pin)+++def _build_browser_session(+ *, state: Any, cfg: Any, bus: Any, session_id: str, send_binary: Any, send_json: Any+) -> Any:+ """Build a BrowserVoiceSession with shared STT/TTS + a per-connection brain.++ Returns ``None`` when the speech stack can't be constructed (e.g. no provider+ key) — the caller then closes the socket cleanly. A test can inject+ ``state.browser_voice_session_factory`` to bypass the real provider build.+ """+ factory = getattr(state, "browser_voice_session_factory", None)+ if factory is not None:+ return factory(session_id=session_id, send_binary=send_binary, send_json=send_json)+ try:+ from jarvis.brain.factory import build_default_brain+ from jarvis.browser_voice.session import BrowserVoiceSession+ from jarvis.plugins.stt import build_stt_from_config+ from jarvis.plugins.tts import build_tts_from_config++ stt = build_stt_from_config(cfg.stt)+ tts = build_tts_from_config(cfg.tts)+ brain = build_default_brain(bus=bus, tier="router")+ except Exception as exc: # noqa: BLE001 — missing key / unbuildable stack+ log.warning("browser_voice: speech stack build failed: %s", exc)+ return None+ return BrowserVoiceSession(+ session_id=session_id,+ send_binary=send_binary,+ send_json=send_json,+ stt=stt,+ brain=brain,+ tts=tts,+ language_code=_resolve_language(cfg),+ bus=bus,+ )++[email protected]("/ws/audio")+async def browser_voice_ws(ws: WebSocket) -> None:+ """Browser-microphone voice socket: run the per-connection turn loop."""+ await ws.accept()++ app = ws.scope.get("app")+ state = app.state if app is not None else None+ bus = getattr(state, "bus", None)+ cfg = getattr(state, "config", None) or getattr(state, "cfg", None)+ if cfg is None:+ try:+ cfg = cfg_mod.load_config()+ except Exception: # noqa: BLE001+ cfg = None++ if cfg is not None and not _browser_voice_enabled(cfg):+ await ws.close(code=1008, reason="browser voice disabled")+ return++ session_id = str(uuid4())++ async def _send_binary(data: bytes) -> None:+ await ws.send_bytes(data)++ async def _send_json(msg: dict[str, Any]) -> None:+ await ws.send_json(msg)++ session = _build_browser_session(+ state=state,+ cfg=cfg,+ bus=bus,+ session_id=session_id,+ send_binary=_send_binary,+ send_json=_send_json,+ )+ if session is None:+ await ws.close(code=1011, reason="speech stack unavailable")+ return++ try:+ while True:+ try:+ msg = await ws.receive()+ except WebSocketDisconnect:+ break+ except RuntimeError:+ # AP-20: an unclean disconnect raises RuntimeError (not+ # WebSocketDisconnect) — terminal, break (never continue).+ break+ if msg.get("type") == "websocket.disconnect":+ break+ data = msg.get("bytes")+ if data is not None:+ await session.handle_audio_frame(data)+ continue+ text = msg.get("text")+ if text is not None:+ try:+ control = json.loads(text)+ except Exception: # noqa: BLE001 — malformed control frame, drop it+ log.debug("browser_voice: dropping malformed control frame")+ continue+ if isinstance(control, dict):+ await session.handle_control(control)+ finally:+ await session.end(reason="ws_closed")diff --git a/jarvis/browser_voice/session.py b/jarvis/browser_voice/session.pyindex d6a216a0ba..34067ae305 100644--- a/jarvis/browser_voice/session.py+++ b/jarvis/browser_voice/session.py@@ -128,7 +128,10 @@ class BrowserVoiceSession: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))+ self._turn_task = asyncio.create_task(+ self._run_turn(utterance), name=f"bv-turn-{self.session_id}"+ )+ self._turn_task.add_done_callback(self._on_turn_done)async def handle_control(self, msg: dict[str, Any]) -> None:"""Process a JSON control frame from the browser."""@@ -138,6 +141,9 @@ class BrowserVoiceSession:if rate != self.browser_sample_rate:self.browser_sample_rate = rateself._in_resampler = Resampler(rate, STT_SAMPLE_RATE)+ # Drop any audio buffered at the old rate so STT never sees a+ # rate-mismatched blob across a reconnect / rate change.+ self._endpointer.reset()lang = msg.get("language")if isinstance(lang, str) and lang:self.language_code = lang@@ -147,6 +153,15 @@ class BrowserVoiceSession:elif kind == "audio_stop":await self.end(reason="client_stop")+ def _on_turn_done(self, task: asyncio.Task[None]) -> None:+ """Surface a turn task that died outside _run_turn's own guard (a bare+ create_task otherwise loses the traceback with no session context)."""+ if task.cancelled():+ return+ exc = task.exception()+ if exc is not None:+ log.warning("browser_voice[%s] turn task raised", self.session_id, exc_info=exc)+# -- turn loop ---------------------------------------------------------async def _run_turn(self, utterance_pcm16: bytes) -> None:@@ -157,6 +172,9 @@ class BrowserVoiceSession:transcript = await self._transcribe(utterance_pcm16)text = (transcript or "").strip()if not text:+ # End-of-turn fired but nothing transcribable — let the browser+ # reset any "thinking" affordance (AD-OE6: never a silent drop).+ await self._send_json({"type": "vad_silence"})returnlog.info("browser_voice[%s] user: %s", self.session_id, text)await self._send_json({"type": "transcript", "text": text, "is_final": True})@@ -219,10 +237,20 @@ class BrowserVoiceSession:# -- barge-in / lifecycle ---------------------------------------------async def _barge_in(self) -> None:- """Cancel in-flight TTS playback (the browser owns its playback queue)."""+ """Cancel in-flight TTS playback and tell the browser to flush its queue.++ On a mid-stream cancel the ``_speak`` coroutine never reaches its+ ``tts_end``; without a signal the browser's playback queue would hang+ (review BLOCKER). The canceller emits ``tts_cancel`` — best-effort,+ since the socket may already be closing.+ """if self._tts_task is not None and not self._tts_task.done():self._tts_task.cancel()self._speaking = False+ try:+ await self._send_json({"type": "tts_cancel"})+ except Exception: # noqa: BLE001, S110 — best-effort on a closing socket+ passasync def end(self, *, reason: str = "") -> None:"""End the session: cancel playback, mark ended."""@@ -242,4 +270,7 @@ class BrowserVoiceSession:)def _lang_short(self) -> str:- return (self.language_code or "de-DE").split("-", 1)[0].lower()+ # scrub_for_voice only knows the runtime locales de/en/es (AP-11, regex+ # only); an unknown tag would silently apply the wrong blacklist.+ tag = (self.language_code or "de-DE").split("-", 1)[0].lower()+ return tag if tag in {"de", "en", "es"} else "de"diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 055ca703b8..2c23e9e370 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -281,6 +281,12 @@ class WebServer:from jarvis.telephony.status import TelephonyManagerapp.state.telephony_manager = TelephonyManager()+ # Browser-microphone voice bridge (B2): /ws/audio — the headless/VPS+ # voice path via the browser's own mic/speaker, no sounddevice. Always+ # mounted; gated by [browser_voice].enabled (default on) at connect time.+ from jarvis.browser_voice.route import router as browser_voice_router++ app.include_router(browser_voice_router)app.include_router(sub_agents_router)app.include_router(outputs_router)# Socials section — project social-media links (pure file store, no Brain dep).diff --git a/tests/unit/browser_voice/test_route.py b/tests/unit/browser_voice/test_route.pynew file mode 100644index 0000000000..f9b0343790--- /dev/null+++ b/tests/unit/browser_voice/test_route.py@@ -0,0 +1,116 @@+"""B2 slice 2 — the /ws/audio route receive loop (fake WS, no real server).++Drives ``browser_voice_ws()`` directly with a fake WebSocket + an injected+session factory: binary frames dispatch to handle_audio_frame, JSON control+frames to handle_control, the AP-20 RuntimeError-break is terminal, and end()+runs in the finally. The real socket + AudioWorklet are browser-only (slice 3).+"""+from __future__ import annotations++from types import SimpleNamespace++from fastapi import WebSocketDisconnect++from jarvis.browser_voice.route import browser_voice_ws+++class _RecSession:+ def __init__(self) -> None:+ self.audio: list[bytes] = []+ self.controls: list[dict] = []+ self.ended = False++ async def handle_audio_frame(self, data: bytes) -> None:+ self.audio.append(bytes(data))++ async def handle_control(self, msg: dict) -> None:+ self.controls.append(msg)++ async def end(self, reason: str = "") -> None:+ self.ended = True+++class _FakeWS:+ def __init__(self, incoming, *, state) -> None:+ self._incoming = list(incoming)+ self.scope = {"app": SimpleNamespace(state=state)}+ self.accepted = False+ self.sent_bytes: list[bytes] = []+ self.sent_json: list[dict] = []+ self.closed = None++ async def accept(self) -> None:+ self.accepted = True++ async def receive(self) -> dict:+ if self._incoming:+ return self._incoming.pop(0)+ raise WebSocketDisconnect()++ async def send_bytes(self, b) -> None:+ self.sent_bytes.append(bytes(b))++ async def send_json(self, m) -> None:+ self.sent_json.append(m)++ async def close(self, code: int = 1000, reason: str = "") -> None:+ self.closed = (code, reason)+++def _state(session, cfg=None):+ return SimpleNamespace(+ config=cfg if cfg is not None else SimpleNamespace(), # no browser_voice -> enabled+ bus=None,+ browser_voice_session_factory=lambda **kw: session,+ )+++async def test_route_dispatches_binary_and_control_then_ends():+ rec = _RecSession()+ ws = _FakeWS(+ [+ {"type": "websocket.receive", "bytes": b"\x01\x00\x02\x00"},+ {"type": "websocket.receive", "text": '{"type":"barge_in"}'},+ {"type": "websocket.disconnect", "code": 1000},+ ],+ state=_state(rec),+ )+ await browser_voice_ws(ws)+ assert ws.accepted+ assert rec.audio == [b"\x01\x00\x02\x00"]+ assert rec.controls == [{"type": "barge_in"}]+ assert rec.ended # end() ran in the finally+++async def test_route_closes_when_disabled():+ rec = _RecSession()+ cfg = SimpleNamespace(browser_voice=SimpleNamespace(enabled=False))+ ws = _FakeWS([], state=_state(rec, cfg=cfg))+ await browser_voice_ws(ws)+ assert ws.closed is not None and ws.closed[0] == 1008+ assert rec.audio == [] # never reached the loop+++async def test_route_closes_when_speech_stack_unavailable():+ state = SimpleNamespace(+ config=SimpleNamespace(),+ bus=None,+ browser_voice_session_factory=lambda **kw: None, # build failed (no key)+ )+ ws = _FakeWS([], state=state)+ await browser_voice_ws(ws)+ assert ws.closed is not None and ws.closed[0] == 1011+++async def test_route_breaks_on_runtimeerror():+ # AP-20: an unclean disconnect raises RuntimeError (not WebSocketDisconnect)+ # -> terminal break, end() still runs.+ rec = _RecSession()++ class _RaisingWS(_FakeWS):+ async def receive(self) -> dict:+ raise RuntimeError("WebSocket is not connected")++ ws = _RaisingWS([], state=_state(rec))+ await browser_voice_ws(ws)+ assert rec.endeddiff --git a/tests/unit/browser_voice/test_session.py b/tests/unit/browser_voice/test_session.pyindex 853f7fb1f3..f7972a0360 100644--- a/tests/unit/browser_voice/test_session.py+++ b/tests/unit/browser_voice/test_session.py@@ -81,7 +81,9 @@ def _make_session(sink, *, stt=None, brain=None, tts=None, rate=STT_SAMPLE_RATE,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)."""+ await the spawned turn task. Waits for the turn count to INCREMENT (relative)+ so it works when called repeatedly."""+ start_turns = session.turnssession._endpointer.silence_ms = 100session._endpointer.min_speech_ms = 60for _ in range(2):@@ -92,7 +94,7 @@ async def _drive_one_utterance(session, rate=STT_SAMPLE_RATE) -> None:await session.handle_audio_frame(_pcm16_frame(0, rate=rate))for _ in range(200):await asyncio.sleep(0)- if session.turns >= 1:+ if session.turns > start_turns:breakawait asyncio.sleep(0.01)@@ -139,12 +141,24 @@ async def test_brain_receives_transcript():assert "Wie geht es dir?" in brain.prompts-async def test_empty_transcript_skips_turn():+async def test_empty_transcript_emits_vad_silence_and_skips_turn():sink = _Sink()session = _make_session(sink, stt=FakeSTT([""]))await _drive_one_utterance(session)assert session.turns == 0assert sink.binary == []+ assert sink.json_of("vad_silence") # browser can reset its "thinking" UI+++async def test_two_consecutive_utterances_both_complete():+ # The _processing re-entrancy gate must reopen after each turn (the core+ # correctness invariant of the session loop).+ sink = _Sink()+ session = _make_session(sink, stt=FakeSTT(["eins", "zwei"]))+ await _drive_one_utterance(session)+ assert session.turns == 1+ await _drive_one_utterance(session)+ assert session.turns == 2async def test_audio_start_sets_rate_and_language():@@ -176,6 +190,8 @@ async def test_barge_in_cancels_tts():task = session._tts_taskassert task is None or task.cancelled() or task.done()assert session._speaking is False+ # The browser must get a flush signal (it never received tts_end).+ assert sink.json_of("tts_cancel")async def test_end_cancels_tasks():