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
chore: auto-save WIP via Claude stop-hook safety net (2026-07-10 17:54)
Ruben Lütke0a93878a6a58
diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex 36abb29ed2..3eb6c0c8b7 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -66,7 +66,12 @@ def _build_browser_session(if build_realtime_session is not None:rt = build_realtime_session(- cfg=cfg, bus=bus, session_id=session_id, send_binary=send_binary, send_json=send_json+ cfg=cfg,+ bus=bus,+ session_id=session_id,+ send_binary=send_binary,+ send_json=send_json,+ surface="browser",)if rt is not None:return rtdiff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex c664297ca8..b572b7bb5c 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -1038,6 +1038,18 @@ class VoiceSessionStarted(Event):language: str = "de"+@dataclass(frozen=True, slots=True)+class RealtimeSessionReady(Event):+ """A duplex provider accepted the effective session configuration."""++ session_id: str = ""+ provider: str = ""+ model: str = ""+ surface: str = ""+ input_sample_rate: int = 0+ output_sample_rate: int = 0++@dataclass(frozen=True, slots=True)class VoiceTurnStarted(Event):"""A new turn within the active session is starting."""diff --git a/jarvis/realtime/desktop.py b/jarvis/realtime/desktop.pynew file mode 100644index 0000000000..6aa5d863e5--- /dev/null+++ b/jarvis/realtime/desktop.py@@ -0,0 +1,123 @@+"""Desktop playback adapter for the transport-neutral realtime session."""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator+from typing import Any++from jarvis.core.protocols import AudioChunk+++class DesktopRealtimePlayback:+ """Feed provider PCM deltas through one persistent ``AudioPlayer`` stream.++ The bounded queue applies backpressure when an output device is slower than+ the provider. A turn-complete marker drains naturally; barge-in or teardown+ stops the device immediately and discards queued audio.+ """++ def __init__(+ self,+ player: Any,+ *,+ sample_rate: int = 24_000,+ max_queue_chunks: int = 200,+ finish_timeout_s: float = 120.0,+ ) -> None:+ self._player = player+ self._sample_rate = int(sample_rate)+ self._max_queue_chunks = max(1, int(max_queue_chunks))+ self._finish_timeout_s = max(1.0, float(finish_timeout_s))+ self._queue: asyncio.Queue[AudioChunk | None] | None = None+ self._task: asyncio.Task[None] | None = None++ async def send_binary(self, pcm: bytes) -> None:+ if not pcm:+ return+ if self._task is None or self._task.done():+ self._queue = asyncio.Queue(maxsize=self._max_queue_chunks)+ self._task = asyncio.create_task(+ self._player.play_chunks(self._chunks(self._queue)),+ name="realtime-desktop-playback",+ )+ assert self._queue is not None+ await self._queue.put(+ AudioChunk(pcm=bytes(pcm), sample_rate=self._sample_rate, timestamp_ns=0)+ )++ def set_sample_rate(self, sample_rate: int) -> None:+ """Set the rate announced by the accepted provider handshake.++ Providers must announce this before their first audio delta. Refuse a+ mid-stream rate change because one ``AudioPlayer`` stream cannot safely+ reinterpret already queued PCM at a different rate.+ """+ rate = int(sample_rate)+ if rate <= 0:+ raise ValueError("Realtime output sample rate must be positive")+ if self._task is not None and not self._task.done():+ raise RuntimeError("Cannot change realtime sample rate during playback")+ self._sample_rate = rate++ async def finish_turn(self) -> None:+ queue, task = self._detach()+ if queue is None or task is None:+ return+ await queue.put(None)+ try:+ await asyncio.wait_for(task, timeout=self._finish_timeout_s)+ except TimeoutError:+ self._player.stop()+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ async def cancel(self) -> None:+ queue, task = self._detach()+ self._player.stop()+ if queue is None or task is None:+ return+ while not queue.empty():+ try:+ queue.get_nowait()+ except asyncio.QueueEmpty: # pragma: no cover - race-safe guard+ break+ try:+ queue.put_nowait(None)+ except asyncio.QueueFull: # pragma: no cover - queue was drained above+ pass+ try:+ await asyncio.wait_for(task, timeout=2.0)+ except TimeoutError:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ async def close(self) -> None:+ await self.cancel()++ def _detach(+ self,+ ) -> tuple[asyncio.Queue[AudioChunk | None] | None, asyncio.Task[None] | None]:+ queue, task = self._queue, self._task+ self._queue = None+ self._task = None+ return queue, task++ @staticmethod+ async def _chunks(+ queue: asyncio.Queue[AudioChunk | None],+ ) -> AsyncIterator[AudioChunk]:+ while True:+ chunk = await queue.get()+ if chunk is None:+ return+ yield chunk+++__all__ = ["DesktopRealtimePlayback"]diff --git a/jarvis/realtime/factory.py b/jarvis/realtime/factory.pyindex 26d2f6a2d4..235fda12d3 100644--- a/jarvis/realtime/factory.py+++ b/jarvis/realtime/factory.py@@ -84,6 +84,7 @@ def build_realtime_session(send_binary: Any,send_json: Any,half_duplex: bool = False,+ surface: str = "browser",):"""Build a transport-neutral realtime session wrapper.@@ -110,6 +111,7 @@ def build_realtime_session(config=cfg,bus=bus,half_duplex=half_duplex,+ surface=surface,)except Exception as exc: # noqa: BLE001 — unbuildable stack => classic pathlog.warning("Realtime session build failed: %s", exc)diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex f96cfbb863..30bdc70686 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport asyncioimport loggingfrom typing import Any+from uuid import uuid4from jarvis.core.protocols import AudioChunkfrom jarvis.core.turn_language import resolve_output_language@@ -57,6 +58,7 @@ class RealtimeVoiceSession:bus: Any = None,browser_sample_rate: int = 48_000,half_duplex: bool = False,+ surface: str = "browser",) -> None:self.session_id = session_idself._send_binary = send_binary@@ -75,6 +77,7 @@ class RealtimeVoiceSession:self.browser_sample_rate, self._input_sample_rate)self._half_duplex = bool(half_duplex)+ self._surface = str(surface or "unknown")self._output_active = Falseself._language = self._resolve_lang(text="")@@ -85,6 +88,11 @@ class RealtimeVoiceSession:self._output_samples_sent = 0self._ended = Falseself._provider_errors: list[str] = []+ self._active_model = ""+ self._turn_id = ""+ self._turn_index = 0+ self._last_user_text = ""+ self._output_transcript: list[str] = []def _resolve_lang(self, *, text: str) -> str:brain = getattr(self._config, "brain", None)@@ -117,6 +125,9 @@ class RealtimeVoiceSession:),})+ await self._publish_ready()+ if self._surface == "browser":+ await self._publish_browser_session_started()elif kind == "barge_in":await self._barge_in()elif kind == "audio_stop":@@ -173,6 +184,7 @@ class RealtimeVoiceSession:self._provider = providerself._session = session+ self._active_model = modelself._input_sample_rate = input_rateself._in_resampler = StreamingPcm16Resampler(self.browser_sample_rate, input_rate@@ -223,6 +235,12 @@ class RealtimeVoiceSession:language=new_language,)mark_phase(LatencyPhase.REALTIME_INPUT_COMMITTED)+ self._last_user_text = event.text+ if not self._turn_id:+ self._turn_id = str(uuid4())+ self._turn_index += 1+ await self._publish_turn_started()+ await self._publish_transcription(event.text, bool(event.is_final))await self._send_json({"type": "transcript",@@ -242,6 +260,7 @@ class RealtimeVoiceSession:)self._gate.drain()continue+ self._output_transcript.append(display)await self._send_json({"type": "transcript",@@ -272,6 +291,7 @@ class RealtimeVoiceSession:await self._emit_audio(chunk)self._gate.drain()await self._send_json({"type": "turn_complete"})+ await self._publish_turn_completed()self._output_active = Falseself._output_samples_sent = 0elif event.type == "error":@@ -332,6 +352,116 @@ class RealtimeVoiceSession:except Exception: # noqa: BLE001, S110 — telemetry must never break voicepass+ async def _publish_ready(self) -> None:+ if self._bus is None:+ return+ try:+ from jarvis.core.events import RealtimeSessionReady++ await self._bus.publish(+ RealtimeSessionReady(+ source_layer=f"realtime.{self.active_provider}",+ session_id=self.session_id,+ provider=self.active_provider,+ model=self._active_model,+ surface=self._surface,+ input_sample_rate=self._input_sample_rate,+ output_sample_rate=int(+ getattr(self._provider, "output_sample_rate", 24_000) or 24_000+ ),+ )+ )+ except Exception: # noqa: BLE001, S110+ pass++ async def _publish_browser_session_started(self) -> None:+ if self._bus is None:+ return+ try:+ from jarvis.core.events import VoiceSessionStarted++ await self._bus.publish(+ VoiceSessionStarted(+ source_layer=f"realtime.{self.active_provider}",+ session_id=self.session_id,+ wake_keyword="browser_microphone",+ language=self._language,+ )+ )+ except Exception: # noqa: BLE001, S110+ pass++ async def _publish_transcription(self, text: str, is_final: bool) -> None:+ if self._bus is None:+ return+ try:+ from jarvis.core.events import TranscriptionUpdate++ await self._bus.publish(+ TranscriptionUpdate(+ source_layer=f"realtime.{self.active_provider}",+ text=text,+ is_final=is_final,+ )+ )+ except Exception: # noqa: BLE001, S110+ pass++ async def _publish_turn_started(self) -> None:+ if self._bus is None:+ return+ try:+ from jarvis.core.events import VoiceTurnStarted++ await self._bus.publish(+ VoiceTurnStarted(+ source_layer=f"realtime.{self.active_provider}",+ session_id=self.session_id,+ turn_id=self._turn_id,+ turn_index=self._turn_index,+ )+ )+ except Exception: # noqa: BLE001, S110+ pass++ async def _publish_turn_completed(self) -> None:+ if not self._turn_id:+ self._output_transcript.clear()+ self._last_user_text = ""+ return+ answer = "".join(self._output_transcript).strip()+ if self._bus is not None:+ try:+ from jarvis.core.events import ResponseGenerated, VoiceTurnCompleted++ if answer:+ await self._bus.publish(+ ResponseGenerated(+ source_layer=f"realtime.{self.active_provider}",+ text=answer,+ language=self._language,+ )+ )+ await self._bus.publish(+ VoiceTurnCompleted(+ source_layer=f"realtime.{self.active_provider}",+ session_id=self.session_id,+ turn_id=self._turn_id,+ user_text=self._last_user_text,+ user_lang=self._language,+ jarvis_text=answer,+ jarvis_lang=self._language,+ tier="realtime",+ provider=self.active_provider,+ model=self._active_model,+ )+ )+ except Exception: # noqa: BLE001, S110+ pass+ self._turn_id = ""+ self._last_user_text = ""+ self._output_transcript.clear()+async def _emit_audio(self, chunk: Any) -> None:pcm = bytes(getattr(chunk, "pcm", b"") or b"")if not pcm:@@ -383,6 +513,20 @@ class RealtimeVoiceSession:await self._session.close()except Exception: # noqa: BLE001, S110 — best-effort teardownpass+ if self._surface == "browser" and self._bus is not None:+ try:+ from jarvis.core.events import VoiceSessionEnded++ await self._bus.publish(+ VoiceSessionEnded(+ source_layer=f"realtime.{self.active_provider}",+ session_id=self.session_id,+ hangup_reason=reason or "client_stop",+ turn_count=self._turn_index,+ )+ )+ except Exception: # noqa: BLE001, S110+ passlog.info("realtime[%s] ended: reason=%s", self.session_id, reason)@propertydiff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 4ad1b23a05..11ea180a89 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -326,6 +326,25 @@ _STT_UNAVAILABLE_PHRASE: dict[str, str] = {"es": "Perdona, no te he entendido bien ahora mismo. ¿Puedes repetirlo, por favor?",}+# Honest cross-family fallback when a requested duplex provider cannot open a+# session. The classic pipeline remains available for this voice call so a+# missing key, exhausted balance, unsupported model, or network outage never+# turns the Realtime switch into a silent dead end (AP-22/AP-23).+_REALTIME_UNAVAILABLE_PHRASE: dict[str, str] = {+ "de": (+ "Die Realtime-Verbindung ist gerade nicht verfügbar. "+ "Ich wechsle für diese Sitzung zur klassischen Sprachverarbeitung."+ ),+ "en": (+ "The realtime connection is unavailable right now. "+ "I am switching this session to the classic voice pipeline."+ ),+ "es": (+ "La conexión en tiempo real no está disponible ahora mismo. "+ "Cambiaré esta sesión al sistema de voz clásico."+ ),+}+# AD-OE6 zero-silent-drop fallback for a brain TURN that times out. Live bug# 2026-05-29: "kannst du Claude Code öffnen" stalled the Gemini stream; the# brain-timeout path returned to LISTENING in SILENCE (and idle_timeout@@ -1418,6 +1437,7 @@ class SpeechPipeline:self._state = PipelineState.IDLEself._call_event = asyncio.Event()self._hangup_event = asyncio.Event()+ self._current_voice_session_id: str | None = None# Optionale Event-Bus-Integration — wenn None, sind alle# _transition/_emit-Calls no-ops (Rueckwaertskompatibilitaet)self._bus = bus@@ -4713,6 +4733,7 @@ class SpeechPipeline:# spoken cue. (The spoken-cue path is for mid-conversation use.)self._session_has_assistant_spoken = Falsesession_id = str(uuid4())+ self._current_voice_session_id = session_idsession_started_at = time.time()wake_keyword = ("push_to_talk"@@ -4738,6 +4759,7 @@ class SpeechPipeline:except Exception as exc: # noqa: BLE001log.exception("Session-Fehler: %s", exc)finally:+ self._current_voice_session_id = None# PTT is one-shot per hold — disarm before the next session so a# stale flag can never reroute a later wake-word session into# the raw-recording path.@@ -4835,7 +4857,24 @@ class SpeechPipeline:self._last_announcement_spoken_monotonic = Noneself._last_answer_floor_monotonic = Noneif self._ptt_mode:+ # Push-to-talk is deliberately a discrete classic turn: the key-up+ # edge is its endpoint and the duplex protocols do not expose one+ # provider-neutral commit primitive. Normal wake/hotkey sessions+ # use Realtime when selected.return await self._ptt_session()+ requested_mode = str(+ getattr(+ getattr(getattr(self, "_config", None), "voice", None),+ "mode",+ "pipeline",+ )+ or "pipeline"+ ).strip().lower()+ if requested_mode == "realtime":+ realtime_reason = await self._active_realtime_session()+ if realtime_reason is not None:+ return realtime_reason+ await self._speak_realtime_unavailable()async with MicrophoneCapture(device=self._input_device,max_queue_chunks=REALTIME_QUEUE_CHUNKS,@@ -4968,6 +5007,147 @@ class SpeechPipeline:next_task.cancel()return HANGUP_HOTKEY+ async def _active_realtime_session(self) -> str | None:+ """Run one desktop duplex session, or request classic fallback.++ Imports stay lazy so the optional realtime stack never enters the boot+ critical path. The session owns provider-family fallback and resampling;+ this adapter owns only the local microphone, speaker, and lifecycle.+ Desktop starts half-duplex because PortAudio has no portable acoustic+ echo cancellation. The browser surface provides full duplex with Web+ Audio echo cancellation.+ """+ try:+ from jarvis.realtime.desktop import DesktopRealtimePlayback+ from jarvis.realtime.factory import build_realtime_session+ except ImportError as exc:+ log.warning("Realtime desktop stack is unavailable: %s", exc)+ return None++ playback = DesktopRealtimePlayback(self._player)+ turn_complete = asyncio.Event()+ speaking = False++ async def _send_binary(pcm: bytes) -> None:+ nonlocal speaking+ if not speaking:+ speaking = True+ await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)+ await playback.send_binary(pcm)++ async def _send_json(message: dict[str, Any]) -> None:+ nonlocal speaking+ kind = str(message.get("type", ""))+ if kind == "audio_ready":+ playback.set_sample_rate(+ int(message.get("output_sample_rate", 24_000) or 24_000)+ )+ log.info(+ "Realtime desktop session ready: provider=%s input=%sHz output=%sHz",+ message.get("provider", "unknown"),+ message.get("input_sample_rate", "unknown"),+ message.get("output_sample_rate", "unknown"),+ )+ elif kind == "transcript":+ role = str(message.get("role", ""))+ if role == "user" and bool(message.get("is_final", False)):+ await self._set_turn_state(TurnTakingState.PROCESSING)+ elif kind == "tts_cancel":+ speaking = False+ await playback.cancel()+ await self._set_turn_state(TurnTakingState.LISTENING)+ elif kind == "turn_complete":+ await playback.finish_turn()+ speaking = False+ await self._set_turn_state(TurnTakingState.LISTENING)+ if not self._continue_listening_after_response:+ turn_complete.set()+ elif kind in {"provider_error", "error_spoken"}:+ log.warning("Realtime desktop status: %s", message)++ session_id = getattr(self, "_current_voice_session_id", None) or str(uuid4())+ session = build_realtime_session(+ cfg=self._config,+ bus=self._bus,+ session_id=session_id,+ send_binary=_send_binary,+ send_json=_send_json,+ half_duplex=True,+ surface="desktop",+ )+ if session is None:+ return None++ wait_tasks: set[asyncio.Task[Any]] = set()+ reason = "desktop_fallback"+ try:+ await session.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await self._set_turn_state(TurnTakingState.LISTENING)+ async with MicrophoneCapture(+ device=self._input_device,+ max_queue_chunks=REALTIME_QUEUE_CHUNKS,+ device_priority=self._input_priority,+ ) as mic:+ async def _send_microphone() -> None:+ async for chunk in self._session_input_stream(mic.stream()):+ await session.handle_audio_frame(chunk.pcm)++ microphone_task = asyncio.create_task(+ _send_microphone(), name=f"rt-mic-{session_id}"+ )+ provider_task = asyncio.create_task(+ session.wait_finished(), name=f"rt-provider-{session_id}"+ )+ hangup_task = asyncio.create_task(+ self._hangup_event.wait(), name=f"rt-hangup-{session_id}"+ )+ wait_tasks.update({microphone_task, provider_task, hangup_task})+ if not self._continue_listening_after_response:+ wait_tasks.add(+ asyncio.create_task(+ turn_complete.wait(), name=f"rt-turn-{session_id}"+ )+ )+ done, _pending = await asyncio.wait(+ wait_tasks, return_when=asyncio.FIRST_COMPLETED+ )+ if hangup_task in done and self._hangup_event.is_set():+ reason = HANGUP_HOTKEY+ return HANGUP_HOTKEY+ if turn_complete.is_set():+ reason = HANGUP_TURN_COMPLETE+ return HANGUP_TURN_COMPLETE+ for task in done:+ if task.cancelled():+ continue+ exc = task.exception()+ if exc is not None:+ log.warning(+ "Realtime desktop task ended with %s: %s",+ type(exc).__name__,+ exc,+ )+ # A dead provider stream or microphone unwinds into the classic+ # pipeline inside the same call, with an honest spoken notice.+ return None+ except asyncio.CancelledError:+ reason = "shutdown"+ raise+ except Exception as exc: # noqa: BLE001 — classic fallback is load-bearing+ log.warning("Realtime desktop session failed; using pipeline: %s", exc)+ return None+ finally:+ for task in wait_tasks:+ if not task.done():+ task.cancel()+ for task in wait_tasks:+ try:+ await task+ except (asyncio.CancelledError, Exception):+ pass+ await session.end(reason=reason)+ await playback.close()+async def _ptt_session(self) -> str:"""Push-to-talk turn: record raw mic audio until the key is released,then submit the whole capture as ONE prompt (one-shot).@@ -7283,6 +7463,20 @@ class SpeechPipeline:except Exception as exc: # noqa: BLE001log.warning("STT-unavailable fallback speak failed: %s", exc)+ async def _speak_realtime_unavailable(self) -> None:+ """Explain a duplex failure before continuing on the classic path."""+ lang = _phrase_lang(self._output_language(None, ""))+ phrase = _REALTIME_UNAVAILABLE_PHRASE[lang]+ try:+ await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)+ await self._speak(+ phrase,+ language=lang,+ kind=SPOKEN_KIND_UNAVAILABLE,+ )+ except Exception as exc: # noqa: BLE001 — fallback must never block recovery+ log.warning("Realtime-unavailable fallback speak failed: %s", exc)+def _mark_brain_progress(self) -> None:"""Record that the in-flight brain turn just made progress.diff --git a/tests/unit/realtime/test_desktop.py b/tests/unit/realtime/test_desktop.pynew file mode 100644index 0000000000..3505557e95--- /dev/null+++ b/tests/unit/realtime/test_desktop.py@@ -0,0 +1,68 @@+from __future__ import annotations++import asyncio++import pytest++from jarvis.realtime.desktop import DesktopRealtimePlayback+++class FakePlayer:+ def __init__(self) -> None:+ self.chunks = []+ self.stopped = 0++ async def play_chunks(self, chunks) -> None:+ async for chunk in chunks:+ self.chunks.append(chunk)++ def stop(self) -> None:+ self.stopped += 1+++async def test_turn_uses_one_stream_and_drains_in_order():+ player = FakePlayer()+ playback = DesktopRealtimePlayback(player)++ await playback.send_binary(b"\x01\x00" * 8)+ await playback.send_binary(b"\x02\x00" * 8)+ await playback.finish_turn()++ assert [chunk.pcm for chunk in player.chunks] == [+ b"\x01\x00" * 8,+ b"\x02\x00" * 8,+ ]+ assert all(chunk.sample_rate == 24_000 for chunk in player.chunks)+++async def test_cancel_stops_player_and_discards_queued_audio():+ gate = asyncio.Event()++ class SlowPlayer(FakePlayer):+ async def play_chunks(self, chunks) -> None:+ async for chunk in chunks:+ await gate.wait()+ self.chunks.append(chunk)++ player = SlowPlayer()+ playback = DesktopRealtimePlayback(player)+ await playback.send_binary(b"\x01\x00" * 8)++ await playback.cancel()++ assert player.stopped == 1+ assert player.chunks == []+++async def test_handshake_sample_rate_is_used_for_the_next_turn():+ player = FakePlayer()+ playback = DesktopRealtimePlayback(player)++ playback.set_sample_rate(16_000)+ await playback.send_binary(b"\x01\x00" * 8)+ await playback.finish_turn()++ assert [chunk.sample_rate for chunk in player.chunks] == [16_000]diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.pynew file mode 100644index 0000000000..d560092fda--- /dev/null+++ b/tests/unit/speech/test_realtime_mode.py@@ -0,0 +1,213 @@+"""Desktop voice-mode routing and duplex lifecycle regression tests."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest++import jarvis.speech.pipeline as pipeline_mod+from jarvis.sessions.constants import HANGUP_SHUTDOWN, HANGUP_TURN_COMPLETE+from jarvis.speech.pipeline import SpeechPipeline+++class _FakePlayer:+ def __init__(self) -> None:+ self.pcm: list[bytes] = []+ self.stopped = 0++ async def play_chunks(self, chunks) -> None:+ async for chunk in chunks:+ self.pcm.append(chunk.pcm)++ def stop(self) -> None:+ self.stopped += 1+++class _SilentMic:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *_exc: object) -> bool:+ return False++ async def stream(self):+ await asyncio.Event().wait()+ if False: # pragma: no cover - makes this an async iterator+ yield None+++class _EmptyVad:+ def utterances(self, _stream):+ async def _empty():+ if False: # pragma: no cover - makes this an async iterator+ yield b""++ return _empty()+++class _FakeRealtimeSession:+ def __init__(self, send_binary, send_json) -> None:+ self._send_binary = send_binary+ self._send_json = send_json+ self.controls: list[dict[str, object]] = []+ self.end_reason = ""+ self._forever = asyncio.Event()++ async def handle_control(self, message) -> None:+ self.controls.append(message)+ await self._send_json(+ {+ "type": "audio_ready",+ "provider": "fake-live",+ "input_sample_rate": 16_000,+ "output_sample_rate": 24_000,+ }+ )+ await self._send_json(+ {+ "type": "transcript",+ "role": "user",+ "text": "hello",+ "is_final": True,+ }+ )+ await self._send_binary(b"\x01\x00" * 16)+ await self._send_json({"type": "turn_complete"})++ async def handle_audio_frame(self, _pcm: bytes) -> None:+ return None++ async def wait_finished(self) -> None:+ await self._forever.wait()++ async def end(self, *, reason: str = "") -> None:+ self.end_reason = reason+++def _pipe(mode: str = "realtime") -> SpeechPipeline:+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._config = SimpleNamespace(+ voice=SimpleNamespace(mode=mode),+ brain=SimpleNamespace(reply_language="en"),+ )+ pipe._player = _FakePlayer()+ pipe._bus = None+ pipe._input_device = None+ pipe._input_priority = ()+ pipe._hangup_event = asyncio.Event()+ pipe._continue_listening_after_response = False+ pipe._current_voice_session_id = "desktop-session"+ pipe._muted = False+ pipe._input_suppressed_until_ns = 0+ pipe._ptt_mode = False+ pipe._vad = _EmptyVad()+ pipe._idle_timeout_s = 0.1+ pipe._idle_hangup_enabled = True+ pipe._session_end_reason = None+ pipe._carry_pcm = bytearray()+ pipe._carry_started_monotonic = None+ pipe._last_endpoint_reason = None+ pipe._last_announcement_spoken_monotonic = None+ pipe._last_answer_floor_monotonic = None+ states = []++ async def _set_state(state) -> None:+ states.append(state)++ async def _publish(_event) -> None:+ return None++ pipe._set_turn_state = _set_state # type: ignore[method-assign]+ pipe._publish_event = _publish # type: ignore[method-assign]+ pipe._test_states = states # type: ignore[attr-defined]+ return pipe+++async def test_desktop_realtime_handshake_streams_audio_and_ends_single_turn(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipe = _pipe()+ built: dict[str, object] = {}++ def _build(**kwargs):+ built.update(kwargs)+ session = _FakeRealtimeSession(kwargs["send_binary"], kwargs["send_json"])+ built["session"] = session+ return session++ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic())++ reason = await asyncio.wait_for(pipe._active_realtime_session(), timeout=2.0)++ assert reason == HANGUP_TURN_COMPLETE+ assert built["half_duplex"] is True+ assert built["surface"] == "desktop"+ assert built["session_id"] == "desktop-session"+ assert pipe._player.pcm == [b"\x01\x00" * 16]+ assert built["session"].end_reason == HANGUP_TURN_COMPLETE+++async def test_realtime_mode_routes_before_the_classic_microphone(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipe = _pipe()+ calls = 0++ async def _run_realtime():+ nonlocal calls+ calls += 1+ return HANGUP_TURN_COMPLETE++ pipe._active_realtime_session = _run_realtime # type: ignore[method-assign]++ def _classic_mic_must_not_open(**_kwargs):+ raise AssertionError("classic microphone opened during a healthy realtime session")++ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _classic_mic_must_not_open)++ assert await pipe._active_session() == HANGUP_TURN_COMPLETE+ assert calls == 1+++async def test_failed_realtime_session_explains_and_falls_back_in_same_call(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipe = _pipe()+ notices = 0++ async def _failed_realtime():+ return None++ async def _notice():+ nonlocal notices+ notices += 1++ pipe._active_realtime_session = _failed_realtime # type: ignore[method-assign]+ pipe._speak_realtime_unavailable = _notice # type: ignore[method-assign]+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic())++ reason = await asyncio.wait_for(pipe._active_session(), timeout=2.0)++ assert reason == HANGUP_SHUTDOWN+ assert notices == 1+++async def test_pipeline_mode_never_enters_realtime_branch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipe = _pipe(mode="pipeline")++ async def _must_not_run():+ raise AssertionError("realtime branch ran while pipeline mode was selected")++ pipe._active_realtime_session = _must_not_run # type: ignore[method-assign]+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic())++ assert await asyncio.wait_for(pipe._active_session(), timeout=2.0) == HANGUP_SHUTDOWN