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): give the dictation lane sole ownership of the microphone
Ruben Lütke39a1826caf91
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 7f4f733d63..bc240a64e8 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -25,7 +25,7 @@ from collections.abc import AsyncIterator, Awaitable, Callablefrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanagerfrom pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Protocolfrom uuid import uuid4import numpy as np@@ -636,6 +636,32 @@ def _feed_live_mic_level(chunk: AudioChunk) -> None:mic_level.feed(float(np.sqrt(np.mean(np.square(samples)))))+class _ChunkSource(Protocol):+ """Anything one lane can drain audio frames from.++ Satisfied by both ``MicrophoneCapture`` (a lane that opened the device+ itself) and ``_SessionInputBuffer`` (a lane that took over a stream some+ other lane already had open). Having the two behind one shape is what lets+ the dictation lane accept either without a second native input stream.+ """++ def stream(self) -> AsyncIterator[AudioChunk]: ...+++# How long a dictation waits for an ambiguous wake-microphone lease to end+# before it gives up. Only reachable if the handoff itself failed; the honest+# outcome is a refused dictation, never a second stream on the same device.+_DICTATION_WAKE_RELEASE_TIMEOUT_S = 3.0++# Longest gap between two "dictation key is down" reports that still counts as+# ONE hold. The polling hotkey backend re-reports a held chord every few tens of+# milliseconds, and the edge-driven backends (pynput / Quartz) report a press+# exactly once per real chord-down — so nothing legitimate lands anywhere near+# this window, while a press past it can only be a fresh press or a key-up that+# was never delivered. See ``SpeechPipeline._on_dictate_press``.+_DICTATE_HOLD_REPEAT_GRACE_S = 2.0++class _SessionInputBuffer:"""Replayable bounded handoff for one continuously captured mic stream.@@ -1351,6 +1377,10 @@ class SpeechPipeline:# ``_ptt_mode`` for the dictation lane so a repeated press edge (the# Windows backend polls and re-fires on_press while held) is idempotent.self._dictate_key_down = False+ # Monotonic time of the last press edge that reported the key as down.+ # It is what makes the latch above self-healing: see+ # ``_on_dictate_press`` and ``_DICTATE_HOLD_REPEAT_GRACE_S``.+ self._dictate_key_seen_at = 0.0# ``self._stt`` is the LOCAL FasterWhisperProvider used by the wake# backstop + VAD endpoint-probe (many calls/sec, a cloud round-trip# would be too slow). In the cloud-first lightweight path it is None:@@ -4731,9 +4761,45 @@ class SpeechPipeline:Idempotent by design: the Windows backend polls, so ``on_press`` firesagain on every poll while the chord is held. Only the first edge from"key up" starts anything.++ **The latch heals itself.** A key-up edge can be lost — the pynput and+ Quartz backends clear their own chord state without firing ``on_release``+ when the input permission is revoked mid-chord, and a focus change, a+ UAC prompt or an RDP reconnect can do the same. A latch that only a+ release could clear then swallowed EVERY later press, which presents as+ "the dictation shortcut just stopped working" with no error and no way+ back except an app restart. So a press that arrives long after the last+ one reported the key down is treated as what it physically is — a fresh+ press on a key nobody is holding — not as a repeat.++ The two cases are told apart by TIME, not by guessing: a real hold+ re-reports itself every poll tick on the polling backend (tens of+ milliseconds), while the edge-driven backends report a press exactly once+ per real chord-down. Anything past the grace window is therefore either a+ lost key-up or a genuinely new press, and both want the same repair."""- if self._dictate_key_down:- return+ now = time.monotonic()+ last_seen = float(getattr(self, "_dictate_key_seen_at", 0.0))+ latched = bool(getattr(self, "_dictate_key_down", False))+ stale = latched and (now - last_seen) > _DICTATE_HOLD_REPEAT_GRACE_S+ self._dictate_key_seen_at = now+ if latched and not stale:+ return # the same hold, re-reported by a polling backend+ if stale:+ log.info(+ "Dictation key-up edge was lost %.1fs ago — clearing the stale "+ "hold latch so the shortcut keeps working.",+ now - last_seen,+ )+ self._dictate_key_down = False+ if self.dictation_active():+ # The orphaned recording is still running with the microphone+ # open. Treat this press as the release that never arrived:+ # finish and deliver what was said instead of starting a second+ # dictation on top of it. The latch is clear, so the user's next+ # press starts a fresh one.+ self.stop_dictation()+ returnself._dictate_key_down = Trueif not self.start_dictation(target=self._configured_dictation_target()):# Could not start (mic busy, a voice session is live, no STT). Drop@@ -5324,6 +5390,96 @@ class SpeechPipeline:finally:await buffer.close()+ async def _release_unclaimed_wake_handoff(self) -> None:+ """Give back a wake stream that was offered but never taken.++ The wake owner parks on ``buffer.released`` once it has offered its+ stream, so a claimer that unwinds between the offer and the claim would+ strand it there — it cannot even reach its own cleanup. Closing the+ buffer here is the release signal. Safe to call when nothing is pending,+ and it never suspends for an offered handoff (that buffer has no pump+ task), so it also works from inside a task being cancelled.+ """+ buffer = getattr(self, "_wake_handoff_buffer", None)+ ready = getattr(self, "_wake_handoff_ready", None)+ if buffer is None and (ready is None or not ready.is_set()):+ return+ self._wake_handoff_buffer = None+ if ready is not None:+ ready.clear()+ if buffer is not None:+ await buffer.close()++ async def _claim_wake_capture_for_dictation(self) -> _SessionInputBuffer | None:+ """Take the wake microphone over for a dictation, or return ``None``.++ A dictation is a session start like any other: whatever already owns the+ input device hands the live stream over, so the two never run side by+ side. Without this the common case — the wake loop sitting in+ ``_run_parallel_wake``, its steady state whenever Jarvis is idle — meant+ a dictation key press opened a SECOND native input stream on the same+ device for the whole dictation (AP-24 / the BUG-014 family).++ ``None`` means "no wake stream exists"; the caller then opens exactly one+ capture of its own. A pipeline built via ``__new__`` (the unit-test+ pattern) has no wake plumbing at all and takes the same path.+ """+ if getattr(self, "_wake_handoff_ready", None) is None:+ return None+ try:+ return await self._claim_wake_capture_for_session()+ except asyncio.CancelledError:+ # A dictation cancelled INSIDE the handoff window would otherwise+ # leave the wake loop waiting forever on a stream nobody will ever+ # release: permanently deaf with an app restart as the only cure+ # (BUG-037). Give the offered stream back before unwinding.+ await self._release_unclaimed_wake_handoff()+ raise+ except Exception as exc: # noqa: BLE001 — never a crashed dictation+ log.warning("Dictation could not take over the wake microphone: %s", exc)+ await self._release_unclaimed_wake_handoff()+ # The lease ended ambiguously. Waiting for the wake side to finish+ # closing is the only safe way to reach a fallback capture; opening one+ # now could be the second stream this whole path exists to prevent.+ try:+ await asyncio.wait_for(+ self._wake_capture_released.wait(),+ timeout=_DICTATION_WAKE_RELEASE_TIMEOUT_S,+ )+ except TimeoutError:+ raise RuntimeError(+ "The wake microphone did not release in time; refusing to open "+ "a second input stream for this dictation."+ ) from None+ return None++ @asynccontextmanager+ async def _capture_dictation_input(self) -> AsyncIterator[_ChunkSource]:+ """Own exactly ONE microphone for the duration of a dictation.++ Mirrors ``_capture_first_session_input``: borrow the live wake stream+ when there is one, otherwise open a single fallback capture. On the way+ out the borrowed stream is closed and the wake owner is awaited, so the+ wake loop re-arms its own microphone as soon as the dictation's block on+ activation lifts — including on the crash path, because the release runs+ in a ``finally``.+ """+ buffer = await self._claim_wake_capture_for_dictation()+ if buffer is not None:+ try:+ yield buffer+ finally:+ # ``close()`` sets ``released`` before it awaits anything, so+ # the wake owner is freed even if this task is being cancelled.+ await buffer.close()+ await self._wake_capture_released.wait()+ return++ async with MicrophoneCapture(+ device=self._input_device, device_priority=self._input_priority+ ) as mic:+ yield mic+def _wake_listening_enabled(self) -> bool:return self._openwakeword_enabled or self._whisper_wake_enabled@@ -5637,11 +5793,32 @@ class SpeechPipeline:# Jarvis goes deaf immediately — without touching the OS mic.# (A fresh mute while IDLE is already handled by _wake_loop's# _activation_allowed() gate, which never opens the mic.)- if getattr(self, "_muted", False):- continue+ muted = getattr(self, "_muted", False)+ # A dictation is the second way this stream stops belonging+ # to the wake word. It is the same STATE gate the activation+ # predicate uses (never transcript content — AP-27).+ dictating = self._dictation_blocks_activation()if handoff_buffer is not None:+ # The stream has been handed to whoever claimed it. Mute+ # still starves a VOICE session (input-only mute), but+ # never the dictation lane: an explicit dictation press+ # is the user deliberately speaking into their own text+ # field, and the lane's own fallback capture has always+ # ignored mute. Dropping frames here would make a+ # dictation silently record nothing whenever the wake+ # microphone happened to be the one it took over.+ if muted and not dictating:+ continuehandoff_buffer.put(chunk)continue+ if muted or dictating:+ # Nothing claimed the stream, so these frames would go+ # to the wake detectors. While a dictation is running+ # they are the user's dictated words: feeding them to a+ # detector both risks tripping the wake word mid-+ # dictation and shares this native engine with the+ # dictation's own transcription (AP-24).+ continuering_bytes.extend(chunk.pcm)if len(ring_bytes) > RING_MAX:del ring_bytes[: len(ring_bytes) - RING_MAX]@@ -5990,9 +6167,13 @@ class SpeechPipeline:max(0.0, self._wake_lock_until - now),)else:+ # Same resolver as every other gated site —+ # a hardcoded guess here named the wrong+ # cause during a live diagnosis.log.info(- "Wake detection discarded: desktop "- "activation is unavailable."+ "Wake detection discarded: %s.",+ self._activation_block_reason()+ or "activation not allowed",)break# The UI consumes WakeWordDetected plus supervisor@@ -6045,7 +6226,13 @@ class SpeechPipeline:# Ignore activation edges that arrive inside the speaker-echo lock.now = time.time()if not self._activation_allowed():- log.info("Voice call ignored: desktop activation is unavailable.")+ # Resolved, never guessed: this backstop closes for a mute and+ # for a running dictation too, and a log line that names the+ # window instead is exactly what misled an earlier diagnosis.+ log.info(+ "Voice call ignored: %s.",+ self._activation_block_reason() or "activation not allowed",+ )# A discarded call consumes any PTT arming with it — otherwise a# stale ``_ptt_mode`` would reroute the NEXT (wake-word) call# into the raw-recording path that has no key to release.@@ -7705,7 +7892,8 @@ class SpeechPipeline:async def _dictation_session(self) -> None:"""Capture mic audio, transcribe it in segments, deliver the result.- A stripped-down ``_ptt_session``: open the mic, drain into a buffer,+ A stripped-down ``_ptt_session``: take the one microphone over (or open+ it when nothing else holds it), drain into a buffer,publish a live ``DictationTranscript`` while speaking, and on the stopevent (or the max-duration cap) produce the final text, clean it, and —when the target is ``insert`` — paste it into the focused field of@@ -7883,12 +8071,14 @@ class SpeechPipeline:# up" and never runs the delivery twice.finished = Falsetry:- async with MicrophoneCapture(- device=self._input_device, device_priority=self._input_priority- ) as mic:+ # ONE microphone owner at a time: this takes the live wake stream+ # over when there is one and opens its own capture otherwise, so a+ # dictation never runs a second native input stream beside the wake+ # loop's (AP-24). The wake side gets its stream back on exit.+ async with self._capture_dictation_input() as source:async def _drain() -> None:- async for chunk in mic.stream():+ async for chunk in source.stream():buffer.extend(chunk.pcm)# Feed the live loudness so the bar's equalizer moves# while dictating — same normalized RMS as the VAD anddiff --git a/tests/unit/dictation/test_dictate_keybind.py b/tests/unit/dictation/test_dictate_keybind.pyindex ada53deb8d..7aba5c1940 100644--- a/tests/unit/dictation/test_dictate_keybind.py+++ b/tests/unit/dictation/test_dictate_keybind.py@@ -9,9 +9,11 @@ debugger, was accepted.from __future__ import annotationsimport asyncio+import timeimport pytest+import jarvis.speech.pipeline as pipeline_modfrom jarvis.core.config import DictationConfig, TriggerConfigfrom jarvis.core.config_writer import KEYBIND_ACTIONS, KEYBIND_TOML_KEYfrom jarvis.speech.pipeline import PipelineState, SpeechPipeline@@ -221,7 +223,13 @@ class _RecordingPipeline(SpeechPipeline):def test_press_starts_once_even_though_the_backend_polls() -> None:- """The Windows backend re-fires on_press while the chord is held."""+ """The Windows backend re-fires on_press while the chord is held.++ This pins the idempotency of a HELD key — repeats that arrive inside the+ grace window are one dictation. It deliberately does NOT pin the latch as+ permanent: a press that arrives long after the last one is a fresh press,+ which is what keeps a lost key-up from disabling the shortcut (below).+ """pipe = _RecordingPipeline()pipe._on_dictate_press()pipe._on_dictate_press()@@ -231,6 +239,71 @@ def test_press_starts_once_even_though_the_backend_polls() -> None:assert pipe.started == ["auto"]+def test_a_hold_is_still_one_dictation_late_inside_the_grace_window() -> None:+ """A slow poll tick is still the same hold, not a new press."""+ pipe = _RecordingPipeline()+ pipe._on_dictate_press()+ pipe._dictate_key_seen_at = time.monotonic() - (+ pipeline_mod._DICTATE_HOLD_REPEAT_GRACE_S - 0.5+ )+ pipe._on_dictate_press()+ assert pipe.started == ["auto"]+ assert pipe._dictate_key_down is True+++def test_a_lost_key_up_never_swallows_the_next_press() -> None:+ """The stuck-latch defect: no error, no way back except an app restart.++ A key-up edge really can go missing — the pynput and Quartz backends clear+ their own chord state WITHOUT firing ``on_release`` when the input+ permission is revoked mid-chord, and a focus change, a UAC prompt or an RDP+ reconnect can do the same. The latch has to heal itself.+ """+ pipe = _RecordingPipeline()+ pipe._on_dictate_press()+ assert pipe._dictate_key_down is True++ # The release never arrives; time passes; the user presses again. The+ # earlier dictation is already over (duration cap), so nothing to stop.+ pipe._dictate_key_seen_at = time.monotonic() - (+ pipeline_mod._DICTATE_HOLD_REPEAT_GRACE_S + 1.0+ )+ pipe._on_dictate_press()++ assert pipe.started == ["auto", "auto"], "the shortcut must keep working"+ assert pipe._dictate_key_down is True+ assert pipe.stopped == 0+++def test_a_stale_press_ends_an_orphaned_recording_instead_of_stacking_one() -> None:+ """A lost key-up leaves the microphone open; the next press is the release.++ Starting a second dictation on top is impossible anyway (the lane refuses+ while one runs), so the honest repair is to finish and deliver the orphan.+ The latch is clear afterwards, so the following press records normally.+ """+ pipe = _RecordingPipeline()++ class _RunningTask:+ def done(self) -> bool:+ return False++ pipe._on_dictate_press()+ pipe._dictation_task = _RunningTask() # type: ignore[assignment]+ pipe._dictate_key_seen_at = time.monotonic() - (+ pipeline_mod._DICTATE_HOLD_REPEAT_GRACE_S + 1.0+ )+ pipe._on_dictate_press()++ assert pipe.stopped == 1+ assert pipe.started == ["auto"]+ assert pipe._dictate_key_down is False++ pipe._dictation_task = None+ pipe._on_dictate_press()+ assert pipe.started == ["auto", "auto"]++def test_the_key_follows_the_configured_target() -> None:pipe = _RecordingPipeline()pipe._dictation_cfg = DictationConfig(target="chat")diff --git a/tests/unit/speech/test_dictation_mic_handoff.py b/tests/unit/speech/test_dictation_mic_handoff.pynew file mode 100644index 0000000000..1142767253--- /dev/null+++ b/tests/unit/speech/test_dictation_mic_handoff.py@@ -0,0 +1,372 @@+"""One microphone owner at a time — a dictation takes the wake stream over.++The wake loop sits inside ``_run_parallel_wake`` with the input device open+whenever Jarvis is idle, which is exactly the state the dictation shortcut is+pressed in. Opening the dictation's own capture there meant TWO native input+streams on one device for the whole dictation: the BUG-014 family, and a shared+native engine between concurrent callers (AP-24).++So the dictation lane goes through the same single-owner handoff every other+session start uses. The tests that matter most are the ones about giving the+stream BACK: a dictation that ends normally, one that is cancelled mid-recording,+and one whose audio source dies under it must all leave the wake loop able to+re-arm its own microphone — a wake word that never comes back is BUG-037, whose+only cure is an app restart.+"""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator++import pytest++import jarvis.speech.pipeline as pipeline_mod+from jarvis.core.config import DictationConfig+from jarvis.core.protocols import AudioChunk+from jarvis.speech.pipeline import PipelineState, SpeechPipeline+++class _FakeTTS:+ name = "fake-tts"+ supports_streaming = False++ async def synthesize(self, text: str, **_kwargs) -> AsyncIterator[bytes]:+ if False: # pragma: no cover - protocol-shaped empty iterator+ yield text.encode()+++class _StubSTT:+ """Returns nothing, so no test here depends on a transcription."""++ async def transcribe_pcm(self, pcm: bytes, **_kwargs):+ class _Empty:+ text = ""+ language = ""++ return _Empty()+++class _ControlledMic:+ """A microphone whose open/close edges and frames the test drives."""++ def __init__(self) -> None:+ self.frames: asyncio.Queue[AudioChunk | BaseException] = asyncio.Queue()+ self.entered = asyncio.Event()+ self.open_count = 0+ self.close_count = 0+ self.closed = False++ async def __aenter__(self) -> _ControlledMic:+ self.open_count += 1+ self.closed = False+ self.entered.set()+ return self++ async def __aexit__(self, *_exc: object) -> bool:+ self.closed = True+ self.close_count += 1+ return False++ async def stream(self) -> AsyncIterator[AudioChunk]:+ while True:+ item = await self.frames.get()+ if isinstance(item, BaseException):+ raise item+ yield item+++class _NeverWake:+ async def detect(self, chunks: AsyncIterator[AudioChunk]) -> AsyncIterator[str]:+ async for _chunk in chunks:+ await asyncio.Event().wait()+ if False: # pragma: no cover - protocol-shaped async iterator+ yield ""+++def _chunk(pcm: bytes) -> AudioChunk:+ return AudioChunk(pcm=pcm, sample_rate=16_000, timestamp_ns=1)+++def _wake_pipeline(+ monkeypatch: pytest.MonkeyPatch,+) -> tuple[SpeechPipeline, _ControlledMic, list[int]]:+ """A pipeline whose every ``MicrophoneCapture`` is the same fake device."""+ mic = _ControlledMic()+ factory_calls: list[int] = []++ def _mic_factory(**_kwargs) -> _ControlledMic:+ factory_calls.append(1)+ return mic++ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _mic_factory)+ pipeline = SpeechPipeline(tts=_FakeTTS(), bus=None, enable_whisper_wake=False)+ pipeline._openwakeword_enabled = True+ pipeline._whisper_wake_enabled = False+ pipeline._wake = _NeverWake() # type: ignore[assignment]+ pipeline._utterance_stt = _StubSTT()+ # No live preview: this file is about the microphone lease, not transcription.+ pipeline._dictation_cfg = DictationConfig(partial_interval_s=0.0)+ pipeline._state = PipelineState.IDLE++ async def _no_delivery(**_kwargs) -> str:+ return ""++ pipeline._finish_dictation = _no_delivery # type: ignore[assignment]+ return pipeline, mic, factory_calls+++# --------------------------------------------------------------------------+# The handoff itself+# --------------------------------------------------------------------------+++async def test_a_dictation_takes_the_live_wake_microphone_instead_of_opening_one(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline, mic, factory_calls = _wake_pipeline(monkeypatch)++ wake_task = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)+ assert len(factory_calls) == 1++ marker = _chunk(b"dictated-word")+ async with pipeline._capture_dictation_input() as source:+ # Still exactly one device open, and it is the wake loop's.+ assert len(factory_calls) == 1+ assert mic.closed is False+ await mic.frames.put(marker)+ assert await asyncio.wait_for(anext(source.stream()), timeout=1.0) is marker++ await asyncio.wait_for(wake_task, timeout=1.0)+ assert len(factory_calls) == 1+ assert mic.open_count == 1+ assert mic.close_count == 1+ assert pipeline._wake_capture_released.is_set()+++async def test_a_dictation_opens_one_capture_when_no_wake_stream_exists(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The headless / wake-parked case: nothing to take over, so open one."""+ pipeline, mic, factory_calls = _wake_pipeline(monkeypatch)+ assert pipeline._wake_capture_released.is_set()++ async with pipeline._capture_dictation_input() as source:+ assert len(factory_calls) == 1+ marker = _chunk(b"first-word")+ await mic.frames.put(marker)+ assert await asyncio.wait_for(anext(source.stream()), timeout=1.0) is marker++ assert mic.close_count == 1+++async def test_a_pipeline_without_wake_plumbing_still_dictates() -> None:+ """Unit-test pipelines built via ``__new__`` have no handoff events."""+ bare = SpeechPipeline.__new__(SpeechPipeline)+ assert await bare._claim_wake_capture_for_dictation() is None+++# --------------------------------------------------------------------------+# Giving the stream back — the part a restart would otherwise be needed for+# --------------------------------------------------------------------------+++async def test_the_wake_loop_gets_its_microphone_back_after_a_dictation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Full lane: start the dictation, stop it, and re-arm wake on one device."""+ pipeline, mic, factory_calls = _wake_pipeline(monkeypatch)++ wake_task = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)++ assert pipeline.start_dictation(target="chat") is True+ dictation = pipeline._dictation_task+ assert dictation is not None+ # The wake stream is handed over, not duplicated.+ await asyncio.wait_for(pipeline._wake_handoff_ready.wait(), timeout=1.0)+ await mic.frames.put(_chunk(b"\x01\x02" * 8_000))+ await asyncio.sleep(0)+ assert len(factory_calls) == 1++ pipeline.stop_dictation()+ await asyncio.wait_for(dictation, timeout=2.0)+ await asyncio.wait_for(wake_task, timeout=1.0)++ assert mic.open_count == 1+ assert mic.close_count == 1+ assert pipeline._wake_capture_released.is_set()+ # And the gate that kept wake quiet is open again, so the next+ # ``_run_parallel_wake`` can re-open the device.+ assert pipeline._dictation_blocks_activation() is False++ mic.entered.clear()+ rearmed = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)+ assert mic.open_count == 2+ rearmed.cancel()+ with pytest.raises(asyncio.CancelledError):+ await rearmed+++async def test_a_cancelled_dictation_still_releases_the_wake_microphone(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The crash path: nothing runs an orderly stop, and wake must still return."""+ pipeline, mic, _factory_calls = _wake_pipeline(monkeypatch)++ wake_task = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)++ assert pipeline.start_dictation(target="chat") is True+ dictation = pipeline._dictation_task+ assert dictation is not None+ await asyncio.wait_for(pipeline._wake_handoff_ready.wait(), timeout=1.0)++ dictation.cancel()+ with pytest.raises(asyncio.CancelledError):+ await dictation++ await asyncio.wait_for(wake_task, timeout=1.0)+ assert mic.close_count == 1+ assert pipeline._wake_capture_released.is_set()+ assert pipeline._dictation_blocks_activation() is False+++async def test_a_dying_audio_source_ends_the_dictation_and_frees_wake(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The device disappears mid-dictation — both lanes have to unwind."""+ pipeline, mic, _factory_calls = _wake_pipeline(monkeypatch)++ wake_task = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)++ assert pipeline.start_dictation(target="chat") is True+ dictation = pipeline._dictation_task+ assert dictation is not None+ await asyncio.wait_for(pipeline._wake_handoff_ready.wait(), timeout=1.0)++ await mic.frames.put(RuntimeError("input device went away"))++ await asyncio.wait_for(dictation, timeout=2.0)+ await asyncio.wait_for(wake_task, timeout=1.0)+ assert mic.close_count == 1+ assert pipeline._wake_capture_released.is_set()+++# --------------------------------------------------------------------------+# The detectors must not eat the dictated words (AP-24)+# --------------------------------------------------------------------------+++async def test_the_wake_detectors_are_starved_while_a_dictation_runs(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A dictation that did NOT take the stream still must not feed wake.++ Reachable whenever the wake microphone opens while a dictation is already+ recording on its own capture. Feeding those frames to a detector both risks+ tripping the wake word on the user's dictated words and runs a second+ consumer on the same native engine.+ """+ pipeline, mic, _factory_calls = _wake_pipeline(monkeypatch)++ seen: list[AudioChunk] = []++ class _CountingWake:+ async def detect(self, chunks: AsyncIterator[AudioChunk]) -> AsyncIterator[str]:+ async for chunk in chunks:+ seen.append(chunk)+ if False: # pragma: no cover - protocol-shaped async iterator+ yield ""++ pipeline._wake = _CountingWake() # type: ignore[assignment]++ wake_task = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)++ await mic.frames.put(_chunk(b"before"))+ for _ in range(6):+ await asyncio.sleep(0)+ assert len(seen) == 1++ # A dictation is now running on its own capture (the gate is a plain state+ # gate, so the test can set it exactly as ``start_dictation`` does).+ blocking = asyncio.create_task(asyncio.Event().wait())+ pipeline._dictation_task = blocking # type: ignore[assignment]+ pipeline._dictation_wake_block_until = pipeline_mod.time.time() + 300.0+ try:+ await mic.frames.put(_chunk(b"dictated"))+ for _ in range(6):+ await asyncio.sleep(0)+ assert len(seen) == 1, "dictated audio must never reach a wake detector"+ finally:+ blocking.cancel()+ pipeline._dictation_task = None++ await mic.frames.put(_chunk(b"after"))+ for _ in range(6):+ await asyncio.sleep(0)+ assert len(seen) == 2, "wake hears again the moment the dictation is over"++ wake_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await wake_task+++async def test_a_wake_dropped_by_a_dictation_says_so_in_the_log(+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+) -> None:+ """The pre-emit gate used to hardcode "desktop activation is unavailable".++ That line is read during live diagnoses, and naming the window when the real+ cause is a running dictation is exactly the wrong-cause detour the shared+ reason resolver exists to prevent.+ """+ pipeline, mic, _factory_calls = _wake_pipeline(monkeypatch)++ release = asyncio.Event()++ class _HeldWake:+ async def detect(self, chunks: AsyncIterator[AudioChunk]) -> AsyncIterator[str]:+ await anext(chunks)+ await release.wait()+ yield "jarvis"++ pipeline._wake = _HeldWake() # type: ignore[assignment]++ async def _verified(_pcm: bytes) -> bool:+ return True++ pipeline._verify_oww_hit = _verified # type: ignore[method-assign]++ wake_task = asyncio.create_task(pipeline._run_parallel_wake())+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)+ await mic.frames.put(_chunk(b"hey"))+ for _ in range(6):+ await asyncio.sleep(0)++ blocking = asyncio.create_task(asyncio.Event().wait())+ pipeline._dictation_task = blocking # type: ignore[assignment]+ pipeline._dictation_wake_block_until = pipeline_mod.time.time() + 300.0+ try:+ with caplog.at_level("INFO", logger="jarvis.speech.pipeline"):+ release.set()+ await asyncio.wait_for(wake_task, timeout=2.0)+ messages = [r.getMessage() for r in caplog.records]+ assert any(+ "Wake detection discarded: a dictation is running" in m for m in messages+ ), messages+ finally:+ blocking.cancel()+ pipeline._dictation_task = Nonediff --git a/tests/unit/speech/test_dictation_wake_gate.py b/tests/unit/speech/test_dictation_wake_gate.pyindex bb33c06525..c99aef79ce 100644--- a/tests/unit/speech/test_dictation_wake_gate.py+++ b/tests/unit/speech/test_dictation_wake_gate.py@@ -179,6 +179,52 @@ def test_a_closed_capture_gate_is_named_without_guessing() -> None:assert "microphone capture is not permitted" in pipe._activation_block_reason()+# --------------------------------------------------------------------------+# Every gated site names the REAL reason+# --------------------------------------------------------------------------+++async def test_the_state_loop_names_the_dictation_instead_of_guessing(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """A hardcoded reason here once sent a live diagnosis after the wrong cause.++ The state loop is the backstop that drops an activation edge; it closes for+ a mute and for a running dictation too, so "the desktop window is not+ available" is a guess that can be flatly wrong.+ """+ pipe = _gate_pipeline()+ pipe._call_event = asyncio.Event()+ pipe._ptt_mode = False+ pipe._dictation_task = asyncio.create_task(_blocking_task())+ pipe._dictation_wake_block_until = time.time() + 300.0++ aborted = asyncio.Event()++ async def _abort() -> None:+ aborted.set()++ pipe._abort_pending_wake_handoff = _abort # type: ignore[method-assign]++ loop_task = asyncio.create_task(pipe._state_loop())+ try:+ with caplog.at_level("INFO", logger="jarvis.speech.pipeline"):+ pipe._call_event.set()+ await asyncio.wait_for(aborted.wait(), timeout=1.0)+ messages = [r.getMessage() for r in caplog.records]+ assert any("a dictation is running" in m for m in messages), messages+ assert not any("desktop activation is unavailable" in m for m in messages)+ finally:+ loop_task.cancel()+ pipe._dictation_task.cancel()+ for task in (loop_task, pipe._dictation_task):+ try:+ await task+ except asyncio.CancelledError:+ pass++# --------------------------------------------------------------------------# The bar must not flicker out of its dictation look# --------------------------------------------------------------------------