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
feat(audio): locale-independent + user-personalizable device auto-selection
Ruben Lütkea4a6c5d1b834
diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.pyindex 64d1271cc1..426fa0fb61 100644--- a/jarvis/audio/capture.py+++ b/jarvis/audio/capture.py@@ -11,7 +11,7 @@ from __future__ import annotationsimport asyncioimport time-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Sequencefrom typing import TYPE_CHECKINGimport numpy as np@@ -27,6 +27,7 @@ else:except Exception: # noqa: BLE001 — sounddevice/PortAudio (libportaudio2) absent (headless/slim)sd = None # type: ignore[assignment]+from jarvis.audio.device_select import is_legacy_primary_mapperfrom jarvis.core.protocols import AudioChunkSAMPLE_RATE = 16_000 # Whisper native rate@@ -43,6 +44,15 @@ DTYPE = "int16"# (push-to-talk, dictation) use the deeper default instead. See MicrophoneCapture.REALTIME_QUEUE_CHUNKS = 6+# Input NAMES we never open as a microphone: playback/loopback/monitor sources+# (opening one feeds constant hiss or TTS echo into the wake path) and GPU-HDMI+# audio. Matched case-insensitively. A few translated playback labels (the+# localized speaker/headphone words listed below) are additive coverage for a+# localized Windows where a loopback enumerates under its translated name — data,+# prose. The MME "Sound Mapper" / DirectSound "Primary Sound Driver" virtual+# routers are NOT listed here (their name is localized); they are skipped+# STRUCTURALLY via ``is_legacy_primary_mapper``, which also correctly catches+# the DirectSound *recording* mapper that no fixed substring covered._BLOCKED_INPUT_SUBSTRINGS = ("Stereo Mix","What U Hear",@@ -59,15 +69,20 @@ _BLOCKED_INPUT_SUBSTRINGS = ("Display","NVIDIA High Definition","AMD HD Audio",- "Microsoft Soundmapper",- "Primaerer Soundtreiber", # i18n-allow: matched against a localized (German) Windows device name- "Primärer Soundtreiber", # i18n-allow: matched against a localized (German) Windows device name)+# Generic default preference order for "auto-headset" microphone selection, most+# specific first. Not tied to any one machine's hardware — a user whose mic is+# not covered names it via ``[audio].input_device_priority`` (consulted BEFORE+# this list) or pins an explicit ``[audio].input_device`` index, without editing+# code. Bare product tokens (PRO X, Arctis, …) exist because sounddevice often+# enumerates a headset mic without the vendor prefix. "Microphone" / "Mikrofon"+# are the generic last-resort real-mic labels across common Windows UI locales._INPUT_PRIORITY = ("Logitech PRO X", "PRO X", "Logitech",- "Jabra", "Sennheiser", "SteelSeries", "Corsair", "HyperX", "Razer",- "USB Audio", "Headset", "Microphone", "Mikrofon", # i18n-allow: matched against a localized (German) Windows device name+ "Jabra", "Sennheiser", "SteelSeries", "Arctis", "Corsair", "HyperX",+ "Razer", "Bose", "AirPods",+ "USB Audio", "Headset", "Microphone", "Mikrofon", # i18n-allow: localized (German) generic mic label used as matching data"Realtek HD Audio", "Realtek",)@@ -165,13 +180,23 @@ def _fallback_input_devices(primary_idx: int) -> list[int]:return [idx for idx, _ in matches]-def _resolve_input_device(device: int | str | None) -> int | str | None:+def _resolve_input_device(+ device: int | str | None,+ priority: Sequence[str] | None = None,+) -> int | str | None:"""Resolve ``auto-headset`` to a concrete microphone device.Windows exposes loopback and monitor sources as input devices. If Jarvisopens one of those for always-on wake detection, users hear constant hiss orTTS echo through the capture path. Prefer named headset microphones and- skip known playback/loopback inputs.+ skip known playback/loopback inputs and the localized MME/DirectSound+ virtual mapper.++ ``priority`` is the user's own mic-name preference+ (``[audio].input_device_priority``). When non-empty, a device whose name+ contains a user entry outranks EVERY generic ``_INPUT_PRIORITY`` match, so a+ user with an uncommon microphone wins by naming it — no code edit. Empty+ ``priority`` reproduces the generic-only behavior exactly."""if device is None or isinstance(device, int):if device is not None:@@ -183,6 +208,8 @@ def _resolve_input_device(device: int | str | None) -> int | str | None:_log.info("Mic-Resolve: named device '{}'.", device)return device+ user_priority = tuple(p for p in (priority or ()) if p)+try:devices = sd.query_devices()hostapis = sd.query_hostapis()@@ -197,6 +224,10 @@ def _resolve_input_device(device: int | str | None) -> int | str | None:name = str(dev.get("name", ""))if any(blocked.lower() in name.lower() for blocked in _BLOCKED_INPUT_SUBSTRINGS):continue+ # Locale-independent skip of the MME "Sound Mapper" / DirectSound+ # "Primary Sound Driver" recording mapper (translated display name).+ if is_legacy_primary_mapper(idx, hostapis, devices, output=False):+ continue# Drop hostapis that can't serve PortAudio blocking-stream I/O —# WDM-KS makes InputStream.start() raise PaErrorCode -9996 even# when the device enumerates cleanly. Filtering here means the@@ -217,18 +248,25 @@ def _resolve_input_device(device: int | str | None) -> int | str | None:return 99def _name_rank(entry: tuple[int, dict]) -> int:- name = str(entry[1].get("name", ""))- rank = len(_INPUT_PRIORITY)+ low = str(entry[1].get("name", "")).lower()+ # User-configured names take strict precedence and are trusted as an+ # explicit choice: they rank ahead of every generic match AND are exempt+ # from the virtual/AI-mic deprioritize below (if the user deliberately+ # names their virtual cable / broadcast mic, honor it).+ for r, sub in enumerate(user_priority):+ if sub.lower() in low:+ return r+ rank = len(user_priority) + len(_INPUT_PRIORITY)for r, sub in enumerate(_INPUT_PRIORITY):- if sub.lower() in name.lower():- rank = r+ if sub.lower() in low:+ rank = len(user_priority) + rbreak# Push virtual / AI mics (NVIDIA Broadcast, voice changers, virtual# cables) BEHIND every real hardware mic — they often deliver silence# when their companion app is closed (see _INPUT_DEPRIORITIZE). They are# not blocked, only ranked last, so they still serve as a fallback when# no real mic exists.- if any(v.lower() in name.lower() for v in _INPUT_DEPRIORITIZE):+ if any(v.lower() in low for v in _INPUT_DEPRIORITIZE):rank += 1000return rank@@ -280,8 +318,13 @@ class MicrophoneCapture:blocksize: int = BLOCKSIZE,channels: int = CHANNELS,max_queue_chunks: int = 20,+ device_priority: Sequence[str] | None = None,) -> None:- self._device = _resolve_input_device(device)+ # User-configured mic-name priority ([audio].input_device_priority),+ # consulted BEFORE the generic _INPUT_PRIORITY default when resolving+ # "auto-headset". Empty = today's generic behavior.+ self._device_priority: tuple[str, ...] = tuple(device_priority or ())+ self._device = _resolve_input_device(device, self._device_priority)self._sample_rate = sample_rateself._blocksize = blocksizeself._channels = channelsdiff --git a/jarvis/audio/device_select.py b/jarvis/audio/device_select.pynew file mode 100644index 0000000000..79398a5141--- /dev/null+++ b/jarvis/audio/device_select.py@@ -0,0 +1,78 @@+"""Locale-independent audio-device classification shared by the output player+(:mod:`jarvis.audio.player`) and the microphone capture+(:mod:`jarvis.audio.capture`) auto-selection resolvers.++The one piece of device selection that used to depend on a *localized* Windows+display name lived in the two blocklists: the MME "Microsoft Sound Mapper" and+the DirectSound "Primary Sound Driver" virtual routing devices. Their display+name is translated by Windows into each UI language, so a fixed localized+substring only masked the mapper on one UI language and let it through on every+other locale.++They are, however, reliably identifiable **structurally**, without their name:+PortAudio's WMME and DirectSound backends always enumerate their virtual+mapper / primary device as the FIRST direction-matching entry of the host+API's device list, before any real endpoint (a documented enumeration+invariant on Windows). :func:`is_legacy_primary_mapper` uses exactly that, so+the auto-selection never routes to the OS-default sink that ``auto-headset``+exists to bypass — on any Windows UI language.+"""+from __future__ import annotations++from collections.abc import Sequence+from typing import Any++# Host APIs whose PortAudio backend prepends a virtual routing device+# ("Microsoft Sound Mapper - Output/Input" on MME, "Primary Sound Driver" on+# DirectSound) to their device list. WASAPI and WDM-KS expose no such mapper.+_LEGACY_MAPPER_HOSTAPIS: frozenset[str] = frozenset({"MME", "Windows DirectSound"})+++def is_legacy_primary_mapper(+ device_index: int,+ hostapis: Sequence[Any],+ devices: Sequence[Any],+ *,+ output: bool,+) -> bool:+ """Return True if ``device_index`` is the MME/DirectSound virtual mapper.++ Locale-independent replacement for matching a translated display name+ (localized by Windows per UI language). ``output`` selects+ the direction: the output mapper is the first *output-capable* device of an+ MME/DirectSound host API, the input mapper the first *input-capable* one.++ Fails safe: any partial device table (e.g. a test fake whose ``hostapis``+ entries carry no ``devices`` member list) returns False, so a device is+ never mis-classified as a mapper on incomplete data.+ """+ if not (0 <= device_index < len(devices)):+ return False+ dev = devices[device_index]+ hostapi_idx = _get(dev, "hostapi", -1)+ if not (0 <= hostapi_idx < len(hostapis)):+ return False+ hostapi = hostapis[hostapi_idx]+ if _get(hostapi, "name", "") not in _LEGACY_MAPPER_HOSTAPIS:+ return False+ member_indices = _get(hostapi, "devices", None)+ if not member_indices:+ # No membership list (partial/fake table) — cannot classify structurally.+ return False+ channel_key = "max_output_channels" if output else "max_input_channels"+ for member_idx in member_indices:+ if not (0 <= member_idx < len(devices)):+ continue+ if _get(devices[member_idx], channel_key, 0) > 0:+ # First direction-matching device of the host API == the mapper.+ return member_idx == device_index+ return False+++def _get(obj: Any, key: str, default: Any) -> Any:+ """Read ``key`` from a sounddevice mapping-like object (dict or DeviceList+ entry), falling back to ``default`` when absent."""+ try:+ return obj.get(key, default) # type: ignore[no-any-return]+ except AttributeError:+ return getattr(obj, key, default)diff --git a/jarvis/audio/player.py b/jarvis/audio/player.pyindex 4bf6989318..260479e1d8 100644--- a/jarvis/audio/player.py+++ b/jarvis/audio/player.py@@ -11,7 +11,7 @@ from __future__ import annotationsimport asyncioimport loggingimport time-from collections.abc import AsyncIterator, Callable+from collections.abc import AsyncIterator, Callable, Sequencefrom typing import TYPE_CHECKING, Anyimport numpy as np@@ -27,6 +27,7 @@ else:sd = None # type: ignore[assignment]from jarvis.audio import level_tap+from jarvis.audio.device_select import is_legacy_primary_mapperfrom jarvis.audio.gain import apply_output_gain, clamp_volumefrom jarvis.core.events import AudioOutFirstfrom jarvis.core.protocols import AudioChunk@@ -42,23 +43,35 @@ _PortAudioError: type[BaseException] = sd.PortAudioError if sd is not None elseTTS_SAMPLE_RATE = 24_000 # Gemini 3.1 Flash TTS output rateTTS_WRITE_BUFFER_MS = 120-# Audio devices we NEVER select as auto-headset output — monitor speakers-# via HDMI/DisplayPort. Typical GPU audio chip names.+# Audio devices we NEVER auto-select as headset output. These are+# locale-independent hardware/interface names: monitor speakers reached over+# HDMI/DisplayPort (GPU audio chips) and digital passthrough with no guaranteed+# sink. Matched case-insensitively. The Windows MME "Sound Mapper" and+# DirectSound "Primary Sound Driver" virtual routers are NOT listed here — their+# display name is localized, so they are skipped STRUCTURALLY instead (see+# ``is_legacy_primary_mapper``), which works on every Windows UI language._BLOCKED_OUTPUT_SUBSTRINGS = ("NVIDIA High Definition", # NVIDIA GPU audio (monitor via HDMI/DP)"AMD HD Audio", # AMD GPU audio- "Primärer Soundtreiber", # i18n-allow: Windows primary hook, ambiguous — matched against a localized (German) Windows device name- "Microsoft Soundmapper",- "SPDIF", # digital-out with no target on unknown setups+ "SPDIF", # digital-out with no guaranteed sink)-# Preference order for "auto-headset": the first match is used.-# 2026-05-10: "PRO X" is listed first because sounddevice often lists Logitech-# headsets as "Lautsprecher (PRO X)" (without the manufacturer name) — "Logitech-# PRO X" misses the user's headset and falls back to the Realtek on-board device.+# Generic default preference order for "auto-headset" output: a curated list of+# common consumer headset product families, most specific first. It is NOT tied+# to any one machine's hardware — a user whose device is not covered names it+# via ``[audio].output_device_priority`` (consulted BEFORE this list) or pins an+# explicit ``[audio].output_device`` index, both without editing code.+#+# "PRO X" precedes "Logitech PRO X" because sounddevice frequently enumerates+# Logitech headsets as "Lautsprecher (PRO X)" / "Speakers (PRO X)" WITHOUT the+# vendor name, so the bare product token matches where "Logitech PRO X" would+# miss and fall back to the on-board Realtek device. The other bare tokens+# (Arctis, AirPods, Bose, …) exist for the same reason — many headsets list+# their model without the vendor prefix._HEADSET_PRIORITY = ("PRO X", "Logitech PRO X", "Logitech",- "Jabra", "Sennheiser", "SteelSeries", "Corsair", "HyperX", "Razer",+ "Jabra", "Sennheiser", "SteelSeries", "Arctis", "Corsair", "HyperX",+ "Razer", "Bose", "AirPods","USB Audio", "Headset","Realtek HD Audio", "Realtek",)@@ -162,20 +175,33 @@ def _candidate_output_rates(source_rate: int, device_default: int = 0) -> list[ireturn candidates-def _resolve_output_device(device: int | str | None) -> int | str | None:+def _resolve_output_device(+ device: int | str | None,+ priority: Sequence[str] | None = None,+) -> int | str | None:"""Resolve "auto-headset" or None to a concrete device index.- int: returned as-is (user specified an explicit index)- None: system default- "auto-headset": searches output devices for headset patterns, skips- GPU-HDMI outputs (monitor speakers), prefers WASAPI over MME- (mono routing bug on 8-channel surround)+ GPU-HDMI outputs (monitor speakers) and the localized MME/DirectSound+ virtual mapper, prefers WASAPI over MME (mono routing bug on 8-channel+ surround)++ ``priority`` is the user's own device-name preference+ (``[audio].output_device_priority``). When non-empty, a device whose name+ contains a user entry outranks EVERY generic ``_HEADSET_PRIORITY`` match, so+ a user with an uncommon headset (Focusrite, an audio interface, a specific+ dongle) wins by naming it — no code edit. Empty ``priority`` reproduces the+ generic-only behavior exactly."""if device is None or isinstance(device, int):return deviceif not isinstance(device, str) or device != "auto-headset":return device+ user_priority = tuple(p for p in (priority or ()) if p)+try:devices = sd.query_devices()hostapis = sd.query_hostapis()@@ -193,7 +219,12 @@ def _resolve_output_device(device: int | str | None) -> int | str | None:if d.get("max_output_channels", 0) <= 0:continuename = d.get("name", "")- if any(blocked in name for blocked in _BLOCKED_OUTPUT_SUBSTRINGS):+ low = name.lower()+ if any(blocked.lower() in low for blocked in _BLOCKED_OUTPUT_SUBSTRINGS):+ continue+ # Locale-independent skip of the MME "Sound Mapper" / DirectSound+ # "Primary Sound Driver" virtual router (translated display name).+ if is_legacy_primary_mapper(idx, hostapis, devices, output=True):continuehostapi_idx = d.get("hostapi", -1)hostapi_name = (@@ -228,11 +259,18 @@ def _resolve_output_device(device: int | str | None) -> int | str | None:return 99def _name_rank(entry: tuple[int, dict]) -> int:- name = entry[1].get("name", "")- for rank, sub in enumerate(_HEADSET_PRIORITY):- if sub.lower() in name.lower():+ low = entry[1].get("name", "").lower()+ # User-configured names take strict precedence: any match in the user's+ # priority list ranks ahead of every generic match. Both blocks keep+ # "earlier entry = stronger". The generic block is offset by the user+ # list length so a generic hit can never tie or beat a user hit.+ for rank, sub in enumerate(user_priority):+ if sub.lower() in low:return rank- return len(_HEADSET_PRIORITY)+ for rank, sub in enumerate(_HEADSET_PRIORITY):+ if sub.lower() in low:+ return len(user_priority) + rank+ return len(user_priority) + len(_HEADSET_PRIORITY)# Primary sort key: name match; secondary: host API preference. Without a# name match the original order (system default) is preserved.@@ -264,10 +302,17 @@ class AudioPlayer:channels: int = 1,bus: Any = None,volume: float = 1.0,+ device_priority: Sequence[str] | None = None,) -> None:+ # User-configured device-name priority ([audio].output_device_priority).+ # Consulted BEFORE the generic _HEADSET_PRIORITY default when resolving+ # "auto-headset", so an uncommon headset wins by name without a code+ # edit. Empty tuple = today's generic behavior. Kept so set_device can+ # re-resolve with the same preference after a hot-swap.+ self._device_priority: tuple[str, ...] = tuple(device_priority or ())# Resolve "auto-headset" / similar strings to the actual device index.# Integer values are not resolved — the user specifies those explicitly.- self._device = _resolve_output_device(device)+ self._device = _resolve_output_device(device, self._device_priority)self._sample_rate = sample_rateself._channels = channels# Master output volume knob in [0.0, 1.0]. Applied in _write_samples via@@ -374,7 +419,12 @@ class AudioPlayer:``self._device = _resolve_output_device(device)`` plus reloggingthe new device on the next play."""- new_device = _resolve_output_device(device)+ # ``getattr`` default keeps ``__new__``-built instances (test fixtures /+ # hot-reload that skip ``__init__``) working — same pattern as the+ # ``_volume`` / progress-counter reads elsewhere in this class.+ new_device = _resolve_output_device(+ device, getattr(self, "_device_priority", ())+ )if new_device == self._device:return # no-op; avoid needless cache flushself._device = new_devicediff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 5293f70f0c..e1eb0f0c2e 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -1120,6 +1120,27 @@ class MCPServerConfig(BaseModel):class AudioConfig(BaseModel):input_device: str = "auto-headset"output_device: str = "auto-headset"+ # Optional user-defined device-name priority for the "auto-headset" resolver.+ # Each entry is a case-insensitive substring of a device name; earlier =+ # higher priority. When non-empty, these are matched BEFORE the built-in+ # generic headset list, so a user with an uncommon device (e.g. "Focusrite",+ # "Bose", "AirPods", a specific USB dongle) makes it win without editing+ # code. Empty (default) keeps the generic auto-detection. Ignored when+ # input_device/output_device is an explicit index or a concrete name.+ output_device_priority: list[str] = Field(+ default_factory=list,+ description=(+ "Preferred output-device name substrings (highest priority first); "+ "consulted before the generic headset auto-detection."+ ),+ )+ input_device_priority: list[str] = Field(+ default_factory=list,+ description=(+ "Preferred input (microphone) device name substrings (highest "+ "priority first); consulted before the generic auto-detection."+ ),+ )echo_cancellation: bool = Truesample_rate: int = 16000frame_ms: int = 10diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 049682dd97..822e6a552b 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1342,7 +1342,23 @@ class SpeechPipeline:# chain: ``config`` may be None (test fixtures) and older TOMLs predate# the field — both fall back to full volume._tts_volume = getattr(getattr(config, "tts", None), "volume", 1.0)- self._player = AudioPlayer(device=output_device, bus=bus, volume=_tts_volume)+ # Optional user device-name priority ([audio].*_device_priority) fed into+ # the "auto-headset" resolver so an uncommon headset/mic wins by name+ # without a code edit. Defensive getattr: ``config`` may be None (test+ # fixtures) and older TOMLs predate the fields — both mean "no override".+ _audio_cfg = getattr(config, "audio", None)+ self._output_priority: tuple[str, ...] = tuple(+ getattr(_audio_cfg, "output_device_priority", None) or ()+ )+ self._input_priority: tuple[str, ...] = tuple(+ getattr(_audio_cfg, "input_device_priority", None) or ()+ )+ self._player = AudioPlayer(+ device=output_device,+ bus=bus,+ volume=_tts_volume,+ device_priority=self._output_priority,+ )# Kept so warm-up can re-resolve the output device against a freshly# re-enumerated PortAudio table (post-reboot idx-drift cure, BUG-014).self._output_device = output_device@@ -4330,7 +4346,9 @@ class SpeechPipeline:# which belong to the wake layer; this change deliberately does not touch# them. The drop-OLDEST overflow policy (capture ``_safe_put``) still# applies and is safe here.- async with MicrophoneCapture(device=self._input_device) as mic:+ async with MicrophoneCapture(+ device=self._input_device, device_priority=self._input_priority+ ) as mic:fanout_task = asyncio.create_task(_fanout(mic), name="fanout")oww_task = (asyncio.create_task(_run_oww(), name="oww-wake")@@ -4658,7 +4676,9 @@ class SpeechPipeline:if self._ptt_mode:return await self._ptt_session()async with MicrophoneCapture(- device=self._input_device, max_queue_chunks=REALTIME_QUEUE_CHUNKS+ device=self._input_device,+ max_queue_chunks=REALTIME_QUEUE_CHUNKS,+ device_priority=self._input_priority,) as mic:vad_iter = self._vad.utterances(self._session_input_stream(mic.stream())@@ -4800,7 +4820,9 @@ class SpeechPipeline:"""buffer = bytearray()hung_up = False- async with MicrophoneCapture(device=self._input_device) as mic:+ async with MicrophoneCapture(+ device=self._input_device, device_priority=self._input_priority+ ) as mic:mic_open_at = time.monotonic()await self._set_turn_state(TurnTakingState.LISTENING)await self._publish_event(ListeningStarted(source_layer="speech"))@@ -5059,7 +5081,9 @@ class SpeechPipeline:passtry:- async with MicrophoneCapture(device=self._input_device) as mic:+ async with MicrophoneCapture(+ device=self._input_device, device_priority=self._input_priority+ ) as mic:async def _drain() -> None:async for chunk in mic.stream():@@ -7920,7 +7944,9 @@ class SpeechPipeline:try:async with MicrophoneCapture(- device=self._input_device, max_queue_chunks=REALTIME_QUEUE_CHUNKS+ device=self._input_device,+ max_queue_chunks=REALTIME_QUEUE_CHUNKS,+ device_priority=self._input_priority,) as mic:residual = np.empty(0, dtype=np.float32)speech_run = 0diff --git a/tests/unit/audio/test_device_priority_and_mapper.py b/tests/unit/audio/test_device_priority_and_mapper.pynew file mode 100644index 0000000000..a8dd642d6c--- /dev/null+++ b/tests/unit/audio/test_device_priority_and_mapper.py@@ -0,0 +1,164 @@+"""Locale-robust auto-headset selection + user device-name priority.++Two guarantees pinned here:++1. **Locale robustness.** The MME "Sound Mapper" / DirectSound "Primary Sound+ Driver" virtual routers carry a Windows-*localized* display name, so the old+ German-only substring let the mapper through on+ English/French/… Windows and the resolver could route to the OS-default sink+ that ``auto-headset`` exists to bypass. They are now skipped STRUCTURALLY+ (``jarvis.audio.device_select.is_legacy_primary_mapper``) — the first+ direction-matching device of an MME/DirectSound host API — regardless of the+ translated name.++2. **Personalization.** ``[audio].output_device_priority`` /+ ``input_device_priority`` let any user float their own device to the top by+ name, ahead of the generic built-in headset list, without editing code. An+ empty priority reproduces the generic behavior exactly.+"""+from __future__ import annotations++import pytest++import jarvis.audio.capture as cap+import jarvis.audio.player as pl+from jarvis.audio.device_select import is_legacy_primary_mapper+++def _patch_out(monkeypatch, hostapis, devices) -> None:+ monkeypatch.setattr(pl.sd, "query_devices", lambda: devices)+ monkeypatch.setattr(pl.sd, "query_hostapis", lambda: hostapis)+++def _patch_in(monkeypatch, hostapis, devices) -> None:+ monkeypatch.setattr(cap.sd, "query_devices", lambda: devices)+ monkeypatch.setattr(cap.sd, "query_hostapis", lambda: hostapis)+++# --------------------------------------------------------------------------- #+# 1. Locale robustness — output #+# --------------------------------------------------------------------------- #+ "mapper_name",+ [+ "Primary Sound Driver", # EN+ "Primärer Soundtreiber", # DE, i18n-allow: localized name under test+ "Pilote son principal", # FR+ "Controlador primario de sonido", # ES+ "Driver audio primario", # IT+ ],+)+def test_localized_output_mapper_is_skipped_structurally(monkeypatch, mapper_name) -> None:+ """The DirectSound primary mapper must be skipped on ANY UI language.++ Table: DirectSound (better host-API rank) exposes its virtual primary+ device FIRST, then a real endpoint; MME exposes another real endpoint. All+ real devices carry an unrecognized name, so ranking falls to host-API+ preference — if the mapper were NOT skipped it would win the DirectSound+ tiebreak. Asserting the REAL DirectSound device is chosen proves the+ structural skip (a name-based filter would miss every non-German name here).+ """+ hostapis = [+ {"name": "Windows DirectSound", "devices": [0, 1]},+ {"name": "MME", "devices": [2]},+ ]+ devices = [+ {"name": mapper_name, "max_output_channels": 2,+ "max_input_channels": 0, "hostapi": 0}, # idx0: mapper+ {"name": "Line Out (Obscure Interface)", "max_output_channels": 2,+ "max_input_channels": 0, "hostapi": 0}, # idx1: real DSound+ {"name": "Line Out (Obscure Interface)", "max_output_channels": 2,+ "max_input_channels": 0, "hostapi": 1}, # idx2: real MME+ ]+ _patch_out(monkeypatch, hostapis, devices)++ resolved = pl._resolve_output_device("auto-headset")++ assert resolved == 1, (+ f"localized mapper {mapper_name!r} leaked through the resolver "+ "(regex-blind locale regression)"+ )+++def test_localized_input_recording_mapper_is_skipped_structurally(monkeypatch) -> None:+ """The DirectSound *recording* primary mapper is skipped too.++ No fixed substring ever covered the recording mapper (its localized name);+ the structural check catches it as the first input-capable DirectSound+ device.+ """+ hostapis = [+ {"name": "Windows DirectSound", "devices": [0, 1]},+ {"name": "MME", "devices": [2]},+ ]+ devices = [+ {"name": "Primary Sound Capture Driver", "max_input_channels": 2,+ "max_output_channels": 0, "hostapi": 0}, # idx0: in-mapper+ {"name": "Line In (Obscure Interface)", "max_input_channels": 2,+ "max_output_channels": 0, "hostapi": 0}, # idx1: real DSound+ {"name": "Line In (Obscure Interface)", "max_input_channels": 2,+ "max_output_channels": 0, "hostapi": 1}, # idx2: real MME+ ]+ _patch_in(monkeypatch, hostapis, devices)++ assert cap._resolve_input_device("auto-headset") == 1+++# --------------------------------------------------------------------------- #+# 2. Personalization — user priority beats the generic default #+# --------------------------------------------------------------------------- #+def test_output_user_priority_beats_generic_headset(monkeypatch) -> None:+ """A user-named device outranks a device the generic list would pick."""+ hostapis = [{"name": "Windows WASAPI", "devices": [0, 1]}]+ devices = [+ # Matches the generic default ("PRO X") — wins with no user priority.+ {"name": "Speakers (PRO X)", "max_output_channels": 2,+ "max_input_channels": 0, "hostapi": 0},+ # The user's own device — not in the generic list at all.+ {"name": "Bose QuietComfort Ultra", "max_output_channels": 2,+ "max_input_channels": 0, "hostapi": 0},+ ]+ _patch_out(monkeypatch, hostapis, devices)++ # Empty priority → generic behavior: the PRO X wins.+ assert pl._resolve_output_device("auto-headset") == 0+ assert pl._resolve_output_device("auto-headset", []) == 0+ # User names their Bose → it wins over the generic PRO X match.+ assert pl._resolve_output_device("auto-headset", ["Bose"]) == 1+++def test_input_user_priority_overrides_generic_and_deprioritize(monkeypatch) -> None:+ """A user-named mic wins even over the virtual-mic deprioritize penalty."""+ hostapis = [{"name": "Windows WASAPI", "devices": [0, 1]}]+ devices = [+ # Real headset mic — matches the generic default ("PRO X").+ {"name": "Microphone (PRO X)", "max_input_channels": 1,+ "max_output_channels": 0, "hostapi": 0},+ # Virtual mic — normally pushed BEHIND every real mic (deprioritized).+ {"name": "Microphone (NVIDIA Broadcast)", "max_input_channels": 2,+ "max_output_channels": 0, "hostapi": 0},+ ]+ _patch_in(monkeypatch, hostapis, devices)++ # Empty priority → the real headset mic wins, virtual is deprioritized.+ assert cap._resolve_input_device("auto-headset") == 0+ # User explicitly names the virtual mic → honored despite the penalty.+ assert cap._resolve_input_device("auto-headset", ["NVIDIA Broadcast"]) == 1+++# --------------------------------------------------------------------------- #+# 3. Structural helper — direct + fail-safe #+# --------------------------------------------------------------------------- #+def test_mapper_helper_fails_safe_without_membership_list() -> None:+ """A partial host-API table (no ``devices`` member list, as in older test+ fakes) must never mis-classify a device as a mapper."""+ hostapis = [{"name": "MME"}] # no "devices" key+ devices = [{"name": "Whatever", "max_output_channels": 2, "hostapi": 0}]+ assert is_legacy_primary_mapper(0, hostapis, devices, output=True) is False+++def test_mapper_helper_only_flags_mme_and_directsound() -> None:+ """WASAPI/WDM-KS expose no virtual mapper — their first device is real."""+ hostapis = [{"name": "Windows WASAPI", "devices": [0]}]+ devices = [{"name": "Speakers", "max_output_channels": 2, "hostapi": 0}]+ assert is_legacy_primary_mapper(0, hostapis, devices, output=True) is Falsediff --git a/tests/unit/audio/test_player_device_swap.py b/tests/unit/audio/test_player_device_swap.pyindex dcc1d9983e..81446d4c9b 100644--- a/tests/unit/audio/test_player_device_swap.py+++ b/tests/unit/audio/test_player_device_swap.py@@ -172,8 +172,12 @@ def test_set_device_with_auto_headset_string_resolves(monkeypatch) -> None:"""import jarvis.audio.player as player_mod+ # _resolve_output_device now takes an optional priority arg (user+ # device-name preference); the stub accepts and ignores it.monkeypatch.setattr(- player_mod, "_resolve_output_device", lambda d: 42 if d == "auto-headset" else d+ player_mod,+ "_resolve_output_device",+ lambda d, priority=None: 42 if d == "auto-headset" else d,)p = _make_player(device=3)