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(live): emit explicit thinking/speaking frames for the Jarvis bar
rubenluetke10-beepa9d2d9866859
diff --git a/jarvis/live/native.py b/jarvis/live/native.pyindex eb7e3f698a..d443492fbb 100644--- a/jarvis/live/native.py+++ b/jarvis/live/native.py@@ -206,6 +206,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):async def _native_event(self, event: Any) -> None:assert self._tools is not None and self._ledger is not Noneif event.type == "audio_delta" and event.audio is not None:+ await self._note_speaking()await self._send_binary(event.audio.pcm)elif event.type in {"input_transcript", "output_transcript_delta"}:role: Literal["user", "assistant"] = (@@ -258,9 +259,11 @@ class NativeLiveVoiceSession(LiveVoiceSession):self._jobs.add(task)task.add_done_callback(self._jobs.discard)elif event.type in {"interrupted", "speech_started"}:+ self._speaking = False+ self._thinking = Falseawait self._send_json({"type": "tts_cancel"})elif event.type == "turn_complete":- await self._send_json({"type": "tts_end"})+ await self._note_turn_end()elif event.type == "usage":usage = event.usage or {}await asyncio.to_thread(diff --git a/jarvis/live/session.py b/jarvis/live/session.pyindex 495d716e6d..c0828fb0ec 100644--- a/jarvis/live/session.py+++ b/jarvis/live/session.py@@ -72,6 +72,8 @@ class LiveVoiceSession:self._delegation_responses: dict[str, str] = {}self._voice_seconds = 0.0self.playback_active = False+ self._speaking = False+ self._thinking = Falseself._active_model = ""self._archive_turn_id = str(uuid4())self._parent_owned = False@@ -114,6 +116,54 @@ class LiveVoiceSession:def is_active(self) -> bool:return self._connection is not None and not self._closing+ @property+ def phase(self) -> str:+ """The surface indicator state: speaking, thinking or listening."""+ if self._speaking or self.playback_active:+ return "speaking"+ if self._thinking:+ return "thinking"+ return "listening"++ async def _emit_indicator(self, message: dict) -> None:+ """Send a speaking/thinking indicator without breaking the session.++ Indicators are best-effort UI hints: a closing socket must never turn+ them into a session failure.+ """+ if self._closing:+ return+ try:+ await self._send_json(message)+ except Exception: # noqa: BLE001 — indicators must not kill voice+ log.debug("Live indicator frame could not be sent", exc_info=True)++ async def _note_thinking(self) -> None:+ if self._thinking or self._speaking or self._closing:+ return+ self._thinking = True+ await self._emit_indicator({"type": "thinking"})++ async def _note_speaking(self) -> None:+ if self._closing:+ return+ first = not self._speaking+ self._speaking = True+ self._thinking = False+ if first:+ await self._emit_indicator({"type": "tts_start"})+ await self._emit_indicator({"type": "speaking"})++ async def _note_turn_end(self) -> None:+ if self._closing:+ return+ ended_speech = self._speaking+ self._speaking = False+ self._thinking = False+ if ended_speech:+ await self._emit_indicator({"type": "tts_end"})+ await self._emit_indicator({"type": "turn_complete"})+async def wait_finished(self) -> None:await self._closed.wait()@@ -172,7 +222,10 @@ class LiveVoiceSession:await self._connection.send({"type": "response.create"})elif kind == "barge_in":# GPT-Live hears interruptions in the continuous input stream.+ self._speaking = False+ self._thinking = Falseawait self._send_json({"type": "audio_clear"})+ await self._emit_indicator({"type": "tts_cancel"})async def _start(self, message: dict) -> None:self._adopt_desktop_session()@@ -388,8 +441,17 @@ class LiveVoiceSession:"end_ms": fragment.end_ms,})- elif kind == "session.output_audio.delta" and not self._connection.answer_sdp:- await self._send_binary(base64.b64decode(event["delta"]))+ if role == "assistant" and current:+ await self._note_thinking()+ elif kind == "session.output_audio.delta":+ # The sideband carries this event on every transport, including+ # WebRTC where the media itself travels over RTP. The binary+ # forwarding below stays PCM-only, but the speaking signal must+ # reach the surfaces on both paths — otherwise the Jarvis bar+ # never leaves listening while GPT-Live talks.+ await self._note_speaking()+ if not self._connection.answer_sdp:+ await self._send_binary(base64.b64decode(event["delta"]))elif kind in {"session.usage.updated", "session.closed"}:self._wire_seconds = max(self._wire_seconds, float(event.get("usage", {}).get("seconds", self._wire_seconds))@@ -450,6 +512,7 @@ class LiveVoiceSession:self._response_revisions[self._response_id] = self._tools.revisionself._delegation_responses[delegation] = self._response_idself._responses.setdefault(self._response_id, [])+ await self._note_thinking()elif kind == "response.output_item.done":item = event.get("item", {})if item.get("type") == "function_call":@@ -466,6 +529,7 @@ class LiveVoiceSession:if rid in self._completed:returnself._completed.add(rid)+ await self._note_turn_end()usage = response.get("usage") or {}profile = getattr(self._config, "live", LiveConfig())await asyncio.to_thread(diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsxindex d135007905..00797784b9 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx@@ -152,6 +152,32 @@ describe("BrowserRealtimeControl", () => {expect(useEventStore.getState().voiceState).toBe("thinking");});+ it("shows speaking on the live tts_start frame without binary audio", async () => {+ // GPT-Live talks over WebRTC: no PCM sideband, no onAudio — the+ // backend's explicit frame is the only speaking signal the bar gets.+ render(<BrowserRealtimeControl />);+ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));++ act(() => fakes.callbacks?.onStatus?.("thinking", {}));+ expect(useEventStore.getState().voiceState).toBe("thinking");++ act(() => fakes.callbacks?.onStatus?.("tts_start", {}));+ expect(useEventStore.getState().voiceState).toBe("speaking");+ });++ it("returns to listening when the live session clears audio on barge-in", async () => {+ render(<BrowserRealtimeControl />);+ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));++ act(() => fakes.callbacks?.onStatus?.("speaking", {}));+ expect(useEventStore.getState().voiceState).toBe("speaking");++ act(() => fakes.callbacks?.onStatus?.("audio_clear", {}));+ expect(useEventStore.getState().voiceState).toBe("listening");+ });+it("keeps thinking after a progress surface line finishes speaking", async () => {render(<BrowserRealtimeControl />);fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsxindex 62aecf1f40..1bc1306826 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx@@ -255,6 +255,10 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:setVoice("thinking");} else if (status === "speaking" || status === "listening") {setVoice(status);+ } else if (status === "tts_start") {+ // GPT-Live emits speaking state explicitly because its WebRTC+ // audio never reaches the binary playback path (no onAudio).+ setVoice("speaking");} else if (status === "turn_complete" || status === "tts_end") {if (status === "tts_end" &&@@ -266,7 +270,9 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:resumeThinkingAfterSpeechRef.current = false;setVoice("listening");}- } else if (status === "tts_cancel") {+ } else if (status === "tts_cancel" || status === "audio_clear") {+ // audio_clear is the live session's barge-in flush: the user+ // interrupted, so the assistant is no longer speaking.setVoice("listening");} else if (status === "tts_browser_unavailable" ||diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex 94781595f9..e59b99ce6b 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -55,6 +55,13 @@ const OUTPUT_TAP_TTL_MS = 600;/** Historical fixed budget for one realtime start attempt. */const DEFAULT_START_BUDGET_MS = 20_000;+/**+ * Consecutive quiet analyser frames before the WebRTC voice tap reports+ * listening (~700 ms at 60 fps). Word gaps must not flip the Jarvis bar+ * back to listening mid-sentence.+ */+const REMOTE_SILENCE_HANGOVER_FRAMES = 42;+/** Bounded startup pre-roll, mirroring the desktop's 30 s replay window.** Captured microphone PCM used to be DISCARDED until the backend answered@@ -397,11 +404,18 @@ export class RealtimeAudioClient {private mediaFrame = 0;private remoteSource: MediaStreamAudioSourceNode | null = null;private lastPlaybackActive = false;+ private remoteSilenceFrames = 0;private observeRemoteAudio(stream: MediaStream): void {if (!this.ctx) return;+ // A suspended context measures only zeros: the assistant would talk+ // while the bar keeps showing listening. The call started from a user+ // gesture, so resuming here is allowed and makes the tap truthful.+ void this.ctx.resume().catch(() => undefined);cancelAnimationFrame(this.mediaFrame);this.remoteSource?.disconnect();+ this.lastPlaybackActive = false;+ this.remoteSilenceFrames = 0;const analyser = this.ctx.createAnalyser();analyser.fftSize = 256;this.remoteSource = this.ctx.createMediaStreamSource(stream);@@ -412,11 +426,23 @@ export class RealtimeAudioClient {const rms = Math.sqrt(samples.reduce((sum, x) => sum + x * x, 0) / samples.length);this.cb.onOutputLevel?.(this.outputMeter.push(rms));const active = rms > 0.004;- if (active !== this.lastPlaybackActive) {- this.lastPlaybackActive = active;- if (active) this.cb.onAudio?.();- this.cb.onStatus?.(active ? "speaking" : "listening", {});- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: "playback_state", active }));+ if (active) {+ this.remoteSilenceFrames = 0;+ if (!this.lastPlaybackActive) {+ this.lastPlaybackActive = true;+ this.cb.onAudio?.();+ this.cb.onStatus?.("speaking", {});+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: "playback_state", active: true }));+ }+ } else if (this.lastPlaybackActive) {+ // Word gaps are silence too: only report listening after the tail+ // of the reply is really over, or the bar flickers mid-sentence.+ this.remoteSilenceFrames += 1;+ if (this.remoteSilenceFrames >= REMOTE_SILENCE_HANGOVER_FRAMES) {+ this.lastPlaybackActive = false;+ this.cb.onStatus?.("listening", {});+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: "playback_state", active: false }));+ }}this.mediaFrame = requestAnimationFrame(measure);};@@ -795,6 +821,8 @@ export class RealtimeAudioClient {cancelAnimationFrame(this.mediaFrame);this.remoteSource?.disconnect();this.remoteSource = null;+ this.lastPlaybackActive = false;+ this.remoteSilenceFrames = 0;const socket = this.ws;this.ws = null;this.ready = false;diff --git a/jarvis/ui/web/voice_call_routes.py b/jarvis/ui/web/voice_call_routes.pyindex c4f06d0fd6..b7fdae154a 100644--- a/jarvis/ui/web/voice_call_routes.py+++ b/jarvis/ui/web/voice_call_routes.py@@ -63,10 +63,13 @@ async def voice_state() -> dict[str, Any]:sessions = active()if sessions:+ phase = getattr(sessions[0], "phase", "listening")+ if phase not in {"speaking", "thinking", "listening"}:+ phase = "speaking" if sessions[0].playback_active else "listening"return {"available": True,"state": "active",- "voice_state": "speaking" if sessions[0].playback_active else "listening",+ "voice_state": phase,}pipeline = _pipeline()if pipeline is None:diff --git a/tests/contract/test_gpt_live.py b/tests/contract/test_gpt_live.pyindex 44865a8d58..5f27f8f70b 100644--- a/tests/contract/test_gpt_live.py+++ b/tests/contract/test_gpt_live.py@@ -536,3 +536,139 @@ async def test_late_transcript_cannot_reopen_tool_execution_after_close(ledger):})assert not session._tools.accepting+async def test_live_drives_jarvis_bar_indicators(ledger):+ """Thinking while the model works, speaking while it talks — on both transports."""+ import base64++ json_frames: list[dict] = []+ binary_frames: list[bytes] = []++ async def send_json(event):+ json_frames.append(event)++ async def send_binary(data):+ binary_frames.append(data)++ def make_session(*, webrtc: bool):+ cfg = SimpleNamespace(brain=SimpleNamespace(reply_language="en"))+ session = LiveVoiceSession(+ session_id="s",+ send_binary=send_binary,+ send_json=send_json,+ providers=[SimpleNamespace(name="test")],+ config=cfg,+ )+ session._ledger = ledger+ session._tools = LiveTools(Gateway(), ledger, "s", language="en", backend_model="chosen")+ session._connection = SimpleNamespace(send=send_json, answer_sdp="answer" if webrtc else "")+ return session++ async def response_created(session):+ await session._event(+ {+ "type": "response.event",+ "delegation_id": "d",+ "event": {"type": "response.created", "response": {"id": "r"}},+ }+ )++ async def response_completed(session):+ await session._event(+ {+ "type": "response.event",+ "delegation_id": "d",+ "event": {"type": "response.completed", "response": {"id": "r"}},+ }+ )++ pcm = base64.b64encode(b"\x00\x01" * 160).decode("ascii")++ # WebRTC (ChatGPT Live): audio travels over RTP, but the speaking+ # signal must still reach the bar — without it the bar never leaves+ # listening while Jarvis talks.+ session = make_session(webrtc=True)+ await response_created(session)+ assert {"type": "thinking"} in json_frames+ assert session.phase == "thinking"+ await session._event(+ {+ "type": "session.output_audio.delta",+ "delta": pcm,+ "start_ms": 0,+ "end_ms": 100,+ }+ )+ assert {"type": "tts_start"} in json_frames+ assert {"type": "speaking"} in json_frames+ assert binary_frames == []+ assert session.phase == "speaking"+ await response_completed(session)+ types = [frame["type"] for frame in json_frames]+ assert "tts_end" in types+ assert "turn_complete" in types+ assert session.phase == "listening"++ # PCM transport: the same signals plus the forwarded audio itself.+ json_frames.clear()+ binary_frames.clear()+ session = make_session(webrtc=False)+ await response_created(session)+ assert {"type": "thinking"} in json_frames+ await session._event(+ {+ "type": "session.output_audio.delta",+ "delta": pcm,+ "start_ms": 0,+ "end_ms": 100,+ }+ )+ assert {"type": "speaking"} in json_frames+ assert len(binary_frames) == 1+ await response_completed(session)+ assert session.phase == "listening"++ # A barge-in returns the bar to listening instead of freezing on speaking.+ json_frames.clear()+ session = make_session(webrtc=True)+ await response_created(session)+ await session._event(+ {"type": "session.output_audio.delta", "delta": pcm, "start_ms": 0, "end_ms": 10}+ )+ assert session.phase == "speaking"+ await session.handle_control({"type": "barge_in"})+ assert {"type": "tts_cancel"} in json_frames+ assert session.phase == "listening"+++async def test_live_assistant_transcript_keeps_thinking_visible(ledger):+ json_frames: list[dict] = []++ async def send(event):+ json_frames.append(event)++ cfg = SimpleNamespace(brain=SimpleNamespace(reply_language="en"))+ session = LiveVoiceSession(+ session_id="s",+ send_binary=send,+ send_json=send,+ providers=[SimpleNamespace(name="test")],+ config=cfg,+ )+ session._ledger = ledger+ session._tools = LiveTools(Gateway(), ledger, "s", language="en", backend_model="chosen")+ session._connection = SimpleNamespace(send=send, answer_sdp="answer")+ for index, delta in enumerate(["Hel", "lo"]):+ await session._event(+ {+ "type": "session.output_transcript.delta",+ "event_id": f"e-{index}",+ "delta": delta,+ "start_ms": index * 80,+ "end_ms": index * 80 + 80,+ }+ )+ thinking = [frame for frame in json_frames if frame["type"] == "thinking"]+ assert len(thinking) == 1+ assert session.phase == "thinking"