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(audio): follow headset plug and unplug at runtime on every OS
Ruben Lütkede6468df7b7c
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 4b052f7606..b364a55876 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -7003,3 +7003,51 @@ module contract), `tests/unit/speech/test_echo_guard.py` +`tests/unit/realtime/test_session_self_echo.py` (strict short judgment isbarge-scoped; replay of session c77b7a88's turns 4/5). Physical validation onthe Mac speakers+mic setup remains pending.++---++## BUG-102: audio devices frozen at process start — plugging or pulling a headset lags and breaks voice until restart (HIGH, FIXED IN CODE 2026-07-20; HARDWARE VALIDATION PENDING)++**Symptom.** Mac live test 2026-07-20: plugging wired headphones into the+MacBook made the whole voice loop lag heavily; unplugging them left voice+broken AND laggy until an app restart. The settings pinned the microphone to+the jack's device by name while output stood on automatic.++**Reconstruction.** PortAudio freezes its device table at initialization —+the process never sees devices arriving or leaving, on ANY OS. Three layers+degrade at once. (1) The persistent output stream keeps writing to the+no-longer-default or vanished device: blocking writes stall for seconds,+watchdogs fire, everything downstream feels laggy. (2) The mic stall+watchdog does reopen after ~3 s of silence — but only against the STALE+table, so it retries the dead endpoint forever and can never find the newly+arrived one. (3) Boot-time device settling (`device_init`) and the Settings+rescan (out-of-process probe) both exist, but NOTHING watched the topology+at runtime.++**Fix (`jarvis/audio/topology.py`, cross-platform by construction).**+A post-ready watcher polls the existing out-of-process device probe (safe+while this process holds live streams) every 5 s and reduces each snapshot+to a name-based signature (devices + default pair — never indices). On a+settled change it performs the ONE safe refresh sequence: discard every+registered capture stream and the player's stream FIRST (re-init with live+streams is the BUG-058 native-fault path), re-initialize PortAudio under the+established re-init lock, then invalidate every resolve/device cache and+re-resolve the configured output spec. Reopening is owned by the existing+self-healers: the mic watchdog fires on its next one-second tick (heartbeat+backdated by `discard_native_stream`) and the player reopens lazily on the+next playback. Every native stream open now holds `stream_open_guard()` so+no stream can be born between terminate and initialize. Headless installs+short-circuit before ever spawning the probe. Nothing runs on the boot+critical path (AP-26).++**Class rule.** PortAudio's device table is immutable per initialization:+any long-running voice process MUST either watch topology and re-init+(coordinated, streams quiesced first) or accept death on the first hot-swap.+A name-pinned device is an automatic choice by contract — when it vanishes,+resolution falls over to a real device and comes back when the name returns.++**Guards.** `tests/unit/audio/test_topology.py`: signature identity (index+shuffles invisible, unplug + default move visible), one refresh per settled+change, probe outage fails open, refresh order (quiesce → re-init →+invalidate → re-resolve), watchdog heartbeat backdating. Physical+plug/unplug validation on macOS/Windows/Linux remains pending.diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.pyindex e49b89e976..b61cb4b642 100644--- a/jarvis/audio/capture.py+++ b/jarvis/audio/capture.py@@ -30,6 +30,7 @@ else:except Exception: # noqa: BLE001 — sounddevice/PortAudio (libportaudio2) absent (headless/slim)sd = None # type: ignore[assignment]+from jarvis.audio import topologyfrom jarvis.audio.device_select import is_legacy_primary_mapperfrom jarvis.core.protocols import AudioChunk@@ -808,15 +809,38 @@ class MicrophoneCapture:capture_rate, self._sample_rate, self._channels))- stream = sd.InputStream(- device=attempt,- channels=self._channels,- samplerate=capture_rate,- blocksize=capture_blocksize,- dtype=DTYPE,- callback=self._callback,+ # The guard keeps this open out of the PortAudio re-init+ # window of the hot-swap watcher (BUG-102): a stream born+ # between _terminate and _initialize is a native fault. The+ # open runs OFF the event loop so a refresh holding the+ # guard stalls only this open, never the whole loop.+ def _guarded_open(+ device: int | str | None, rate: int, blocksize: int+ ) -> Any:+ with topology.stream_open_guard():+ opened = sd.InputStream(+ device=device,+ channels=self._channels,+ samplerate=rate,+ blocksize=blocksize,+ dtype=DTYPE,+ callback=self._callback,+ )+ try:+ opened.start()+ except BaseException:+ # The failed native stream must not leak — the+ # outer candidate loop only sees the exception.+ try:+ opened.close()+ except Exception: # noqa: BLE001, S110+ pass+ raise+ return opened++ stream = await asyncio.to_thread(+ _guarded_open, attempt, capture_rate, capture_blocksize)- stream.start()self._stream = streamself._device = attemptself._using_physical_fallback = physical_fallback@@ -923,30 +947,10 @@ class MicrophoneCapture:old_stream = self._streamself._stream = Noneif old_stream is not None:- # A stalled callback stream cannot drain gracefully. In- # particular, CoreAudio may leave ``InputStream.stop()``- # blocked inside PortAudio for minutes after an endpoint or- # power-state transition. Abort discards the dead native- # stream immediately, matching AudioPlayer's established- # device-wedge recovery contract. Every sounddevice stream- # exposes ``abort``; the ``stop`` fallback keeps lightweight- # test/third-party stream doubles compatible.- discard_method = "abort"- try:- abort = getattr(old_stream, "abort", None)- if callable(abort):- abort()- else:- discard_method = "stop"- old_stream.stop()- except Exception as exc: # noqa: BLE001- _log.debug(- "Mic-Restart: {}() ignored ({}).", discard_method, exc- )- try:- old_stream.close()- except Exception as exc: # noqa: BLE001- _log.debug("Mic-Restart: close() ignored ({}).", exc)+ # A stalled callback stream cannot drain gracefully — see+ # ``_discard_stream`` (abort-first, CoreAudio ``stop()`` can+ # block for minutes after an endpoint transition).+ self._discard_stream(old_stream)try:await self._try_open_stream()_log.info("Mic-Restart #{} succeeded.", self._restart_count)@@ -963,6 +967,51 @@ class MicrophoneCapture:# Reset the heartbeat — grace window for the first frame after reopen.self._last_chunk_monotonic = time.monotonic()+ def discard_native_stream(self) -> None:+ """Drop the native stream so the stall watchdog reopens it (BUG-102).++ Called by the topology watcher (worker thread) right before a+ PortAudio re-init: the old stream belongs to the dying PortAudio+ instance and must not survive it. Backdating the heartbeat makes the+ watchdog fire on its next one-second tick instead of waiting out the+ full stall threshold, so the audible mic gap stays minimal.+ """+ stream, self._stream = self._stream, None+ if stream is not None:+ self._discard_stream(stream)+ if not isinstance(self._device_spec, int):+ # Indices renumber across a PortAudio re-init; retrying the stale+ # resolved index first could silently open a DIFFERENT physical+ # device. Re-enter name/auto resolution against the fresh table.+ self._preferred_device = self._device_spec+ self._last_chunk_monotonic = min(+ self._last_chunk_monotonic,+ time.monotonic() - self._STALL_THRESHOLD_S - 1.0,+ )++ @staticmethod+ def _discard_stream(stream: Any) -> None:+ """Abort-then-close a (possibly wedged) native stream, never raising.++ Abort discards the dead native stream immediately; CoreAudio can+ leave ``stop()`` blocked for minutes after an endpoint transition.+ The ``stop`` fallback keeps lightweight test doubles compatible.+ """+ discard_method = "abort"+ try:+ abort = getattr(stream, "abort", None)+ if callable(abort):+ abort()+ else:+ discard_method = "stop"+ stream.stop()+ except Exception as exc: # noqa: BLE001+ _log.debug("Mic discard: {}() ignored ({}).", discard_method, exc)+ try:+ stream.close()+ except Exception as exc: # noqa: BLE001+ _log.debug("Mic discard: close() ignored ({}).", exc)+async def __aenter__(self) -> MicrophoneCapture:self._loop = asyncio.get_running_loop()await self._try_open_stream()@@ -971,9 +1020,13 @@ class MicrophoneCapture:self._watchdog_task = asyncio.create_task(self._stream_watchdog(), name="mic-stall-watchdog")+ # Visible to the hot-swap watcher so a PortAudio re-init can quiesce+ # this stream first (BUG-102).+ topology.register_capture(self)return selfasync def __aexit__(self, *exc_info) -> None:+ topology.unregister_capture(self)self._closed = Truewatchdog = self._watchdog_taskself._watchdog_task = Nonediff --git a/jarvis/audio/player.py b/jarvis/audio/player.pyindex 9d4607a237..5b891888b2 100644--- a/jarvis/audio/player.py+++ b/jarvis/audio/player.py@@ -28,7 +28,7 @@ else:except Exception: # noqa: BLE001 — sounddevice/PortAudio (libportaudio2) absent (headless/slim)sd = None # type: ignore[assignment]-from jarvis.audio import echo_reference, level_tap+from jarvis.audio import echo_reference, level_tap, topologyfrom jarvis.audio.device_select import is_legacy_primary_mapperfrom jarvis.audio.gain import apply_output_gain, clamp_volumefrom jarvis.core.events import AudioOutFirst@@ -694,15 +694,19 @@ class AudioPlayer:# slowdown" to this 10 ms drain. 0.2 s matches the buffer# depth used by LiveKit-Agents / Pipecat / RealtimeTTS for# TTS-streaming on WASAPI shared mode.- stream = sd.OutputStream(- samplerate=target_rate,- device=self._device,- channels=stream_channels,- dtype="float32",- blocksize=0,- latency=0.2,- )- stream.start()+ # Guarded against the hot-swap watcher's PortAudio re-init+ # window (BUG-102): a stream born between _terminate and+ # _initialize is a native fault.+ with topology.stream_open_guard():+ stream = sd.OutputStream(+ samplerate=target_rate,+ device=self._device,+ channels=stream_channels,+ dtype="float32",+ blocksize=0,+ latency=0.2,+ )+ stream.start()self._stream_channels = stream_channelsself._device_rate_cache[cache_key] = target_ratelog.info(diff --git a/jarvis/audio/topology.py b/jarvis/audio/topology.pynew file mode 100644index 0000000000..3f3f1fc30d--- /dev/null+++ b/jarvis/audio/topology.py@@ -0,0 +1,220 @@+"""Runtime audio-device hot-swap watcher (BUG-102).++PortAudio freezes its device table at initialization, so a process that runs+for hours never sees a headset being plugged in or pulled out. Every layer+above therefore degrades at once: the persistent output stream keeps writing+to a vanished or no-longer-default device (blocking writes, seconds-long+stalls — perceived as "everything lags"), and the microphone watchdog can+only re-open devices from the stale table, so it retries a dead endpoint+forever and can never find the newly arrived one.++This module owns the ONE cross-platform cure, in three parts:++1. **Detection** — poll the out-of-process device probe+ (`jarvis.audio.devices._query_tables_fresh`), which is safe while this+ process holds live streams, and compare a name-based topology signature.+ No OS-specific listener; Windows, macOS, and Linux share the poller.+2. **Coordinated refresh** — when the topology changed: discard every+ registered capture stream and the player's output stream, re-initialize+ PortAudio under the established re-init lock (safe ONLY with no live+ streams — the BUG-058 native-fault hazard), and invalidate every resolve+ cache. The existing self-healers do the rest: the mic stall watchdog+ reopens against the now-fresh table within ~a second, and the player+ reopens lazily on the next playback.+3. **The open guard** — every native stream open holds ``stream_open_guard``+ so no stream can come to life BETWEEN terminate and initialize.++Everything fails open: a failed probe means "no judgment", a failed refresh+leaves the process exactly where it was, and a headless install without+sounddevice never gets past the first probe. Nothing here runs on the boot+critical path (AP-26) — the watcher starts after honest voice readiness.+"""++from __future__ import annotations++import asyncio+import contextlib+import logging+import threading+import weakref+from collections.abc import Callable+from typing import Any++log = logging.getLogger("jarvis.audio.topology")++# Serializes native stream opens against the PortAudio re-init window. An+# RLock so a guarded open path may nest (candidate loops re-enter freely).+_OPEN_LOCK = threading.RLock()++# Live MicrophoneCapture instances that a refresh must quiesce. WeakSet: a+# capture that forgot to unregister can never be kept alive by the watcher.+# The lock covers every add/discard/snapshot — the event loop registers+# captures while the refresh worker thread iterates, and a bare WeakSet is+# not safe against that ("set changed size during iteration").+_captures_lock = threading.Lock()+_captures: weakref.WeakSet[Any] = weakref.WeakSet()++DEFAULT_POLL_S = 5.0+# One burst of CoreAudio/WASAPI events accompanies a single physical plug;+# wait this long after the first divergent signature so the refresh runs once+# against the settled topology instead of once per event.+_SETTLE_S = 1.5+++def stream_open_guard() -> threading.RLock:+ """Lock every native PortAudio stream open must hold (``with ...():``)."""+ return _OPEN_LOCK+++def register_capture(capture: Any) -> None:+ with _captures_lock:+ _captures.add(capture)+++def unregister_capture(capture: Any) -> None:+ with _captures_lock:+ _captures.discard(capture)+++def topology_signature(tables: Any) -> str | None:+ """Reduce a device-table snapshot to a comparable identity string.++ Built from device NAMES with their I/O roles plus the default pair —+ never from indices, which shuffle on every enumeration and would cause+ refresh churn without any physical change.+ """+ if not tables:+ return None+ devices, _hostapis, defaults = tables+ entries = []+ for device in devices:+ has_input = int(device.get("max_input_channels") or 0) > 0+ has_output = int(device.get("max_output_channels") or 0) > 0+ if not (has_input or has_output):+ continue+ name = " ".join(str(device.get("name", "")).split()).casefold()+ entries.append(f"{name}|{int(has_input)}{int(has_output)}")++ def _default_name(index: int | None) -> str:+ if index is None or not 0 <= index < len(devices):+ return ""+ return " ".join(str(devices[index].get("name", "")).split()).casefold()++ return (+ ";".join(sorted(entries))+ + f"##in={_default_name(defaults[0])}##out={_default_name(defaults[1])}"+ )+++def _fresh_signature() -> str | None:+ try:+ import sounddevice # noqa: F401, PLC0415 — headless short-circuit+ except Exception: # noqa: BLE001 — no audio stack → never spawn the probe+ return None+ from jarvis.audio.devices import _query_tables_fresh++ return topology_signature(_query_tables_fresh())+++def refresh_audio_backend(player: Any, output_device: Any = None) -> bool:+ """Coordinated PortAudio re-init after a topology change. Worker-thread.++ Order matters: quiesce every native stream FIRST (a terminate with live+ streams is the BUG-058 native-fault path), then re-init under the shared+ boot re-init lock, then drop every stale resolve cache. Reopening is left+ to the owners — the capture watchdog and the player's lazy open — so this+ function never creates a stream itself.+ """+ try:+ import sounddevice as sd # noqa: PLC0415 — desktop-only optional dep+ except Exception: # noqa: BLE001 — headless install+ return False+ try:+ from jarvis.audio.capture import _invalidate_resolve_cache+ from jarvis.audio.device_init import _REINIT_LOCK++ with _OPEN_LOCK:+ with _captures_lock:+ captures = list(_captures)+ for capture in captures:+ try:+ capture.discard_native_stream()+ except Exception: # noqa: BLE001 — one dead capture never blocks+ log.debug(+ "Capture discard during refresh failed", exc_info=True+ )+ if player is not None:+ try:+ player.invalidate_device_cache()+ except Exception: # noqa: BLE001+ log.debug(+ "Player invalidate during refresh failed", exc_info=True+ )+ with _REINIT_LOCK:+ with contextlib.suppress(Exception):+ sd._terminate()+ try:+ sd._initialize()+ except Exception as exc: # noqa: BLE001+ log.warning("PortAudio re-initialization failed: %s", exc)+ return False+ _invalidate_resolve_cache()+ if player is not None:+ # Re-resolve the CONFIGURED spec against the fresh table; a+ # stale resolved index must never survive the re-init.+ with contextlib.suppress(Exception):+ player.set_device(output_device)+ except Exception: # noqa: BLE001 — a failed refresh must never kill the watcher+ log.warning("Audio backend refresh failed", exc_info=True)+ return False+ return True+++async def watch_topology(+ player: Any,+ output_device: Any = None,+ *,+ poll_s: float = DEFAULT_POLL_S,+ probe: Callable[[], str | None] | None = None,+ refresh: Callable[[], bool] | None = None,+) -> None:+ """Poll for device hot-swap and refresh the audio backend on change.++ Runs forever; the owner cancels it on shutdown. ``probe``/``refresh`` are+ injectable for tests; the defaults use the out-of-process device probe+ and :func:`refresh_audio_backend`.+ """+ probe = probe or _fresh_signature+ refresh = refresh or (lambda: refresh_audio_backend(player, output_device))+ last: str | None = None+ while True:+ await asyncio.sleep(poll_s)+ signature = await asyncio.to_thread(probe)+ if signature is None:+ # Probe unavailable (headless, worker timeout) — no judgment.+ continue+ if last is None:+ last = signature+ continue+ if signature == last:+ continue+ await asyncio.sleep(_SETTLE_S)+ settled = await asyncio.to_thread(probe) or signature+ log.info(+ "Audio device topology changed — refreshing the audio backend "+ "(streams reopen automatically)."+ )+ ok = await asyncio.to_thread(refresh)+ log.info("Audio backend refresh %s.", "completed" if ok else "failed")+ last = settled+++__all__ = [+ "DEFAULT_POLL_S",+ "refresh_audio_backend",+ "register_capture",+ "stream_open_guard",+ "topology_signature",+ "unregister_capture",+ "watch_topology",+]diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 5c12267695..2049f43b16 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1864,6 +1864,7 @@ class SpeechPipeline:# 7-24 s starved warm-up (see ``_warmup_phase_a``). Kept on the instance# so a graceful shutdown can cancel + await it.self._deferred_warmup_task: asyncio.Task | None = None+ self._audio_topology_task: asyncio.Task | None = None# ContinuationBuffer (Spec docs/superpowers/specs/# 2026-05-25-incomplete-prompt-completion-design.md): coalesces a@@ -4094,6 +4095,7 @@ class SpeechPipeline:"_warmup_background_task","_warmup_ready_cue_task","_deferred_warmup_task",+ "_audio_topology_task",):task = getattr(self, attr, None)if task is None:@@ -4101,7 +4103,14 @@ class SpeechPipeline:if not task.done():task.cancel()try:- await task+ # Bounded: a wedged native call inside a background worker+ # (e.g. a PortAudio re-init mid-refresh) must not hang the+ # whole shutdown; the orphaned worker dies with the process.+ await asyncio.wait_for(asyncio.shield(task), timeout=2.0)+ except TimeoutError:+ log.warning(+ "Warm-up background task %s did not stop within 2s.", attr+ )except (asyncio.CancelledError, Exception): # noqa: BLE001 — shutdown swallowpasssetattr(self, attr, None)@@ -4147,6 +4156,14 @@ class SpeechPipeline:)log.info("Warm-up Phase A complete — confirmation audio rendering in background.")+ def _log_audio_topology_done(self, task: asyncio.Task) -> None:+ """A silently dead hot-swap watcher must leave a diagnostic (BUG-102)."""+ if task.cancelled():+ return+ exc = task.exception()+ if exc is not None:+ log.warning("Audio topology watcher died: %s", exc)+def _log_warmup_ready_cue_done(self, task: asyncio.Task) -> None:try:task.result()@@ -4300,6 +4317,23 @@ class SpeechPipeline:self._play_ready_cue(), name="warmup-ready-cue")self._warmup_ready_cue_task.add_done_callback(self._log_warmup_ready_cue_done)+ # Hot-swap watcher (BUG-102): starts only AFTER honest readiness —+ # never on the boot critical path (AP-26). Polls the out-of-process+ # device probe and refreshes PortAudio when a headset is plugged+ # in or pulled, so mic and speaker follow the user's devices at+ # runtime on every OS instead of dying on a frozen device table.+ # ``getattr`` default keeps ``__new__``-built test/hot-reload+ # instances (which skip ``__init__``) working.+ if getattr(self, "_audio_topology_task", None) is None:+ from jarvis.audio.topology import watch_topology++ self._audio_topology_task = asyncio.create_task(+ watch_topology(self._player, self._output_device),+ name="audio-topology-watch",+ )+ self._audio_topology_task.add_done_callback(+ self._log_audio_topology_done+ )finally:# Never orphan the concurrently-started TTS init: if this deferred# task is cancelled (desktop shutdown) before the ``await tts_task``diff --git a/tests/unit/audio/test_topology.py b/tests/unit/audio/test_topology.pynew file mode 100644index 0000000000..02c3e48741--- /dev/null+++ b/tests/unit/audio/test_topology.py@@ -0,0 +1,176 @@+"""Unit tests for the audio hot-swap topology watcher (BUG-102).++Pins the three contracts: the signature reacts to physical changes but not to+index shuffles, the watcher refreshes exactly once per settled change and+fails open on probe outages, and a refresh quiesces every registered stream+before PortAudio is re-initialized.+"""+from __future__ import annotations++import asyncio+import sys+import time++import pytest++import jarvis.audio.topology as topology+from jarvis.audio.capture import MicrophoneCapture+++def _tables(names, default_in=0, default_out=0):+ devices = [+ {"name": name, "max_input_channels": 1, "max_output_channels": 2}+ for name in names+ ]+ return devices, [], (default_in, default_out)+++def test_signature_ignores_index_shuffle_but_sees_devices_and_defaults() -> None:+ base = topology.topology_signature(+ _tables(["Mic A", "Speakers B"], default_in=0, default_out=1)+ )+ # Same physical devices and defaults at shuffled indices → same identity.+ shuffled = topology.topology_signature(+ _tables(["Speakers B", "Mic A"], default_in=1, default_out=0)+ )+ assert base == shuffled+ # The OS default moving to another device IS a change (plug-in switches+ # the default output) even when the device list itself is unchanged.+ default_moved = topology.topology_signature(+ _tables(["Mic A", "Speakers B"], default_in=0, default_out=0)+ )+ assert base != default_moved+ unplugged = topology.topology_signature(_tables(["Speakers B"]))+ assert base != unplugged+ assert topology.topology_signature(None) is None+++async def test_watcher_refreshes_once_per_settled_change(monkeypatch) -> None:+ monkeypatch.setattr(topology, "_SETTLE_S", 0.0)+ signatures = iter(["a", "a", "b", "b", "b", "b", "b"])+ refreshes: list[float] = []++ task = asyncio.create_task(+ topology.watch_topology(+ player=None,+ poll_s=0.01,+ probe=lambda: next(signatures, "b"),+ refresh=lambda: refreshes.append(time.monotonic()) or True,+ )+ )+ await asyncio.sleep(0.3)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert len(refreshes) == 1+++async def test_watcher_fails_open_when_probe_returns_none(monkeypatch) -> None:+ monkeypatch.setattr(topology, "_SETTLE_S", 0.0)+ refreshes: list[bool] = []+ task = asyncio.create_task(+ topology.watch_topology(+ player=None,+ poll_s=0.01,+ probe=lambda: None,+ refresh=lambda: refreshes.append(True) or True,+ )+ )+ await asyncio.sleep(0.15)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert refreshes == []+++class _FakeSd:+ def __init__(self) -> None:+ self.calls: list[str] = []++ def _terminate(self) -> None:+ self.calls.append("terminate")++ def _initialize(self) -> None:+ self.calls.append("initialize")+++class _FakePlayer:+ def __init__(self, calls: list[str]) -> None:+ self._calls = calls++ def invalidate_device_cache(self) -> None:+ self._calls.append("player-invalidate")++ def set_device(self, device) -> None:+ self._calls.append(f"player-set:{device}")+++class _FakeCapture:+ def __init__(self, calls: list[str]) -> None:+ self._calls = calls++ def discard_native_stream(self) -> None:+ self._calls.append("capture-discard")+++def test_refresh_quiesces_streams_before_reinit(monkeypatch) -> None:+ calls: list[str] = []+ fake_sd = _FakeSd()+ monkeypatch.setitem(sys.modules, "sounddevice", fake_sd)+ import jarvis.audio.capture as capture_module++ monkeypatch.setattr(+ capture_module,+ "_invalidate_resolve_cache",+ lambda: calls.append("resolve-invalidate"),+ )+ fake_capture = _FakeCapture(calls)+ topology.register_capture(fake_capture)+ try:+ ok = topology.refresh_audio_backend(_FakePlayer(calls), "auto-headset")+ finally:+ topology.unregister_capture(fake_capture)++ assert ok is True+ # Native streams are quiesced BEFORE the re-init, the caches after it.+ assert calls == [+ "capture-discard",+ "player-invalidate",+ "resolve-invalidate",+ "player-set:auto-headset",+ ]+ assert fake_sd.calls == ["terminate", "initialize"]+++def test_capture_discard_backdates_watchdog_heartbeat() -> None:+ class _Stream:+ def __init__(self) -> None:+ self.aborted = False+ self.closed = False++ def abort(self) -> None:+ self.aborted = True++ def close(self) -> None:+ self.closed = True++ capture = MicrophoneCapture.__new__(MicrophoneCapture)+ stream = _Stream()+ capture._stream = stream+ capture._device_spec = "auto-headset"+ capture._preferred_device = 7 # stale resolved index from the old table+ capture._last_chunk_monotonic = time.monotonic()++ capture.discard_native_stream()++ assert capture._stream is None+ assert stream.aborted and stream.closed+ # A non-pinned spec re-enters fresh name/auto resolution on reopen.+ assert capture._preferred_device == "auto-headset"+ # Backdated past the stall threshold → the watchdog reopens on its next tick.+ assert (+ time.monotonic() - capture._last_chunk_monotonic+ > MicrophoneCapture._STALL_THRESHOLD_S+ )