Skip to content

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.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-06 16:39)

Ruben Lütke1f1854890ccc
diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.py
index 4fec66a846..92d67481cb 100644
--- a/jarvis/audio/capture.py
+++ b/jarvis/audio/capture.py
@@ -237,13 +237,31 @@ def _resolve_input_device(
"""
if device is None or isinstance(device, int):
if device is not None:
- _log.info("Mic-Resolve: explizites Device {} verwendet.", device)
+ _log.info("Mic-Resolve: explicit device {} used.", device)
else:
_log.info("Mic-Resolve: system default input (device=None).")
return device
- if not isinstance(device, str) or device != "auto-headset":
- _log.info("Mic-Resolve: named device '{}'.", device)
+ if not isinstance(device, str):
return device
+ if device != "auto-headset":
+ # A concrete NAME (the Settings device picker persists names — the
+ # only identifier stable across reboots/hot-plugs): resolve to an
+ # index via the shared lookup (best host-API twin — MME first for
+ # 16 kHz capture — WDM-KS/mapper excluded). An unplugged/unknown name
+ # falls through to the auto-headset heuristic so the wake loop never
+ # bricks on a missing device.
+ from jarvis.audio.devices import resolve_device_by_name
+
+ named_idx = resolve_device_by_name(device, output=False)
+ if named_idx is not None:
+ _log.info("Mic-Resolve: named device '{}' -> index {}.", device, named_idx)
+ return named_idx
+ _log.warning(
+ "Mic-Resolve: configured input device '{}' not found — falling "
+ "back to auto-headset selection.",
+ device,
+ )
+ # Fall through to the auto-headset heuristic below.
user_priority = tuple(p for p in (priority or ()) if p)
diff --git a/jarvis/audio/devices.py b/jarvis/audio/devices.py
new file mode 100644
index 0000000000..dd54abdc0f
--- /dev/null
+++ b/jarvis/audio/devices.py
@@ -0,0 +1,222 @@
+"""Audio device enumeration + name resolution for the Settings device pickers.
+
+The Settings view lets the user pin which OUTPUT device Jarvis's voice plays
+on and which MICROPHONE it listens with. Two building blocks live here:
+
+- :func:`list_devices` — the picker's option list: one entry per PHYSICAL
+ device. PortAudio enumerates the same endpoint once per host API
+ (WASAPI/MME/DirectSound/WDM-KS on Windows), and the WMME backend truncates
+ display names to ~31 characters — both artifacts are merged away so the
+ user never sees "PRO X" four times. The localized MME/DirectSound virtual
+ mapper and WDM-KS entries (BUG-014: PortAudio's blocking API is not
+ implemented there) never appear.
+- :func:`resolve_device_by_name` — turns a persisted device NAME back into a
+ concrete PortAudio index at stream-open time. Names are the only stable
+ identifier across reboots and hot-plugs (indices drift — the BUG-014 class
+ ``_stabilize_audio_devices`` exists to fight); raw name strings handed to
+ PortAudio are ambiguous across host APIs, so the lookup applies the
+ direction's host-API preference (output: WASAPI first — mono routing;
+ input: MME first — transparent 16 kHz resampling for the wake loop).
+
+Everything degrades quietly: no sounddevice / no PortAudio (headless
+``python:3.11-slim``) yields an empty list / ``None``, never an exception.
+Nothing here runs on the boot path (AP-26) — callers are the Settings route
+and the stream-open resolvers.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ # Type-checkers see the real module; at runtime the guarded import below
+ # binds sd (or None when PortAudio/sounddevice is absent — headless/slim).
+ import sounddevice as sd
+else:
+ try:
+ import sounddevice as sd
+ except Exception: # noqa: BLE001 — sounddevice/PortAudio (libportaudio2) absent
+ sd = None # type: ignore[assignment]
+
+from jarvis.audio.device_select import is_legacy_primary_mapper
+
+#: The config sentinel for "pick a device automatically" (the default in
+#: ``[audio].input_device`` / ``[audio].output_device``).
+AUTO_DEVICE = "auto-headset"
+
+# Host APIs that cannot serve PortAudio's blocking stream API at all —
+# OutputStream open crashes with -9999 (BUG-014), InputStream.start with
+# -9996. Excluded from the picker AND from name resolution: offering or
+# resolving to one of these hands the caller a guaranteed crash.
+_FORBIDDEN_HOSTAPIS: frozenset[str] = frozenset({"Windows WDM-KS"})
+
+# Host-API preference per direction (lower = better), mirroring the resolvers
+# in jarvis.audio.player / jarvis.audio.capture — see their docstrings for the
+# forensics (WASAPI mono routing for playback; MME 16 kHz resampling for the
+# always-on wake capture). Non-Windows host APIs (CoreAudio, ALSA, pulse) fall
+# to the default rank 99, i.e. enumeration order — correct there, since each
+# device appears once.
+_OUTPUT_HOSTAPI_PREFERENCE = {"Windows WASAPI": 0, "Windows DirectSound": 1, "MME": 2}
+_INPUT_HOSTAPI_PREFERENCE = {"MME": 0, "Windows DirectSound": 1, "Windows WASAPI": 2}
+
+# PortAudio's WMME backend truncates device names (32-byte buffer → ~31
+# chars). A shorter name that is a strict PREFIX of a longer one and at least
+# this long is treated as that device's truncated twin, not a distinct device.
+_MME_TRUNCATION_MIN = 30
+
+
+@dataclass(frozen=True)
+class AudioDeviceInfo:
+ """One picker entry: the device's full display name + OS-default flag."""
+
+ name: str
+ is_default: bool
+
+
+def _hostapi_name(dev: dict[str, Any], hostapis: list[Any]) -> str:
+ idx = dev.get("hostapi", -1)
+ if 0 <= idx < len(hostapis):
+ return str(hostapis[idx].get("name", ""))
+ return ""
+
+
+def _query_tables() -> tuple[list[Any], list[Any]] | None:
+ """The (devices, hostapis) tables, or None when PortAudio is unusable."""
+ if sd is None:
+ return None
+ try:
+ return list(sd.query_devices()), list(sd.query_hostapis())
+ except Exception: # noqa: BLE001 — enumeration must never raise (headless)
+ return None
+
+
+def _candidates(
+ devices: list[Any], hostapis: list[Any], *, output: bool
+) -> list[tuple[int, dict[str, Any], str]]:
+ """(index, device, hostapi_name) of every real, usable device in the
+ requested direction — mapper and forbidden-host-API entries removed."""
+ channel_key = "max_output_channels" if output else "max_input_channels"
+ out: list[tuple[int, dict[str, Any], str]] = []
+ for idx, dev in enumerate(devices):
+ if dev.get(channel_key, 0) <= 0:
+ continue
+ if not str(dev.get("name", "")).strip():
+ continue
+ if is_legacy_primary_mapper(idx, hostapis, devices, output=output):
+ continue
+ hostapi = _hostapi_name(dev, hostapis)
+ if hostapi in _FORBIDDEN_HOSTAPIS:
+ continue
+ out.append((idx, dev, hostapi))
+ return out
+
+
+def _hostapi_rank(hostapi: str, *, output: bool) -> int:
+ table = _OUTPUT_HOSTAPI_PREFERENCE if output else _INPUT_HOSTAPI_PREFERENCE
+ return table.get(hostapi, 99)
+
+
+def _os_default_index(*, output: bool) -> int | None:
+ try:
+ idx = sd.default.device[1 if output else 0]
+ except Exception: # noqa: BLE001 — no default configured
+ return None
+ return idx if isinstance(idx, int) and idx >= 0 else None
+
+
+def list_devices(*, output: bool) -> list[AudioDeviceInfo]:
+ """One picker entry per physical device in the requested direction.
+
+ Dedupes host-API twins by exact name, merges an MME-truncated name into
+ its full-name twin, flags the OS-default endpoint and sorts it first
+ (then alphabetically). Headless / no PortAudio → ``[]``.
+ """
+ tables = _query_tables()
+ if tables is None:
+ return []
+ devices, hostapis = tables
+ cands = _candidates(devices, hostapis, output=output)
+ if not cands:
+ return []
+
+ default_idx = _os_default_index(output=output)
+ default_name = ""
+ if default_idx is not None and 0 <= default_idx < len(devices):
+ default_name = str(devices[default_idx].get("name", ""))
+
+ # Exact-name dedupe: keep one representative per display name (the flag
+ # only needs the name; twins are equivalent for the picker).
+ by_name: dict[str, str] = {} # casefolded -> display name
+ for _idx, dev, _hostapi in cands:
+ name = str(dev.get("name", ""))
+ by_name.setdefault(name.casefold(), name)
+
+ # Truncation merge: drop a name that is a >=_MME_TRUNCATION_MIN-char
+ # strict prefix of another (the WMME-truncated twin of the full name).
+ names = list(by_name.values())
+ merged: list[str] = []
+ for name in names:
+ is_truncated_twin = len(name) >= _MME_TRUNCATION_MIN and any(
+ other != name and other.casefold().startswith(name.casefold())
+ for other in names
+ )
+ if not is_truncated_twin:
+ merged.append(name)
+
+ def _is_default(name: str) -> bool:
+ if not default_name:
+ return False
+ a, b = name.casefold(), default_name.casefold()
+ # The default endpoint may be enumerated under its truncated MME name
+ # while the picker kept the full twin (or vice versa).
+ return a == b or a.startswith(b) or b.startswith(a)
+
+ entries = [AudioDeviceInfo(name=n, is_default=_is_default(n)) for n in merged]
+ entries.sort(key=lambda e: (not e.is_default, e.name.casefold()))
+ return entries
+
+
+def resolve_device_by_name(name: str, *, output: bool) -> int | None:
+ """The PortAudio index for a persisted device NAME, or None when absent.
+
+ Exact (case-insensitive) matches win; otherwise a prefix relation in
+ either direction counts, so a full persisted name still finds its
+ MME-truncated twin and a truncated persisted name its full twin. Among
+ matches the direction's host-API preference decides. ``None`` for the
+ :data:`AUTO_DEVICE` sentinel, an empty string, an unknown name, or a
+ headless host — callers fall back to their auto-headset heuristic.
+ """
+ target = (name or "").strip()
+ if not target or target == AUTO_DEVICE:
+ return None
+ tables = _query_tables()
+ if tables is None:
+ return None
+ devices, hostapis = tables
+
+ target_cf = target.casefold()
+ # Same-device pool: exact matches plus truncation twins (the candidate is
+ # a >=_MME_TRUNCATION_MIN-char prefix of the target — the WMME-truncated
+ # enumeration of the SAME endpoint). Within the pool the direction's
+ # host-API preference decides, so a full persisted name still lands on
+ # the MME twin for capture (16 kHz wake-loop contract) and on WASAPI for
+ # playback. Extensions (target is a prefix of the candidate — a truncated
+ # persisted name, or a distinct longer-named product) are only consulted
+ # when nothing in the same-device pool matched, so they can never steal
+ # an exact hit.
+ same_device: list[tuple[int, str]] = []
+ extensions: list[tuple[int, str]] = []
+ for idx, dev, hostapi in _candidates(devices, hostapis, output=output):
+ dev_cf = str(dev.get("name", "")).casefold()
+ if dev_cf == target_cf or (
+ len(dev_cf) >= _MME_TRUNCATION_MIN and target_cf.startswith(dev_cf)
+ ):
+ same_device.append((idx, hostapi))
+ elif dev_cf.startswith(target_cf):
+ extensions.append((idx, hostapi))
+
+ matches = same_device or extensions
+ if not matches:
+ return None
+ matches.sort(key=lambda m: (_hostapi_rank(m[1], output=output), m[0]))
+ return matches[0][0]
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 75fbc61de0..3f755aef2e 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -216,6 +216,11 @@ def _resolve_output_device(
- int: returned as-is (user specified an explicit index)
- None: system default
+ - a concrete NAME (the Settings device picker persists names — the only
+ identifier stable across reboots/hot-plugs): resolved to an index via
+ :func:`jarvis.audio.devices.resolve_device_by_name` (best host-API twin,
+ WDM-KS/mapper excluded). An unplugged/unknown name falls through to the
+ auto-headset heuristic below — playback never bricks on a missing device.
- "auto-headset": searches output devices for headset patterns, skips
GPU-HDMI outputs (monitor speakers) and the localized MME/DirectSound
virtual mapper, prefers WASAPI over MME (mono routing bug on 8-channel
@@ -230,8 +235,21 @@ def _resolve_output_device(
"""
if device is None or isinstance(device, int):
return device
- if not isinstance(device, str) or device != "auto-headset":
+ if not isinstance(device, str):
return device
+ if device != "auto-headset":
+ from jarvis.audio.devices import resolve_device_by_name
+
+ named_idx = resolve_device_by_name(device, output=True)
+ if named_idx is not None:
+ log.info("Output device %r resolved to index %d.", device, named_idx)
+ return named_idx
+ log.warning(
+ "Configured output device %r not found — falling back to "
+ "auto-headset selection.",
+ device,
+ )
+ # Fall through to the auto-headset heuristic below.
user_priority = tuple(p for p in (priority or ()) if p)
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index ffed3b5dbc..8712ca921e 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -255,6 +255,23 @@ def set_tts_volume(volume: float, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
log.warning("Could not sync tts.volume to config-soll.json: %s", exc) # i18n-allow
+def set_audio_device(
+ kind: str, value: str, *, path: Path = DEFAULT_CONFIG_FILE
+) -> None:
+ """Set ``[audio] input_device`` / ``[audio] output_device``.
+
+ ``kind`` is ``"input"`` or ``"output"``; ``value`` is a device display
+ NAME (the identifier stable across reboots/hot-plugs) or the
+ ``"auto-headset"`` sentinel to restore automatic selection. The ``[audio]``
+ block is NOT pinned in config-soll.json, so the atomic TOML patch alone # i18n-allow: filename reference
+ persists it. The Settings route live-applies the change to the running
+ pipeline; this stores the boot default.
+ """
+ if kind not in ("input", "output"):
+ raise ValueError(f"kind must be 'input' or 'output', got {kind!r}")
+ _patch_table(path, "audio", f"{kind}_device", str(value))
+
+
def set_stt_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set the global STT model (``[stt] model``) across all THREE layers.
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 11d4612fd4..7e56a25236 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1666,6 +1666,38 @@ class SpeechPipeline:
if callable(setter):
setter(float(volume))
+ def set_audio_devices(
+ self,
+ *,
+ input_device: str | None = None,
+ output_device: str | None = None,
+ ) -> None:
+ """Live-apply a Settings device pick — no app/pipeline restart.
+
+ ``None`` leaves a side unchanged; a device NAME pins it and the
+ ``"auto-headset"`` sentinel restores automatic selection (resolution
+ happens at stream-open time in the player/capture resolvers).
+
+ - Output: ``AudioPlayer.set_device`` re-resolves and tears down the
+ persistent stream, so the next utterance plays on the new device.
+ - Input: every mic open reads ``self._input_device`` (per-turn opens
+ pick it up naturally); the long-lived wake session is re-armed via
+ ``_wake_reload_event`` — the same live-reload contract as
+ ``set_wake_plan`` — so the always-on mic reopens on the new device
+ within a moment.
+ """
+ if output_device is not None:
+ self._output_device = output_device or None
+ player = getattr(self, "_player", None)
+ setter = getattr(player, "set_device", None)
+ if callable(setter):
+ setter(self._output_device)
+ if input_device is not None:
+ self._input_device = input_device or None
+ reload_event = getattr(self, "_wake_reload_event", None)
+ if reload_event is not None:
+ reload_event.set()
+
def _wake_poll_interval(self) -> float:
"""The stt_match wake poll interval, derived from the user's Sensitivity
slider (``[trigger.wake_word].sensitivity``). Higher sensitivity polls
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 4450eed925..e6c3f8ccda 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -31,7 +31,7 @@ from collections.abc import Callable
from typing import TYPE_CHECKING
from fastapi import APIRouter, HTTPException, Request
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, model_validator
from jarvis.brain.manager import SUPPORTED_REPLY_LANGUAGES
from jarvis.memory.wiki.integration import get_running_curator
@@ -1785,3 +1785,141 @@ async def put_tts_volume(body: TtsVolumeBody, request: Request) -> dict[str, obj
"applied_live": applied_live,
"restart_required": not applied_live,
}
+
+
+# ---------------------------------------------------------------------------
+# Audio device pickers — which device Jarvis's voice plays on and which
+# microphone it listens with.
+#
+# GET lists one entry per PHYSICAL device (host-API twins deduped, the
+# localized virtual mapper and WDM-KS hidden — jarvis.audio.devices) plus the
+# current selection; PUT persists a device NAME (stable across reboots, unlike
+# PortAudio indices) or the "auto-headset" sentinel to jarvis.toml [audio] and
+# live-applies it to the running pipeline (output: player hot-swap; input:
+# wake-session re-arm). Headless / no PortAudio → available=false, the UI
+# degrades to a caption; a save still persists for the next start.
+# ---------------------------------------------------------------------------
+
+AUDIO_AUTO_DEVICE = "auto-headset"
+
+
+class AudioDeviceSelectBody(BaseModel):
+ output_device: str | None = Field(
+ default=None,
+ min_length=1,
+ max_length=256,
+ description=(
+ "Output device display name, or 'auto-headset' for automatic "
+ "selection. Omit to leave unchanged."
+ ),
+ )
+ input_device: str | None = Field(
+ default=None,
+ min_length=1,
+ max_length=256,
+ description=(
+ "Microphone display name, or 'auto-headset' for automatic "
+ "selection. Omit to leave unchanged."
+ ),
+ )
+ persist: bool = Field(default=True, description="Persist as boot default in jarvis.toml")
+
+ @model_validator(mode="after")
+ def _at_least_one_side(self) -> AudioDeviceSelectBody:
+ if self.output_device is None and self.input_device is None:
+ raise ValueError("Provide output_device and/or input_device.")
+ return self
+
+
+def _selected_audio_devices(request: Request) -> tuple[str, str]:
+ """The persisted (output, input) selection strings from the live config."""
+ cfg = _config(request)
+ audio = getattr(cfg, "audio", None)
+ out = str(getattr(audio, "output_device", AUDIO_AUTO_DEVICE) or AUDIO_AUTO_DEVICE)
+ inp = str(getattr(audio, "input_device", AUDIO_AUTO_DEVICE) or AUDIO_AUTO_DEVICE)
+ return out, inp
+
+
[email protected]("/audio-devices")
+async def get_audio_devices(request: Request) -> dict[str, object]:
+ """Enumerate output/input devices + the current selection for the pickers."""
+ from jarvis.audio.devices import list_devices
+
+ outputs = await asyncio.to_thread(lambda: list_devices(output=True))
+ inputs = await asyncio.to_thread(lambda: list_devices(output=False))
+ selected_output, selected_input = _selected_audio_devices(request)
+ return {
+ "available": bool(outputs or inputs),
+ "auto_value": AUDIO_AUTO_DEVICE,
+ "outputs": [{"name": d.name, "is_default": d.is_default} for d in outputs],
+ "inputs": [{"name": d.name, "is_default": d.is_default} for d in inputs],
+ "selected_output": selected_output,
+ "selected_input": selected_input,
+ }
+
+
[email protected]("/audio-devices")
+async def put_audio_devices(
+ body: AudioDeviceSelectBody, request: Request
+) -> dict[str, object]:
+ """Persist + live-apply the audio device selection (name or auto)."""
+ # Best-effort in-memory cfg update so later cfg reads (voice-offline
+ # alerts, the voice watchdog restart path) agree pre-restart.
+ cfg = _config(request)
+ audio_cfg = getattr(cfg, "audio", None)
+ if audio_cfg is not None:
+ try:
+ if body.output_device is not None:
+ audio_cfg.output_device = body.output_device
+ if body.input_device is not None:
+ audio_cfg.input_device = body.input_device
+ except Exception as exc: # noqa: BLE001 — frozen model is not an error
+ log.debug("in-memory audio device update skipped: %s", exc)
+
+ persisted = False
+ if body.persist:
+ try:
+ from jarvis.core import config_writer
+ from jarvis.core.config import resolve_config_path
+
+ cfg_path = resolve_config_path()
+ if body.output_device is not None:
+ config_writer.set_audio_device(
+ "output", body.output_device, path=cfg_path
+ )
+ if body.input_device is not None:
+ config_writer.set_audio_device(
+ "input", body.input_device, path=cfg_path
+ )
+ persisted = True
+ except Exception as exc: # noqa: BLE001 — persist is best-effort
+ log.warning(
+ "audio-device persist failed (live apply still attempted): %s", exc
+ )
+
+ # Live-apply to the running voice pipeline — no app restart. Best-effort:
+ # a headless/down pipeline just means it applies on next start.
+ applied_live = False
+ pipeline = getattr(request.app.state, "speech_pipeline", None)
+ if pipeline is not None and hasattr(pipeline, "set_audio_devices"):
+ try:
+ pipeline.set_audio_devices(
+ input_device=body.input_device,
+ output_device=body.output_device,
+ )
+ applied_live = True
+ except Exception as exc: # noqa: BLE001 — never fail the save on a live-apply hiccup
+ log.warning(
+ "audio-device live-apply failed (persisted; applies on restart): %s",
+ exc,
+ )
+
+ selected_output, selected_input = _selected_audio_devices(request)
+ return {
+ "ok": True,
+ "selected_output": selected_output,
+ "selected_input": selected_input,
+ "persisted": persisted,
+ "applied_live": applied_live,
+ "restart_required": not applied_live,
+ }
diff --git a/tests/unit/audio/test_capture_device.py b/tests/unit/audio/test_capture_device.py
index beaebd593d..9caa67b9ce 100644
--- a/tests/unit/audio/test_capture_device.py
+++ b/tests/unit/audio/test_capture_device.py
@@ -90,11 +90,33 @@ def test_auto_headset_falls_back_to_default_when_query_fails(monkeypatch) -> Non
assert capture._resolve_input_device("auto-headset") is None
-def test_explicit_input_device_is_not_resolved(monkeypatch) -> None:
+def test_explicit_index_is_not_resolved(monkeypatch) -> None:
def fail_query():
raise AssertionError("query_devices should not be called")
monkeypatch.setattr(capture.sd, "query_devices", fail_query)
- assert capture._resolve_input_device("Microphone (Manual)") == "Microphone (Manual)"
assert capture._resolve_input_device(3) == 3
+
+
+def test_explicit_name_resolves_to_index(monkeypatch) -> None:
+ """A concrete NAME (persisted by the Settings device picker) resolves to
+ its PortAudio index at open time — names are the stable identifier across
+ reboots; raw name strings handed to PortAudio are ambiguous across host
+ APIs (the pre-2026-07 pass-through contract)."""
+ from jarvis.audio import devices as dv
+
+ devices = [
+ {
+ "name": "Microphone (Manual)",
+ "max_input_channels": 1,
+ "max_output_channels": 0,
+ "hostapi": 0,
+ },
+ ]
+ hostapis = [{"name": "Windows WASAPI"}]
+ for mod in (capture, dv):
+ monkeypatch.setattr(mod.sd, "query_devices", lambda: devices)
+ monkeypatch.setattr(mod.sd, "query_hostapis", lambda: hostapis)
+
+ assert capture._resolve_input_device("Microphone (Manual)") == 0
diff --git a/tests/unit/audio/test_devices.py b/tests/unit/audio/test_devices.py
new file mode 100644
index 0000000000..b5e652475c
--- /dev/null
+++ b/tests/unit/audio/test_devices.py
@@ -0,0 +1,252 @@
+"""Device enumeration + name resolution for the Settings audio-device pickers.
+
+Guards for :mod:`jarvis.audio.devices`:
+
+1. **Picker list quality** — one entry per physical device: host-API twins
+ (WASAPI/MME/DirectSound expose the same endpoint) are deduped, the
+ MME-truncated name variant merges into the full name, the localized
+ MME/DirectSound virtual mapper and WDM-KS entries (BUG-014: blocking API
+ unsupported) never appear, the OS-default endpoint is flagged and sorts
+ first.
+2. **Name resolution** — a persisted device NAME resolves to a concrete
+ PortAudio index with the direction's host-API preference (output: WASAPI
+ first; input: MME first), tolerating the MME truncation; an unknown name
+ yields None so callers can fall back to auto-headset.
+3. **Headless safety** — no sounddevice / a failing query degrades to an
+ empty list / None, never raises (python:3.11-slim contract, CLAUDE.md §3).
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.audio import devices as dv
+
+
+def _patch_tables(monkeypatch, hostapis, devices, *, default=(-1, -1)) -> None:
+ monkeypatch.setattr(dv.sd, "query_devices", lambda: devices)
+ monkeypatch.setattr(dv.sd, "query_hostapis", lambda: hostapis)
+ monkeypatch.setattr(dv.sd, "default", SimpleNamespace(device=default))
+
+
+# --------------------------------------------------------------------------- #
+# Windows-like table: one headset + one Realtek board, each on 4 host APIs, #
+# plus the virtual mappers. Mirrors a real PortAudio enumeration. #
+# --------------------------------------------------------------------------- #
+_FULL_HEADSET_OUT = "Lautsprecher (Logitech PRO X Gaming Headset)" # i18n-allow: localized Windows device name under test
+_MME_HEADSET_OUT = _FULL_HEADSET_OUT[:31] # MME truncates at ~31 chars
+_FULL_HEADSET_IN = "Mikrofon (Logitech PRO X Gaming Headset)" # i18n-allow: localized Windows device name under test
+_MME_HEADSET_IN = _FULL_HEADSET_IN[:31]
+
+
+def _windows_tables() -> tuple[list[dict], list[dict]]:
+ hostapis = [
+ {"name": "MME", "devices": [0, 1, 2, 3]},
+ {"name": "Windows DirectSound", "devices": [4, 5]},
+ {"name": "Windows WASAPI", "devices": [6, 7, 8]},
+ {"name": "Windows WDM-KS", "devices": [9]},
+ ]
+ devices = [
+ # -- MME (names truncated, mappers first — the real enumeration order) --
+ {"name": "Microsoft Sound Mapper - Output", "hostapi": 0,
+ "max_output_channels": 2, "max_input_channels": 0}, # 0: out-mapper
+ {"name": "Microsoft Sound Mapper - Input", "hostapi": 0,
+ "max_output_channels": 0, "max_input_channels": 2}, # 1: in-mapper
+ {"name": _MME_HEADSET_OUT, "hostapi": 0,
+ "max_output_channels": 2, "max_input_channels": 0}, # 2
+ {"name": _MME_HEADSET_IN, "hostapi": 0,
+ "max_output_channels": 0, "max_input_channels": 1}, # 3
+ # -- DirectSound (mapper first) --
+ {"name": "Primary Sound Driver", "hostapi": 1,
+ "max_output_channels": 2, "max_input_channels": 0}, # 4: mapper
+ {"name": _FULL_HEADSET_OUT, "hostapi": 1,
+ "max_output_channels": 2, "max_input_channels": 0}, # 5
+ # -- WASAPI (full names) --
+ {"name": _FULL_HEADSET_OUT, "hostapi": 2,
+ "max_output_channels": 2, "max_input_channels": 0}, # 6
+ {"name": _FULL_HEADSET_IN, "hostapi": 2,
+ "max_output_channels": 0, "max_input_channels": 1}, # 7
+ {"name": "Speakers (Realtek HD Audio)", "hostapi": 2,
+ "max_output_channels": 2, "max_input_channels": 0}, # 8
+ # -- WDM-KS (structurally unusable, BUG-014) --
+ {"name": "Speakers (Realtek HD Audio output)", "hostapi": 3,
+ "max_output_channels": 2, "max_input_channels": 0}, # 9
+ ]
+ return hostapis, devices
+
+
+def test_output_list_dedupes_twins_and_hides_mapper_and_wdmks(monkeypatch) -> None:
+ hostapis, devices = _windows_tables()
+ _patch_tables(monkeypatch, hostapis, devices)
+
+ names = [d.name for d in dv.list_devices(output=True)]
+
+ # One entry per physical device: the truncated MME twin merged into the
+ # full name, the mappers and the WDM-KS-only entry are gone.
+ assert names.count(_FULL_HEADSET_OUT) == 1
+ assert _MME_HEADSET_OUT not in names
+ assert "Microsoft Sound Mapper - Output" not in names
+ assert "Primary Sound Driver" not in names
+ assert "Speakers (Realtek HD Audio output)" not in names
+ assert "Speakers (Realtek HD Audio)" in names
+ assert len(names) == 2
+
+
+def test_input_list_contains_only_real_mics(monkeypatch) -> None:
+ hostapis, devices = _windows_tables()
+ _patch_tables(monkeypatch, hostapis, devices)
+
+ names = [d.name for d in dv.list_devices(output=False)]
+
+ assert names == [_FULL_HEADSET_IN]
+
+
+def test_os_default_is_flagged_and_sorts_first(monkeypatch) -> None:
+ hostapis, devices = _windows_tables()
+ # OS default output = the Realtek board (idx 8).
+ _patch_tables(monkeypatch, hostapis, devices, default=(-1, 8))
+
+ out = dv.list_devices(output=True)
+
+ assert out[0].name == "Speakers (Realtek HD Audio)"
+ assert out[0].is_default is True
+ assert all(not d.is_default for d in out[1:])
+
+
+def test_list_devices_headless_returns_empty(monkeypatch) -> None:
+ def fail_query():
+ raise RuntimeError("portaudio unavailable")
+
+ monkeypatch.setattr(dv.sd, "query_devices", fail_query)
+
+ assert dv.list_devices(output=True) == []
+ assert dv.list_devices(output=False) == []
+
+
+def test_list_devices_without_sounddevice_returns_empty(monkeypatch) -> None:
+ monkeypatch.setattr(dv, "sd", None)
+
+ assert dv.list_devices(output=True) == []
+ assert dv.list_devices(output=False) == []
+
+
+# --------------------------------------------------------------------------- #
+# Name resolution #
+# --------------------------------------------------------------------------- #
+def test_resolve_output_name_prefers_wasapi_twin(monkeypatch) -> None:
+ hostapis, devices = _windows_tables()
+ _patch_tables(monkeypatch, hostapis, devices)
+
+ # The full name exists on DirectSound (idx 5) and WASAPI (idx 6) —
+ # output preference picks WASAPI.
+ assert dv.resolve_device_by_name(_FULL_HEADSET_OUT, output=True) == 6
+
+
+def test_resolve_input_name_prefers_mme_twin(monkeypatch) -> None:
+ hostapis, devices = _windows_tables()
+ _patch_tables(monkeypatch, hostapis, devices)
+
+ # The mic exists as the truncated MME twin (idx 3) and on WASAPI (idx 7).
+ # Input preference picks MME (16 kHz resampling, wake-loop contract), and
+ # the truncated name must still match the full persisted name.
+ assert dv.resolve_device_by_name(_FULL_HEADSET_IN, output=False) == 3
+
+
+def test_resolve_never_returns_wdmks(monkeypatch) -> None:
+ hostapis, devices = _windows_tables()
+ _patch_tables(monkeypatch, hostapis, devices)
+
+ # "Speakers (Realtek HD Audio output)" exists ONLY on WDM-KS → not
+ # resolvable; the substring also matches the safe WASAPI Realtek entry.
+ resolved = dv.resolve_device_by_name(
+ "Speakers (Realtek HD Audio)", output=True
+ )
+ assert resolved == 8
+
+
+def test_resolve_unknown_name_returns_none(monkeypatch) -> None:
+ hostapis, devices = _windows_tables()
+ _patch_tables(monkeypatch, hostapis, devices)
+
+ assert dv.resolve_device_by_name("Jabra Evolve2 65", output=True) is None
+
+
+def test_resolve_is_case_insensitive(monkeypatch) -> None:
+ hostapis, devices = _windows_tables()
+ _patch_tables(monkeypatch, hostapis, devices)
+
+ assert (
+ dv.resolve_device_by_name(_FULL_HEADSET_OUT.upper(), output=True) == 6
+ )
+
+
+def test_resolve_headless_returns_none(monkeypatch) -> None:
+ monkeypatch.setattr(dv, "sd", None)
+
+ assert dv.resolve_device_by_name("anything", output=True) is None
+
+
[email protected]("value", ["", " ", "auto-headset"])
+def test_resolve_auto_or_empty_returns_none(monkeypatch, value) -> None:
+ hostapis, devices = _windows_tables()
+ _patch_tables(monkeypatch, hostapis, devices)
+
+ assert dv.resolve_device_by_name(value, output=True) is None
+
+
+# --------------------------------------------------------------------------- #
+# Resolver integration: a persisted NAME in [audio].*_device resolves to an #
+# index at stream-open time; an unplugged name falls back to auto-headset #
+# instead of bricking playback / the wake loop. #
+# --------------------------------------------------------------------------- #
+def _patch_all(monkeypatch, hostapis, devices) -> None:
+ from types import SimpleNamespace as _NS
+
+ import jarvis.audio.capture as cap
+ import jarvis.audio.player as pl
+
+ for mod in (dv, pl, cap):
+ monkeypatch.setattr(mod.sd, "query_devices", lambda: devices)
+ monkeypatch.setattr(mod.sd, "query_hostapis", lambda: hostapis)
+ monkeypatch.setattr(mod.sd, "default", _NS(device=(-1, -1)))
+
+
+def test_player_resolves_configured_name_to_index(monkeypatch) -> None:
+ import jarvis.audio.player as pl
+
+ hostapis, devices = _windows_tables()
+ _patch_all(monkeypatch, hostapis, devices)
+
+ assert pl._resolve_output_device(_FULL_HEADSET_OUT) == 6
+
+
+def test_player_falls_back_to_auto_when_named_device_is_gone(monkeypatch) -> None:
+ import jarvis.audio.player as pl
+
+ hostapis, devices = _windows_tables()
+ _patch_all(monkeypatch, hostapis, devices)
+
+ # The unplugged headset name must not brick playback: the resolver falls
+ # back to the auto-headset heuristic (which lands on a real, safe sink).
+ resolved = pl._resolve_output_device("Jabra Evolve2 65")
+ assert resolved in (5, 6, 8)
+
+
+def test_capture_resolves_configured_name_to_index(monkeypatch) -> None:
+ import jarvis.audio.capture as cap
+
+ hostapis, devices = _windows_tables()
+ _patch_all(monkeypatch, hostapis, devices)
+
+ assert cap._resolve_input_device(_FULL_HEADSET_IN) == 3
+
+
+def test_capture_falls_back_to_auto_when_named_device_is_gone(monkeypatch) -> None:
+ import jarvis.audio.capture as cap
+
+ hostapis, devices = _windows_tables()
+ _patch_all(monkeypatch, hostapis, devices)
+
+ resolved = cap._resolve_input_device("Blue Yeti")
+ assert resolved in (3, 7)
diff --git a/tests/unit/speech/test_audio_device_live_apply.py b/tests/unit/speech/test_audio_device_live_apply.py
new file mode 100644
index 0000000000..7236c28b19
--- /dev/null
+++ b/tests/unit/speech/test_audio_device_live_apply.py
@@ -0,0 +1,72 @@
+"""Live-apply of a Settings audio-device pick — no app/pipeline restart.
+
+``SpeechPipeline.set_audio_devices`` mirrors the ``set_wake_plan`` /
+``set_tts_volume`` live-switch contract: the output side hot-swaps the
+player's device, the input side updates the device every future mic open
+reads and re-arms the running wake session via ``_wake_reload_event`` so the
+always-on mic reopens on the new device.
+"""
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.speech.pipeline import SpeechPipeline
+
+
+class _FakePlayer:
+ def __init__(self) -> None:
+ self.devices: list[object] = []
+
+ def set_device(self, device: object) -> None:
+ self.devices.append(device)
+
+
+def _pipe() -> SpeechPipeline:
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._player = _FakePlayer()
+ pipe._input_device = "auto-headset"
+ pipe._output_device = "auto-headset"
+ pipe._wake_reload_event = asyncio.Event()
+ return pipe
+
+
+def test_output_pick_hot_swaps_player_without_touching_input() -> None:
+ pipe = _pipe()
+
+ pipe.set_audio_devices(output_device="PRO X Gaming Headset")
+
+ assert pipe._output_device == "PRO X Gaming Headset"
+ assert pipe._player.devices == ["PRO X Gaming Headset"]
+ assert pipe._input_device == "auto-headset"
+ assert not pipe._wake_reload_event.is_set()
+
+
+def test_input_pick_updates_device_and_rearms_wake_session() -> None:
+ pipe = _pipe()
+
+ pipe.set_audio_devices(input_device="Blue Yeti")
+
+ assert pipe._input_device == "Blue Yeti"
+ assert pipe._wake_reload_event.is_set()
+ assert pipe._player.devices == [] # output side untouched
+
+
+def test_auto_sentinel_restores_automatic_selection() -> None:
+ pipe = _pipe()
+ pipe._output_device = "PRO X Gaming Headset"
+
+ pipe.set_audio_devices(output_device="auto-headset")
+
+ assert pipe._output_device == "auto-headset"
+ assert pipe._player.devices == ["auto-headset"]
+
+
+def test_none_leaves_both_sides_unchanged() -> None:
+ pipe = _pipe()
+
+ pipe.set_audio_devices()
+
+ assert pipe._input_device == "auto-headset"
+ assert pipe._output_device == "auto-headset"
+ assert pipe._player.devices == []
+ assert not pipe._wake_reload_event.is_set()
diff --git a/tests/unit/ui/test_audio_devices_route.py b/tests/unit/ui/test_audio_devices_route.py
new file mode 100644
index 0000000000..092559cc9f
--- /dev/null
+++ b/tests/unit/ui/test_audio_devices_route.py
@@ -0,0 +1,158 @@
+"""GET/PUT /api/settings/audio-devices — enumerate + persist + live-apply.
+
+The Settings device pickers: GET lists one entry per physical device plus the
+current [audio] selection; PUT persists a device NAME (or the "auto-headset"
+sentinel) via config_writer and live-applies it to the running SpeechPipeline
+(output: player hot-swap, input: wake-session re-arm). Headless hosts degrade
+to available=false / restart_required=true — never a 500.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.audio.devices import AudioDeviceInfo
+from jarvis.ui.web.settings_routes import router
+
+
+def _client(*, output_device="auto-headset", input_device="auto-headset", pipeline=None):
+ app = FastAPI()
+ app.include_router(router)
+ app.state.config = SimpleNamespace(
+ audio=SimpleNamespace(
+ output_device=output_device, input_device=input_device
+ )
+ )
+ if pipeline is not None:
+ app.state.speech_pipeline = pipeline
+ return TestClient(app)
+
+
+def _fake_lists(monkeypatch, outputs, inputs):
+ import jarvis.audio.devices as dv
+
+ monkeypatch.setattr(
+ dv, "list_devices", lambda *, output: outputs if output else inputs
+ )
+
+
+def test_get_lists_devices_and_selection(monkeypatch):
+ _fake_lists(
+ monkeypatch,
+ outputs=[
+ AudioDeviceInfo(name="Speakers (Realtek HD Audio)", is_default=True),
+ AudioDeviceInfo(name="PRO X Gaming Headset", is_default=False),
+ ],
+ inputs=[AudioDeviceInfo(name="Microphone (PRO X)", is_default=True)],
+ )
+
+ r = _client(output_device="PRO X Gaming Headset").get(
+ "/api/settings/audio-devices"
+ )
+
+ assert r.status_code == 200
+ body = r.json()
+ assert body["available"] is True
+ assert body["auto_value"] == "auto-headset"
+ assert body["outputs"][0] == {
+ "name": "Speakers (Realtek HD Audio)",
+ "is_default": True,
+ }
+ assert body["inputs"] == [{"name": "Microphone (PRO X)", "is_default": True}]
+ assert body["selected_output"] == "PRO X Gaming Headset"
+ assert body["selected_input"] == "auto-headset"
+
+
+def test_get_headless_reports_unavailable(monkeypatch):
+ _fake_lists(monkeypatch, outputs=[], inputs=[])
+
+ r = _client().get("/api/settings/audio-devices")
+
+ assert r.status_code == 200
+ body = r.json()
+ assert body["available"] is False
+ assert body["outputs"] == []
+ assert body["inputs"] == []
+
+
+def test_put_persists_and_live_applies(monkeypatch):
+ persisted: dict[str, str] = {}
+ import jarvis.core.config_writer as cw
+
+ monkeypatch.setattr(
+ cw,
+ "set_audio_device",
+ lambda kind, value, **k: persisted.setdefault(kind, value),
+ )
+
+ applied: dict[str, str | None] = {}
+
+ class FakePipeline:
+ def set_audio_devices(self, *, input_device=None, output_device=None):
+ applied["input"] = input_device
+ applied["output"] = output_device
+
+ client = _client(pipeline=FakePipeline())
+ r = client.put(
+ "/api/settings/audio-devices",
+ json={"output_device": "PRO X Gaming Headset", "persist": True},
+ )
+
+ assert r.status_code == 200
+ body = r.json()
+ assert body["ok"] is True
+ assert body["persisted"] is True
+ assert body["applied_live"] is True
+ assert body["restart_required"] is False
+ assert body["selected_output"] == "PRO X Gaming Headset"
+ assert persisted == {"output": "PRO X Gaming Headset"}
+ assert applied == {"input": None, "output": "PRO X Gaming Headset"}
+
+
+def test_put_input_only_and_auto_reset(monkeypatch):
+ persisted: dict[str, str] = {}
+ import jarvis.core.config_writer as cw
+
+ monkeypatch.setattr(
+ cw,
+ "set_audio_device",
+ lambda kind, value, **k: persisted.setdefault(kind, value),
+ )
+
+ client = _client(input_device="Blue Yeti")
+ r = client.put(
+ "/api/settings/audio-devices",
+ json={"input_device": "auto-headset"},
+ )
+
+ assert r.status_code == 200
+ body = r.json()
+ assert body["selected_input"] == "auto-headset"
+ assert persisted == {"input": "auto-headset"}
+ # No pipeline on app.state → persisted only, applies on next start.
+ assert body["applied_live"] is False
+ assert body["restart_required"] is True
+
+
+def test_put_requires_at_least_one_side():
+ r = _client().put("/api/settings/audio-devices", json={"persist": True})
+ assert r.status_code == 422
+
+
+def test_put_survives_persist_failure(monkeypatch):
+ import jarvis.core.config_writer as cw
+
+ def boom(*a, **k):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(cw, "set_audio_device", boom)
+
+ r = _client().put(
+ "/api/settings/audio-devices",
+ json={"output_device": "PRO X Gaming Headset"},
+ )
+
+ assert r.status_code == 200
+ assert r.json()["persisted"] is False