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(dictation): dictate during a live call without hanging it up (#311)
Ruben Lütke18170b7df09f
diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex c73d5d18cd..e79db8d4d5 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -1132,6 +1132,24 @@ class VoiceMuteChanged(Event):source: str = ""+@dataclass(frozen=True, slots=True)+class VoiceInputHeld(Event):+ """A live call's microphone is held back while something else listens.++ Published by the speech pipeline when a dictation starts beside a live+ voice call (``held=True``) and again once that dictation has delivered its+ text (``held=False``). The call keeps running; only the user's audio stops+ reaching the realtime model, so the dictated words go into the text field+ and never become a turn. Separate from ``VoiceMuteChanged`` on purpose:+ that is the user's own mute, and a dictation must neither show it on+ every mute icon nor clear it when it ends.++ ``reason`` is free-form for the log (``"dictation"`` today).+ """+ held: bool = False+ reason: str = ""++@dataclass(frozen=True, slots=True)class VoiceSpeakerMuteChanged(Event):"""Authoritative broadcast that the assistant's voice went silent or audible.diff --git a/jarvis/live/native.py b/jarvis/live/native.pyindex 7dede0d313..f67a87da6a 100644--- a/jarvis/live/native.py+++ b/jarvis/live/native.py@@ -116,6 +116,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):register(self)self._pump_task = asyncio.create_task(self._pump(), name="native-live-events")await self._take_startup_input(message)+ self._watch_input_mute()await self._send_json({"type": "audio_ready",@@ -125,6 +126,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):"output_sample_rate": self._provider.output_sample_rate,"language": self._language,"requires_webrtc_answer": False,+ "input_muted": self._input_muted,})except BaseException:@@ -132,7 +134,12 @@ class NativeLiveVoiceSession(LiveVoiceSession):raiseasync def handle_audio_frame(self, pcm: bytes) -> None:- if self._connection is not None and not self._closing and not self._recovering:+ if (+ self._connection is not None+ and not self._closing+ and not self._recovering+ and not self._input_muted+ ):audio = self._resampler.process(pcm)if audio:try:@@ -410,6 +417,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):if self._ended:returnself._ended = True+ self._stop_watching_input_mute()self._clear_media_levels()self._closing = Trueawait self._publish_phase("idle")diff --git a/jarvis/live/session.py b/jarvis/live/session.pyindex ee9d96d10f..d6f5726a02 100644--- a/jarvis/live/session.py+++ b/jarvis/live/session.py@@ -30,6 +30,20 @@ REASONING_SNAPSHOT_INTERVAL_S = 0.3_REASONING_ITEMS_MAX = 16+def _pipeline_input_muted() -> bool:+ """Jarvis's microphone mute. The speech pipeline is its only writer."""+ from jarvis.core.runtime_refs import get_speech_pipeline++ return bool(getattr(get_speech_pipeline(), "is_muted", False))+++def _pipeline_input_held() -> bool:+ """Whether a dictation beside the call holds the user's audio back."""+ from jarvis.core.runtime_refs import get_speech_pipeline++ return bool(getattr(get_speech_pipeline(), "is_voice_input_held", False))++def _summary_index(event: dict) -> int:"""The summary part a reasoning-summary event belongs to (0 when absent)."""try:@@ -104,6 +118,15 @@ class LiveVoiceSession:self._mic_feedback_owned = Falseself._mic_feedback_warning = Falseself._input_active = False+ # The mute on the pet strip, the Jarvis Bar or the orb. A browser call+ # owns its microphone in the WebView, out of reach of the pipeline's own+ # capture gate, so the session drops the frames and tells the page.+ # ``_input_muted`` is what the frame gate and the page obey: the+ # user's mute OR a dictation holding the input (see ``VoiceInputHeld``).+ self._input_muted = False+ self._user_muted = False+ self._input_held = False+ self._watching_input_mute = Falseself._media_timeout: asyncio.TimerHandle | None = Noneself._active_model = ""self._archive_turn_id = str(uuid4())@@ -300,10 +323,14 @@ class LiveVoiceSession:callable(getattr(mic_level, name, None))for name in ("claim_external", "release_external", "publish"))- if microphone_ready:+ # While a dictation holds the input, its own capture drives the meter:+ # the page's track is silenced, and claiming the meter here would+ # flatten the dictation's bars with the page's zeros.+ meter_owned = microphone_ready and not self._input_held+ if meter_owned:mic_level.claim_external(self.session_id)self._mic_feedback_owned = True- elif not self._mic_feedback_warning:+ elif not microphone_ready and not self._mic_feedback_warning:self._mic_feedback_warning = Truelog.warning("Browser microphone meter needs an app restart; voice remains connected")self._media_received = True@@ -319,7 +346,7 @@ class LiveVoiceSession:level_tap.note_playing(0.3)elif previous_playback:level_tap.reset_playing()- if microphone_ready:+ if meter_owned:mic_level.publish(levels.input_level, owner=self.session_id)if self._media_timeout is not None:self._media_timeout.cancel()@@ -510,6 +537,7 @@ class LiveVoiceSession:if self._closing:returnawait self._take_startup_input(message)+ self._watch_input_mute()await self._send_json({"type": "audio_ready",@@ -521,6 +549,7 @@ class LiveVoiceSession:"requires_webrtc_answer": bool(offer),"webrtc_answer_sdp": self._connection.answer_sdp,"continuous": True,+ "input_muted": self._input_muted,})except BaseException as exc:@@ -594,11 +623,80 @@ class LiveVoiceSession:if prefix is not None:await self._send_json(prefix)+ def _watch_input_mute(self) -> None:+ """Adopt the current microphone mute and follow it until the call ends."""+ self._user_muted = _pipeline_input_muted()+ self._input_held = _pipeline_input_held()+ self._input_muted = self._user_muted or self._input_held+ if self._bus is None or self._watching_input_mute:+ return+ from jarvis.core.events import VoiceInputHeld, VoiceMuteChanged++ self._bus.subscribe(VoiceMuteChanged, self._on_input_mute_changed)+ self._bus.subscribe(VoiceInputHeld, self._on_input_held_changed)+ self._watching_input_mute = True++ def _stop_watching_input_mute(self) -> None:+ if not self._watching_input_mute or self._bus is None:+ return+ from jarvis.core.events import VoiceInputHeld, VoiceMuteChanged++ self._bus.unsubscribe(VoiceMuteChanged, self._on_input_mute_changed)+ self._bus.unsubscribe(VoiceInputHeld, self._on_input_held_changed)+ self._watching_input_mute = False++ async def _on_input_mute_changed(self, event: Any) -> None:+ """Follow the user's own microphone mute."""+ self._user_muted = bool(event.muted)+ await self._apply_input_mute()++ async def _on_input_held_changed(self, event: Any) -> None:+ """Follow a dictation that borrows the user's voice beside the call.++ The call stays open; only the audio stops reaching the model until the+ dictated text has been delivered, so it never becomes a spoken turn.+ """+ self._input_held = bool(event.held)+ log.info(+ "Live call input %s (%s).",+ "held" if self._input_held else "released",+ getattr(event, "reason", "") or "unknown",+ )+ if self._input_held:+ self._release_mic_meter()+ await self._apply_input_mute()++ def _release_mic_meter(self) -> None:+ """Hand the microphone meter back so a dictation's own levels show."""+ if not self._mic_feedback_owned:+ return+ from jarvis.audio import mic_level++ release = getattr(mic_level, "release_external", None)+ if callable(release):+ release(self.session_id)+ self._mic_feedback_owned = False++ async def _apply_input_mute(self) -> None:+ """Drop the user's audio from now on and let the page silence its track.++ Dropping frames here covers the PCM socket. A WebRTC call sends its+ audio straight to the provider, so only the page can silence that one.+ """+ self._input_muted = self._user_muted or self._input_held+ if self._closing:+ return+ try:+ await self._send_json({"type": "input_mute", "muted": self._input_muted})+ except Exception: # noqa: BLE001 — the frames are dropped here regardless+ log.warning("Voice page missed the microphone mute", exc_info=True)+async def handle_audio_frame(self, pcm: bytes) -> None:if (self._connection is Noneor self._closingor self._recovering+ or self._input_mutedor self._connection.answer_sdp):return@@ -1137,6 +1235,7 @@ class LiveVoiceSession:if self._ended:returnself._ended = True+ self._stop_watching_input_mute()self._clear_media_levels()from jarvis.live.runtime import unregisterdiff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 38e73d96cf..0e8e56cade 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -79,6 +79,7 @@ from jarvis.core.events import (TranscriptionUpdate,UtteranceCaptured,VoiceBootStatus,+ VoiceInputHeld,VoiceMuteChanged,VoiceMuteToggleRequested,VoiceSessionEnded,@@ -2388,6 +2389,10 @@ class SpeechPipeline:# and the moment ``_dictation_task`` exists (or the handover is refused),# and never both at once. See ``_begin_dictation_handover``.self._dictation_handover_task: asyncio.Task[None] | None = None+ # A dictation started beside a live call, and whether that call's input+ # is held for it. See ``_live_call_owns_microphone``.+ self._dictation_beside_call = False+ self._voice_input_held = False# 0.0 is a real value here — "no ceiling" — so it must NOT be coerced# to a default the way an absent or malformed setting is. The old# ``or 300.0`` did exactly that and made the off switch unreachable@@ -10919,10 +10924,69 @@ class SpeechPipeline:"The voice pipeline is not running, so dictation cannot start.",)return False+ if self._live_call_owns_microphone():+ # A live call keeps running: its input is held, not hung up.+ return self._commit_dictation(+ loop, target=target, source=source, beside_call=True+ )if self._voice_session_holds_microphone():return self._begin_dictation_handover(loop, target=target, source=source)return self._commit_dictation(loop, target=target, source=source)+ def _live_call_owns_microphone(self) -> bool:+ """True while a live realtime call captures the microphone in the WebView.++ Such a call owns its own capture (getUserMedia, with the browser's echo+ cancellation), so a dictation does not have to take the device away+ from it. Instead the dictation records through its own capture and the+ call's input is HELD until the text is delivered (``VoiceInputHeld``):+ the conversation stays open and the dictated words never become a turn.+ Push-to-talk is excluded — its raw recording is the pipeline's own+ stream, and that lane keeps the ordinary handover.+ """+ if getattr(self, "_ptt_mode", False):+ return False+ try:+ from jarvis.live.runtime import owns_microphone+ except Exception: # noqa: BLE001 — no live stack means no live call+ log.debug("live call registry unavailable", exc_info=True)+ return False+ return owns_microphone()++ @property+ def is_voice_input_held(self) -> bool:+ """Whether a dictation currently holds a live call's input back.++ Read by a call that starts DURING such a dictation, so it adopts the+ hold instead of hearing the dictated words.+ """+ return bool(getattr(self, "_voice_input_held", False))++ def _set_voice_input_held(self, held: bool) -> None:+ """Hold or release a live call's input and tell the call. Never raises."""+ if bool(getattr(self, "_voice_input_held", False)) == held:+ return+ self._voice_input_held = held+ log.info(+ "Live call input %s for the dictation.",+ "held" if held else "released",+ )+ self._publish_event_soon(VoiceInputHeld(held=held, reason="dictation"))++ def _on_beside_call_dictation_done(self, _task: asyncio.Task[None]) -> None:+ """Give the call its voice back once the dictation has fully ended.++ A done-callback rather than a ``finally``: it runs for every end of the+ task, including one cancelled before its first step, so the call can+ never be left deaf. The task ends only after the text was delivered,+ which is the moment the user may talk to the call again.+ """+ try:+ self._dictation_beside_call = False+ self._set_voice_input_held(False)+ except Exception: # noqa: BLE001 — a release must never become a crash+ log.warning("Releasing the live call input failed", exc_info=True)+def _voice_session_holds_microphone(self) -> bool:"""True while the VOICE lane owns the one input device.@@ -11082,26 +11146,42 @@ class SpeechPipeline:log.debug("Dictation handover callback failed", exc_info=True)def _commit_dictation(- self, loop: asyncio.AbstractEventLoop, *, target: str, source: str = "api"+ self,+ loop: asyncio.AbstractEventLoop,+ *,+ target: str,+ source: str = "api",+ beside_call: bool = False,) -> bool:"""Arm the wake block, announce the turn and spawn the recording task.The commit point shared by the direct start and the handover, so botharrive in the dictation lane through exactly one door. Always returns``True``; every reason not to be here is checked by ``start_dictation``.++ ``beside_call`` means a live call keeps running next to this dictation:+ its input is held until the task ends, and the call's hangup event is+ left alone — it belongs to the call, not to this recording."""self._dictation_started_by = str(source or "api")self._dictation_discard_requested = False+ self._dictation_beside_call = beside_call# A fresh dictation session must NOT inherit a stale hangup. ``_hangup_event``# is set by every "auflegen" and is otherwise only cleared when the next# VOICE session is accepted (``_run_session``). The dictation lane shares# that event in its ``asyncio.wait`` gate, so a leftover hangup from an# earlier voice call would finalize this session on its first tick — the# mic appears to "stop the instant you click it". Clear it here, mirroring- # the voice-path ``self._hangup_event.clear()`` at session accept.+ # the voice-path ``self._hangup_event.clear()`` at session accept. Beside+ # a live call the event is the CALL's: clearing it could swallow a+ # hangup the user just asked for, and the lane does not wait on it.hangup = getattr(self, "_hangup_event", None)- if hangup is not None:+ if hangup is not None and not beside_call:hangup.clear()+ if beside_call:+ # Held BEFORE the recording task exists, so the call stops hearing+ # the user as early as possible.+ self._set_voice_input_held(True)# Stored RAW ("auto" / "insert" / "chat"). ``auto`` is resolved when the# recording ENDS, not here: the window that matters is the one in front# when the text is delivered. Clicking "Start dictating" in the app and@@ -11145,10 +11225,13 @@ class SpeechPipeline:self._dictation_task = loop.create_task(self._dictation_session(), name="dictation")+ if beside_call:+ self._dictation_task.add_done_callback(self._on_beside_call_dictation_done)log.info(- "🎙️ dictation started (transcribe-only, target=%s, via=%s).",+ "🎙️ dictation started (transcribe-only, target=%s, via=%s%s).",self._dictation_target,self._dictation_started_by,+ ", beside a live call" if beside_call else "",)return True@@ -13247,7 +13330,14 @@ class SpeechPipeline:else None)stop_task = asyncio.create_task(self._dictation_stop_event.wait())- hangup_task = asyncio.create_task(self._hangup_event.wait())+ # Beside a live call the hangup event is the CALL's: hanging up+ # the conversation must not throw away what is being dictated.+ hangup_event = (+ asyncio.Event()+ if getattr(self, "_dictation_beside_call", False)+ else self._hangup_event+ )+ hangup_task = asyncio.create_task(hangup_event.wait())# Only a recording the HOLD key started is owed a release edge;# the watchdog ends it when the key is physically up and that# edge never came (BUG-191). It sets the stop event, so it is@@ -13270,7 +13360,7 @@ class SpeechPipeline:timeout=self._dictation_max_s or None,return_when=asyncio.FIRST_COMPLETED,)- hung_up = hangup_task in done or self._hangup_event.is_set()+ hung_up = hangup_task in done or hangup_event.is_set()if getattr(self, "_dictation_discard_requested", False):# The bar's close-X: end it like a hangup — nothing# transcribed, nothing delivered.diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.tsindex 0cc026cfb8..33b1dbf6d1 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts@@ -153,6 +153,36 @@ describe("realtime audio client", () => {await client.disconnect();});+ it.each([true, false])("silences the microphone track while Jarvis's mute is on (WebRTC=%s)", async (webrtc) => {+ const { track } = installVoiceBrowserFakes() as { track: { stop: () => void; enabled?: boolean } };+ vi.stubGlobal("Audio", class { play = async () => undefined; pause = () => undefined; });+ const client = new RealtimeAudioClient({}, { browserAudio: true, requiresWebRtcOffer: webrtc });+ const connecting = client.connect();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ socket.receive({+ type: "audio_ready",+ requires_webrtc_answer: webrtc,+ input_muted: true,+ ...(webrtc ? { webrtc_answer_sdp: "answer" } : {}),+ });+ expect(track.enabled).toBe(false);+ await connecting;+ socket.receive({ type: "input_mute", muted: false });+ expect(track.enabled).toBe(true);+ socket.receive({ type: "input_mute", muted: true });+ expect(track.enabled).toBe(false);+ socket.receive({ type: "input_mute", muted: false });+ socket.receive({ type: "audio_stopping" });+ expect(track.enabled).toBe(false);+ // An unmute after the call began closing never reopens the microphone.+ socket.receive({ type: "input_mute", muted: false });+ expect(track.enabled).toBe(false);+ socket.receive({ type: "audio_closed" });+ await client.disconnect();+ });+it("precedes browser PCM with native wake audio on the local/Gemini path", async () => {installVoiceBrowserFakes();const client = new RealtimeAudioClient({}, { browserAudio: true });diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex f065da86ce..f23afed111 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -401,6 +401,11 @@ export class RealtimeAudioClient {private finalized: (() => void) | null = null;private serverClosed = false;private reconnecting = false;+ // Jarvis's microphone mute (pet strip, Jarvis Bar, orb), sent by the+ // backend. A WebRTC call carries this track straight to the provider, so+ // the backend cannot drop its audio; a disabled track sends silence.+ private inputMuted = false;+ private inputStopped = false;constructor(private cb: RealtimeCallbacks = {},@@ -477,6 +482,22 @@ export class RealtimeAudioClient {};}+ private syncInputTracks(): void {+ const enabled = !this.inputMuted && !this.inputStopped;+ this.stream?.getAudioTracks().forEach(track => { track.enabled = enabled; });+ }++ private applyInputMute(muted: unknown): void {+ if (typeof muted !== "boolean") return;+ this.inputMuted = muted;+ this.syncInputTracks();+ }++ private stopInput(): void {+ this.inputStopped = true;+ this.syncInputTracks();+ }+connect(): Promise<void> {if (this.ready) return Promise.resolve();if (this.connecting) return this.connecting;@@ -490,6 +511,8 @@ export class RealtimeAudioClient {this.intentionalClose = false;this.serverClosed = false;this.reconnecting = false;+ this.inputMuted = false;+ this.inputStopped = false;try {const supportIssue = browserRealtimeSupportIssue();if (supportIssue) throw new RealtimeAudioSupportError(supportIssue);@@ -723,7 +746,9 @@ export class RealtimeAudioClient {} else if (type === "audio_stopping") {this.startupNode?.port.postMessage({ type: "suspend" });this.webRtcTransport.muteOutput();- this.stream?.getAudioTracks().forEach(track => { track.enabled = false; });+ this.stopInput();+ } else if (type === "input_mute") {+ this.applyInputMute(message.muted);} else if (type === "audio_closed") {this.serverClosed = true;this.finalized?.();@@ -748,6 +773,8 @@ export class RealtimeAudioClient {// The local control channel can already relay levels while RTP// finishes its handshake. Native and browser bars share this input.this.controlReady = true;+ // Before the retained opening is released below.+ this.applyInputMute(message.input_muted);this.sendMediaLevels(true);this.setOutputRate(message.output_sample_rate);void this.finishAudioReady(message)@@ -926,7 +953,7 @@ export class RealtimeAudioClient {if (this.options.browserAudio && this.ready && !this.serverClosed && this.ws?.readyState === WebSocket.OPEN) {this.ready = false;this.webRtcTransport.muteOutput();- this.stream?.getAudioTracks().forEach(track => { track.enabled = false; });+ this.stopInput();await new Promise<void>(resolve => {const timer = window.setTimeout(resolve, 16_000);this.finalized = () => { window.clearTimeout(timer); resolve(); };diff --git a/tests/contract/test_live_input_mute.py b/tests/contract/test_live_input_mute.pynew file mode 100644index 0000000000..fdfd04f3b2--- /dev/null+++ b/tests/contract/test_live_input_mute.py@@ -0,0 +1,153 @@+"""Jarvis's microphone mute reaches a live call whose microphone the page owns.++Live 2026-10-01: the pet strip's microphone flipped the pipeline's mute, but a+browser-owned GPT-Live call kept hearing the user, because the pipeline's+capture gate never sees that audio.+"""++from types import SimpleNamespace++import pytest++from jarvis.core import runtime_refs+from jarvis.core.bus import EventBus+from jarvis.core.events import VoiceInputHeld, VoiceMuteChanged+from jarvis.live.native import NativeLiveVoiceSession+from jarvis.live.session import LiveVoiceSession+++class _Connection:+ answer_sdp = ""++ def __init__(self) -> None:+ self.sent: list[object] = []++ async def send(self, message: dict) -> None:+ self.sent.append(message)++ async def send_audio(self, chunk: object) -> None:+ self.sent.append(chunk)++ async def close(self) -> None:+ return None++[email protected](params=[LiveVoiceSession, NativeLiveVoiceSession])+def call(request, monkeypatch):+ pipeline = SimpleNamespace(is_muted=False)+ monkeypatch.setattr(runtime_refs, "get_speech_pipeline", lambda: pipeline)+ bus = EventBus()+ page: list[dict] = []++ async def send_json(message: dict) -> None:+ page.append(message)++ async def send_binary(_data: bytes) -> None:+ return None++ session = request.param(+ session_id="mute-test",+ bus=bus,+ send_json=send_json,+ send_binary=send_binary,+ config=SimpleNamespace(brain=SimpleNamespace(reply_language="en")),+ providers=[+ SimpleNamespace(name="test", input_sample_rate=24000, output_sample_rate=24000)+ ],+ )+ connection = _Connection()+ session._connection = connection+ return SimpleNamespace(+ session=session, bus=bus, page=page, connection=connection, pipeline=pipeline+ )+++PCM = b"\x01\x00" * 4800+++async def test_a_mute_during_the_call_stops_the_audio_and_tells_the_page(call):+ call.session._watch_input_mute()+ await call.session.handle_audio_frame(PCM)+ assert len(call.connection.sent) == 1++ await call.bus.publish(VoiceMuteChanged(muted=True, source="pet_strip"))+ assert call.page[-1] == {"type": "input_mute", "muted": True}+ await call.session.handle_audio_frame(PCM)+ assert len(call.connection.sent) == 1++ await call.bus.publish(VoiceMuteChanged(muted=False, source="pet_strip"))+ assert call.page[-1] == {"type": "input_mute", "muted": False}+ await call.session.handle_audio_frame(PCM)+ assert len(call.connection.sent) == 2+++async def test_a_call_that_starts_muted_adopts_the_mute(call):+ call.pipeline.is_muted = True+ call.session._watch_input_mute()+ assert call.session._input_muted is True+ await call.session.handle_audio_frame(PCM)+ assert call.connection.sent == []+++async def test_an_ended_call_stops_following_the_mute(call):+ call.session._watch_input_mute()+ call.session._stop_watching_input_mute()+ await call.bus.publish(VoiceMuteChanged(muted=True, source="pet_strip"))+ assert call.page == []+ assert call.session._input_muted is False+++async def test_a_dictation_holds_the_call_input_until_it_is_delivered(call):+ call.session._watch_input_mute()+ await call.bus.publish(VoiceInputHeld(held=True, reason="dictation"))+ assert call.page[-1] == {"type": "input_mute", "muted": True}+ await call.session.handle_audio_frame(PCM)+ assert call.connection.sent == []++ await call.bus.publish(VoiceInputHeld(held=False, reason="dictation"))+ assert call.page[-1] == {"type": "input_mute", "muted": False}+ await call.session.handle_audio_frame(PCM)+ assert len(call.connection.sent) == 1+++async def test_releasing_the_hold_never_unmutes_the_user(call):+ call.session._watch_input_mute()+ await call.bus.publish(VoiceMuteChanged(muted=True, source="pet_strip"))+ await call.bus.publish(VoiceInputHeld(held=True, reason="dictation"))+ await call.bus.publish(VoiceInputHeld(held=False, reason="dictation"))+ assert call.page[-1] == {"type": "input_mute", "muted": True}+ await call.session.handle_audio_frame(PCM)+ assert call.connection.sent == []+++async def test_a_call_that_starts_during_a_dictation_adopts_the_hold(call):+ call.pipeline.is_voice_input_held = True+ call.session._watch_input_mute()+ assert call.session._input_muted is True+ await call.session.handle_audio_frame(PCM)+ assert call.connection.sent == []+++async def test_a_held_call_leaves_the_microphone_meter_to_the_dictation(call):+ from jarvis.audio import mic_level++ mic_level.reset_for_tests()+ seen: list[float] = []+ mic_level.subscribe(seen.append)+ call.session._watch_input_mute()+ call.session._mic_feedback_owned = True+ mic_level.claim_external(call.session.session_id)++ await call.bus.publish(VoiceInputHeld(held=True, reason="dictation"))+ # The dictation's own capture feeds the meter without an owner.+ mic_level.publish(0.4)+ assert seen == [0.4]+ assert call.session._mic_feedback_owned is False+ mic_level.reset_for_tests()diff --git a/tests/unit/speech/test_dictation_beside_live_call.py b/tests/unit/speech/test_dictation_beside_live_call.pynew file mode 100644index 0000000000..09a0fdbf56--- /dev/null+++ b/tests/unit/speech/test_dictation_beside_live_call.py@@ -0,0 +1,248 @@+"""The dictation key works DURING a live call instead of hanging it up.++Live 2026-10-01: holding the dictation key in a realtime call ended the call —+the press took the microphone the old way (hang up, wait, record). A live call+captures the microphone in the WebView, so the two never fight over the device:+the dictation records through its own capture while the call's input is HELD+(``VoiceInputHeld``). The model hears nothing until the dictated text has been+delivered, then the conversation continues as if nothing happened.+"""++from __future__ import annotations++import asyncio++import pytest++import jarvis.live.runtime as live_runtime+import jarvis.speech.pipeline as pipeline_mod+from jarvis.core.bus import EventBus+from jarvis.core.events import DictationRefused, DictationStarted, VoiceInputHeld+from jarvis.speech.pipeline import PipelineState, SpeechPipeline, TurnTakingState+++class _StubSTT:+ async def transcribe_pcm(self, pcm: bytes): # pragma: no cover - never called+ raise AssertionError("no transcription in this unit test")+++class _SilentMic:+ """A capture device that never yields a frame."""++ opens = 0++ def __init__(self, *args: object, **kwargs: object) -> None:+ pass++ async def __aenter__(self) -> _SilentMic:+ type(self).opens += 1+ return self++ async def __aexit__(self, *exc: object) -> bool:+ return False++ async def stream(self): # type: ignore[no-untyped-def]+ await asyncio.Event().wait()+ yield # pragma: no cover - unreachable, keeps this an async generator+++class _Player:+ def __init__(self) -> None:+ self.stops = 0++ def stop(self) -> None:+ self.stops += 1+++class _Collector:+ def __init__(self, bus: EventBus) -> None:+ self.held: list[bool] = []+ self.started: list[DictationStarted] = []+ self.refused: list[DictationRefused] = []+ bus.subscribe(VoiceInputHeld, self._held)+ bus.subscribe(DictationStarted, self._started)+ bus.subscribe(DictationRefused, self._refused)++ async def _held(self, event: VoiceInputHeld) -> None:+ self.held.append(event.held)++ async def _started(self, event: DictationStarted) -> None:+ self.started.append(event)++ async def _refused(self, event: DictationRefused) -> None:+ self.refused.append(event)+++def _pipeline(bus: EventBus) -> SpeechPipeline:+ """A pipeline reduced to the dictation lane, sitting in a live call."""+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._bus = bus+ pipe._utterance_stt = _StubSTT()+ pipe._dictation_task = None+ pipe._dictation_handover_task = None+ pipe._dictation_stop_event = asyncio.Event()+ pipe._dictation_cfg = None+ pipe._dictation_max_s = 5.0+ pipe._dictation_wake_block_until = 0.0+ pipe._dictation_completion_published = True+ pipe._ptt_mode = False+ pipe._ptt_partial_interval_s = 0.0 # no live probe in these tests+ # The desktop pipeline sits in an active session while the call runs.+ pipe._state = PipelineState.ACTIVE+ pipe._turn_state = TurnTakingState.IDLE+ pipe._muted = False+ pipe._input_device = "default"+ pipe._input_priority = ()+ pipe._hangup_event = asyncio.Event()+ pipe._player = _Player()++ async def _no_delivery(**_kwargs) -> str:+ return ""++ pipe._finish_dictation = _no_delivery # type: ignore[assignment]+ return pipe+++async def _drain_bus() -> None:+ for _ in range(6):+ await asyncio.sleep(0)++[email protected](autouse=True)+def _live_call(monkeypatch: pytest.MonkeyPatch):+ """One registered browser call that owns the microphone."""+ monkeypatch.setattr(_SilentMic, "opens", 0)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _SilentMic)+ monkeypatch.setattr(live_runtime, "_active", {"call-1": object()})+ monkeypatch.setattr(live_runtime, "_opening", set())+++async def test_the_key_dictates_without_hanging_up_the_call() -> None:+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _pipeline(bus)++ assert pipe.start_dictation(target="insert") is True+ await _drain_bus()++ assert pipe._dictation_handover_task is None, "no handover beside a live call"+ assert pipe._hangup_event.is_set() is False, "the call is not hung up"+ assert pipe._player.stops == 0+ assert pipe._state is PipelineState.ACTIVE+ assert pipe.dictation_active() is True+ assert _SilentMic.opens == 1, "the dictation records through its own capture"+ assert [e.target for e in seen.started] == ["insert"]+ assert seen.refused == []+ # The call stops hearing the user for as long as the dictation runs.+ assert pipe.is_voice_input_held is True+ assert seen.held == [True]++ task = pipe._dictation_task+ assert task is not None+ pipe.stop_dictation()+ await asyncio.wait_for(task, timeout=2.0)+ await _drain_bus()++ # Delivered — the call gets the user's voice back.+ assert pipe.is_voice_input_held is False+ assert seen.held == [True, False]+ assert pipe._hangup_event.is_set() is False+++async def test_a_cancelled_dictation_still_gives_the_call_its_voice_back() -> None:+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _pipeline(bus)++ assert pipe.start_dictation() is True+ task = pipe._dictation_task+ assert task is not None+ # Cancelled before its first step: no ``finally`` inside it ever runs.+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ await _drain_bus()++ assert pipe.is_voice_input_held is False+ assert seen.held == [True, False]+++async def test_hanging_up_the_call_does_not_throw_the_dictation_away() -> None:+ bus = EventBus()+ _Collector(bus)+ pipe = _pipeline(bus)++ assert pipe.start_dictation() is True+ await _drain_bus()+ pipe._hangup_event.set()+ await _drain_bus()++ assert pipe.dictation_active() is True, "the call's hangup is not the dictation's"++ task = pipe._dictation_task+ assert task is not None+ pipe.stop_dictation()+ await asyncio.wait_for(task, timeout=2.0)+ # The call's hangup request survives the dictation untouched.+ assert pipe._hangup_event.is_set() is True+++async def test_a_pending_call_hangup_is_not_swallowed_by_the_press() -> None:+ bus = EventBus()+ _Collector(bus)+ pipe = _pipeline(bus)+ pipe._hangup_event.set()++ assert pipe.start_dictation() is True+ assert pipe._hangup_event.is_set() is True++ task = pipe._dictation_task+ assert task is not None+ pipe.stop_dictation()+ await asyncio.wait_for(task, timeout=2.0)+++async def test_push_to_talk_keeps_the_ordinary_handover(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """PTT records on the pipeline's own stream, so it is not a WebView call."""+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _pipeline(bus)+ pipe._ptt_mode = True+ hangups: list[bool] = []+ monkeypatch.setattr(pipe, "request_hangup", lambda: hangups.append(True))++ assert pipe.start_dictation() is True+ assert hangups == [True]+ handover = pipe._dictation_handover_task+ assert handover is not None+ handover.cancel()+ await asyncio.gather(handover, return_exceptions=True)+ await _drain_bus()+ assert seen.held == []+ assert pipe.is_voice_input_held is False+++async def test_no_call_means_no_hold(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(live_runtime, "_active", {})+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _pipeline(bus)+ pipe._state = PipelineState.IDLE++ assert pipe.start_dictation() is True+ await _drain_bus()+ assert seen.held == []+ assert pipe.is_voice_input_held is False++ task = pipe._dictation_task+ assert task is not None+ pipe.stop_dictation()+ await asyncio.wait_for(task, timeout=2.0)diff --git a/tests/unit/ui/test_orb_bus_bridge_dictation.py b/tests/unit/ui/test_orb_bus_bridge_dictation.pyindex b3d1a54ce8..6ca62127cc 100644--- a/tests/unit/ui/test_orb_bus_bridge_dictation.py+++ b/tests/unit/ui/test_orb_bus_bridge_dictation.py@@ -41,6 +41,7 @@ from jarvis.core.events import ( # noqa: E402DictationStarted,DictationTranscribing,DictationTranscript,+ SystemStateChanged,VoiceSessionStarted,WakeCandidateDetected,)@@ -69,6 +70,9 @@ class _FakeOrb:def play_animation(self, name: str) -> None:self.calls.append(("play_animation", name))+ def stop_animation(self, name: str) -> None:+ self.calls.append(("stop_animation", name))+def show_listening_transcript(self, text: str = "", duration_ms: int = 0) -> None:self.calls.append(("transcript", text))@@ -133,15 +137,38 @@ async def test_the_reveal_survives_a_stale_voice_state_label() -> None:await _quiesce(bridge)-async def test_a_live_voice_session_outranks_a_dictation_reveal() -> None:+async def test_a_dictation_beside_a_live_call_takes_the_bar_and_hands_it_back() -> None:+ """Live 2026-10-02: in a call the dictation key left the bar standing still.++ The pipeline holds the call's input while dictating, so the bar shows the+ dictation, ignores the call's state edges meanwhile, and gives the call its+ own look back once the text is delivered.+ """orb = _FakeOrb()bridge = _bridge(orb)bridge._voice_session_active = True+ bridge._last_state = "LISTENING"- await bridge._on_dictation_started(DictationStarted(target="chat"))+ await bridge._on_dictation_started(DictationStarted(target="insert"))+ assert orb.modes == ["dictate"]+ assert bridge._dictation_active is True- assert orb.modes == []+ # The call keeps publishing its phase; the dictation still owns the bar.+ await bridge._on_state(+ SystemStateChanged(new_state="THINKING", previous="LISTENING")+ )+ assert orb.modes == ["dictate"]+ orb.calls.clear()+ bridge._on_mic_level(0.5)+ assert ("set_level", 0.5) in orb.calls++ await bridge._on_dictation_transcribing(DictationTranscribing())+ await bridge._on_dictation_completed(+ DictationCompleted(text="hello", outcome="inserted")+ )+ assert orb.modes[-1] == "think", "the call's current look comes back"assert bridge._dictation_active is False+ assert "idle" not in orb.modesawait _quiesce(bridge)diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.pyindex 43165b5603..a3c6389b99 100644--- a/ui/orb/bus_bridge.py+++ b/ui/orb/bus_bridge.py@@ -1349,7 +1349,7 @@ class OrbBusBridge:# suppression latch (that only blocks ACTIVE-state repaints), so the# genuine IDLE transition, if it still arrives, is a harmless same-mode# repaint. The idle-animation scheduler stays owned by that transition.- if not self._hides_when_idle():+ if not self._hides_when_idle() and not self._dictation_active:try:self._orb.show(mode="idle")except Exception as exc: # noqa: BLE001@@ -1481,6 +1481,13 @@ class OrbBusBridge:except Exception as exc: # noqa: BLE001log.debug("stop_mouth_animation failed: %s", exc)+ if self._dictation_active:+ # A dictation (also one beside a live call) owns the surface until+ # it completes; ``_last_state`` is current, and the completion+ # hands the surface back through ``_restore_voice_surface`` or+ # stands it down when the call ended in the meantime.+ return+if state == "LISTENING":self._orb.show(mode="listen")if prev_state in ("IDLE", "ERROR", "PAUSED"):@@ -1627,6 +1634,9 @@ class OrbBusBridge:)if not late_final_ok:return+ if self._dictation_active:+ # The dictation's live text owns the bubble meanwhile.+ returnif _is_transcript_boilerplate(event.text):log.info("OrbBridge suppressed STT boilerplate transcript: %r",@@ -1652,7 +1662,7 @@ class OrbBusBridge:is already hidden, so we leave it alone."""self._last_response_text = (event.text or "").strip()- if self._last_state in ("THINKING", "SPEAKING"):+ if self._last_state in ("THINKING", "SPEAKING") and not self._dictation_active:self._refresh_voice_bubble()def _refresh_voice_bubble(self) -> None:@@ -1731,10 +1741,14 @@ class OrbBusBridge:released by ``VoiceBootStatus`` stores the mode and stays withdrawn,exactly as it does for a wake word (AP-26)."""- if self._voice_session_active:- log.debug("OrbBridge dictation reveal skipped: a voice session owns the bar")- return- log.info("OrbBridge._on_dictation_started: target=%s", getattr(event, "target", ""))+ # A dictation beside a live call takes the surface over too: the+ # pipeline holds the call's input meanwhile, so the bar shows what is+ # actually listening, and the completion hands the call's look back.+ log.info(+ "OrbBridge._on_dictation_started: target=%s%s",+ getattr(event, "target", ""),+ " (over a live voice session)" if self._voice_session_active else "",+ )self._cancel_dictation_standdown()self._dictation_active = Trueself._dictation_transcribing = False@@ -1771,7 +1785,7 @@ class OrbBusBridge:``_last_state``) so the four dictation handlers can never disagree aboutwho owns the bar."""- if self._voice_session_active:+ if self._voice_session_active and not self._dictation_active:returnif getattr(event, "is_final", False):# The completion handler owns the end of a dictation — it knows the@@ -1796,7 +1810,7 @@ class OrbBusBridge:``dictate_transcribing`` mode renders the orbital core instead, andkeeps the click surface inert exactly like the recording mode does."""- if not self._dictation_active or self._voice_session_active:+ if not self._dictation_active:returnself._dictation_transcribing = Trueself._show_dictation_mode("dictate_transcribing")@@ -1842,12 +1856,23 @@ class OrbBusBridge:# raised for one frame before the stand-down clears it is a flicker,# not a receipt.self._show_listening_transcript("" if quiet else (detail or (event.text or "").strip()))- # Whatever raised the bar must be able to lower it. This guard is- # deliberately the SAME one ``_on_dictation_started`` uses — an- # asymmetric pair (raise on any state, lower only from IDLE) would leave- # the bar lit whenever ``_last_state`` was stale, which is a real- # possibility because dictation never touches the voice state machine.if self._voice_session_active:+ # The dictation ran beside a live call: hand the surface back to+ # the call's own look instead of standing it down to idle. The+ # notice stand-down restores ``_current_voice_mode`` after its+ # dwell, which also clears a sentence shown here.+ if arrived:+ self._restore_voice_surface()+ delay = 0.0 if quiet else DICTATION_OUTCOME_DWELL_S+ else:+ self._show_notice_mode()+ delay = (+ DICTATION_OUTCOME_DWELL_S if detail else DICTATION_NOTHING_BACK_DWELL_S+ )+ try:+ self._schedule_notice_standdown(delay)+ except Exception as exc: # noqa: BLE001+ log.debug("OrbBridge dictation hand-back suppressed: %s", exc)returnif arrived:# Nothing is in flight and nothing failed, so the bar rests NOW@@ -1937,6 +1962,18 @@ class OrbBusBridge:except Exception as exc: # noqa: BLE001 — a missed repaint is cosmeticlog.debug("OrbBridge dictation rest repaint suppressed: %s", exc)+ def _restore_voice_surface(self) -> None:+ """Give the surface back to the live voice session a dictation borrowed.++ Repaints the look the voice lane would be showing now. The state edges+ that arrived during the dictation updated ``_last_state`` but were not+ painted (see ``_on_state``), so this is where they catch up.+ """+ try:+ self._orb.show(mode=self._current_voice_mode())+ except Exception as exc: # noqa: BLE001 — a missed repaint is cosmetic+ log.debug("OrbBridge voice-look restore suppressed: %s", exc)+def _show_notice_mode(self) -> None:"""Drive the current surface into its brief "that did not happen" look.@@ -2053,7 +2090,10 @@ class OrbBusBridge:self._dictation_active = Falseself._dictation_transcribing = Falseif self._voice_session_active:- # A session took over and owns the bar — nothing to clean up.+ # The session owns the bar again; show its look, not the+ # dictation's.+ self._show_listening_transcript("")+ self._restore_voice_surface()return# Stand down directly rather than through _schedule_dictation_# standdown: that path also refuses when ``_last_state`` is not@@ -2126,7 +2166,7 @@ class OrbBusBridge:left as-is (already showing Jarvis's reply); no personality quip ispopped over it."""- if self._last_state != "SPEAKING":+ if self._last_state != "SPEAKING" or self._dictation_active:returnlog.info("OrbBridge._on_audio_out_first → speaking overlay + mouth")# Jarvis answers out loud: the thinking is over (an agent task that