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.

fix(audio): refresh hot-plugged device picker safely

Ruben Lütkef3ad3513cd27
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index 8214e12690..26d9fe4545 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -18,6 +18,15 @@ import signal
import sys
from typing import NoReturn
+# A frozen GUI executable cannot be relaunched with ``python -m`` and has no
+# reliable stdout. Dispatch this private, file-backed sidecar mode before the
+# normal desktop imports so Settings can safely enumerate newly hot-plugged
+# audio hardware in a separate PortAudio instance.
+if len(sys.argv) == 3 and sys.argv[1] == "--audio-device-probe":
+ from jarvis.audio.device_probe import main as _audio_device_probe_main
+
+ raise SystemExit(_audio_device_probe_main(sys.argv[2]))
+
# Windows Terminal defaults to cp1252 — which breaks Unicode (box-drawing,
# emojis, ✓/✗). Force utf-8 before printing anything.
if sys.platform == "win32":
diff --git a/jarvis/audio/device_probe.py b/jarvis/audio/device_probe.py
new file mode 100644
index 0000000000..599ef8035c
--- /dev/null
+++ b/jarvis/audio/device_probe.py
@@ -0,0 +1,93 @@
+"""Emit a fresh-process PortAudio device snapshot for Settings.
+
+PortAudio freezes its device table when it initializes. A long-running
+desktop process therefore cannot discover a headset connected later by simply
+calling ``query_devices()`` again. This tiny worker starts a separate Python
+process, whose new PortAudio instance sees the current operating-system device
+set, and returns only the fields used by :mod:`jarvis.audio.devices`.
+
+The worker is intentionally independent from the live audio process. It never
+terminates or reinitializes that process's PortAudio instance, so an open wake
+microphone or output stream cannot be invalidated during a Settings rescan.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+SNAPSHOT_MARKER = "JARVIS_AUDIO_DEVICE_SNAPSHOT="
+
+
+def _device_index(value: object) -> int:
+ """Normalize a sounddevice default index to an integer sentinel."""
+ try:
+ index = int(value) # type: ignore[arg-type]
+ except (TypeError, ValueError, OverflowError):
+ return -1
+ return index if index >= 0 else -1
+
+
+def collect_snapshot() -> dict[str, Any]:
+ """Return the current PortAudio tables, or an honest empty headless set."""
+ try:
+ import sounddevice as sd # noqa: PLC0415 - optional desktop dependency
+ except Exception: # noqa: BLE001 - no PortAudio is normal on headless hosts
+ return {"ok": True, "devices": [], "hostapis": [], "default": [-1, -1]}
+
+ try:
+ devices = [
+ {
+ "name": str(device.get("name", "")),
+ "hostapi": _device_index(device.get("hostapi", -1)),
+ "max_input_channels": int(device.get("max_input_channels", 0) or 0),
+ "max_output_channels": int(device.get("max_output_channels", 0) or 0),
+ }
+ for device in sd.query_devices()
+ ]
+ hostapis = [
+ {
+ "name": str(hostapi.get("name", "")),
+ "devices": [_device_index(index) for index in hostapi.get("devices", ())],
+ }
+ for hostapi in sd.query_hostapis()
+ ]
+ default_pair = sd.default.device
+ default = [_device_index(default_pair[0]), _device_index(default_pair[1])]
+ except Exception: # noqa: BLE001 - the parent falls back to its cached table
+ return {"ok": False, "devices": [], "hostapis": [], "default": [-1, -1]}
+
+ return {
+ "ok": True,
+ "devices": devices,
+ "hostapis": hostapis,
+ "default": default,
+ }
+
+
+def main(output_path: str | None = None) -> int:
+ """Write one marker-delimited JSON record for the parent process.
+
+ Frozen GUI builds have no usable stdout, so their internal probe mode
+ supplies a private temporary output path. The plain module entry point
+ keeps stdout support for diagnostics and development.
+ """
+ payload = collect_snapshot()
+ record = SNAPSHOT_MARKER + json.dumps(
+ payload, ensure_ascii=True, separators=(",", ":")
+ )
+ if output_path is not None:
+ try:
+ Path(output_path).write_text(record + "\n", encoding="utf-8")
+ except OSError:
+ return 1
+ else:
+ print(record, flush=True)
+ return 0
+
+
+if __name__ == "__main__":
+ import sys
+
+ raise SystemExit(main(sys.argv[1] if len(sys.argv) == 2 else None))
diff --git a/jarvis/audio/devices.py b/jarvis/audio/devices.py
index 713b13f302..b2c3191d87 100644
--- a/jarvis/audio/devices.py
+++ b/jarvis/audio/devices.py
@@ -25,8 +25,13 @@ and the stream-open resolvers.
"""
from __future__ import annotations
+import json
+import subprocess
+import sys
+import tempfile
import unicodedata
from dataclasses import dataclass
+from pathlib import Path
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
@@ -51,6 +56,7 @@ from jarvis.audio.capture import (
from jarvis.audio.capture import (
_HOSTAPI_PREFERENCE as _INPUT_HOSTAPI_PREFERENCE,
)
+from jarvis.audio.device_probe import SNAPSHOT_MARKER
from jarvis.audio.device_select import is_legacy_primary_mapper
from jarvis.audio.player import (
_FORBIDDEN_OUTPUT_HOSTAPIS as _OUTPUT_FORBIDDEN_HOSTAPIS,
@@ -58,6 +64,7 @@ from jarvis.audio.player import (
from jarvis.audio.player import (
_HOSTAPI_PREFERENCE as _OUTPUT_HOSTAPI_PREFERENCE,
)
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
#: The config sentinel for "pick a device automatically" (the default in
#: ``[audio].input_device`` / ``[audio].output_device``).
@@ -67,6 +74,9 @@ AUTO_DEVICE = "auto-headset"
# 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
+_FRESH_PROBE_TIMEOUT_S = 4.0
+
+_DeviceTables = tuple[list[Any], list[Any], tuple[int | None, int | None]]
@dataclass(frozen=True)
@@ -96,16 +106,103 @@ def _hostapi_name(dev: dict[str, Any], hostapis: list[Any]) -> str:
return ""
-def _query_tables() -> tuple[list[Any], list[Any]] | None:
- """The (devices, hostapis) tables, or None when PortAudio is unusable."""
+def _default_index(value: object) -> int | None:
+ """Normalize a sounddevice device index, including non-int scalar types."""
+ try:
+ index = int(value) # type: ignore[arg-type]
+ except (TypeError, ValueError, OverflowError):
+ return None
+ return index if index >= 0 else None
+
+
+def _query_tables_in_process() -> _DeviceTables | None:
+ """Return this process's cached PortAudio tables, if usable."""
if sd is None:
return None
try:
- return list(sd.query_devices()), list(sd.query_hostapis())
+ default_pair = sd.default.device
+ defaults = (_default_index(default_pair[0]), _default_index(default_pair[1]))
+ return list(sd.query_devices()), list(sd.query_hostapis()), defaults
except Exception: # noqa: BLE001 — enumeration must never raise (headless)
return None
+def _fresh_probe_command(output_path: Path) -> list[str]:
+ """Build the probe command for source and frozen desktop installations."""
+ if getattr(sys, "frozen", False):
+ return [sys.executable, "--audio-device-probe", str(output_path)]
+ return [
+ sys.executable,
+ "-m",
+ "jarvis.audio.device_probe",
+ str(output_path),
+ ]
+
+
+def _query_tables_fresh() -> _DeviceTables | None:
+ """Query a new PortAudio process so post-start hot-plugs are visible.
+
+ PortAudio's device list is immutable between initialize and terminate. A
+ child process is the only safe rescan while this process owns live streams:
+ reinitializing the shared instance would close those streams and has caused
+ native CoreAudio faults on macOS. Any worker failure falls back to the
+ in-process table, preserving the headless and degraded-mode contracts.
+ """
+ try:
+ with tempfile.TemporaryDirectory(prefix="jarvis-audio-probe-") as temp_dir:
+ output_path = Path(temp_dir) / "snapshot.json"
+ subprocess.run(
+ _fresh_probe_command(output_path),
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ timeout=_FRESH_PROBE_TIMEOUT_S,
+ check=False,
+ close_fds=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ record = output_path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+ marker_line = next(
+ (line for line in reversed(record.splitlines()) if line.startswith(SNAPSHOT_MARKER)),
+ "",
+ )
+ if not marker_line:
+ return None
+ try:
+ payload = json.loads(marker_line.removeprefix(SNAPSHOT_MARKER))
+ except (json.JSONDecodeError, TypeError):
+ return None
+ if not isinstance(payload, dict) or payload.get("ok") is not True:
+ return None
+ devices = payload.get("devices")
+ hostapis = payload.get("hostapis")
+ defaults = payload.get("default")
+ if not isinstance(devices, list) or not isinstance(hostapis, list):
+ return None
+ if not all(isinstance(device, dict) for device in devices) or not all(
+ isinstance(hostapi, dict) for hostapi in hostapis
+ ):
+ return None
+ if not isinstance(defaults, list) or len(defaults) != 2:
+ return None
+ return (
+ devices,
+ hostapis,
+ (_default_index(defaults[0]), _default_index(defaults[1])),
+ )
+
+
+def _query_tables(*, fresh: bool = False) -> _DeviceTables | None:
+ """Return current or safely refreshed PortAudio device tables."""
+ if fresh:
+ tables = _query_tables_fresh()
+ if tables is not None:
+ return tables
+ return _query_tables_in_process()
+
+
def _candidates(
devices: list[Any], hostapis: list[Any], *, output: bool
) -> list[tuple[int, dict[str, Any], str]]:
@@ -135,30 +232,17 @@ def _hostapi_rank(hostapi: str, *, output: bool) -> int:
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 _os_default_index(defaults: tuple[int | None, int | None], *, output: bool) -> int | None:
+ return defaults[1 if output else 0]
-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
+def _list_devices_from_tables(tables: _DeviceTables, *, output: bool) -> list[AudioDeviceInfo]:
+ devices, hostapis, defaults = tables
cands = _candidates(devices, hostapis, output=output)
if not cands:
return []
- default_idx = _os_default_index(output=output)
+ default_idx = _os_default_index(defaults, output=output)
default_name = ""
if default_idx is not None and 0 <= default_idx < len(devices):
default_name = str(devices[default_idx].get("name", ""))
@@ -202,6 +286,34 @@ def list_devices(*, output: bool) -> list[AudioDeviceInfo]:
return entries
+def list_devices(*, output: bool, fresh: bool = False) -> 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). ``fresh=True`` uses an isolated PortAudio process
+ so devices connected after desktop startup are included without touching
+ live audio streams. Headless / no PortAudio yields ``[]``.
+ """
+ tables = _query_tables(fresh=fresh)
+ if tables is None:
+ return []
+ return _list_devices_from_tables(tables, output=output)
+
+
+def list_device_options(
+ *, fresh: bool = False
+) -> tuple[list[AudioDeviceInfo], list[AudioDeviceInfo]]:
+ """Return output and input picker entries from one consistent snapshot."""
+ tables = _query_tables(fresh=fresh)
+ if tables is None:
+ return [], []
+ return (
+ _list_devices_from_tables(tables, output=True),
+ _list_devices_from_tables(tables, output=False),
+ )
+
+
def resolve_device_by_name(name: str, *, output: bool) -> int | None:
"""The PortAudio index for a persisted device NAME, or None when absent.
@@ -218,7 +330,7 @@ def resolve_device_by_name(name: str, *, output: bool) -> int | None:
tables = _query_tables()
if tables is None:
return None
- devices, hostapis = tables
+ devices, hostapis, _defaults = tables
target_cf = _canon(target)
# Same-device pool: exact matches plus truncation twins (the candidate is
diff --git a/jarvis/ui/web/frontend/src/hooks/useAudioDevices.ts b/jarvis/ui/web/frontend/src/hooks/useAudioDevices.ts
index bbb31474ef..cb911b753f 100644
--- a/jarvis/ui/web/frontend/src/hooks/useAudioDevices.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useAudioDevices.ts
@@ -5,7 +5,8 @@ import { useCallback, useEffect, useState } from "react";
* which microphone it listens with. GET /api/settings/audio-devices lists one
* entry per physical device plus the current [audio] selection; PUT persists
* a device NAME (or the "auto-headset" sentinel for automatic selection) and
- * live-applies it to the running voice pipeline. Mirrors useTtsVolume.
+ * safely live-applies it when the running audio table already contains it;
+ * newly hot-plugged devices take effect after the next app start.
*/
export interface AudioDeviceEntry {
name: string;
@@ -55,6 +56,14 @@ export function useAudioDevices() {
void refetch();
}, [refetch]);
+ useEffect(() => {
+ const mediaDevices = navigator.mediaDevices;
+ if (!mediaDevices?.addEventListener) return;
+ const onDeviceChange = () => void refetch();
+ mediaDevices.addEventListener("devicechange", onDeviceChange);
+ return () => mediaDevices.removeEventListener("devicechange", onDeviceChange);
+ }, [refetch]);
+
const select = useCallback(
async (
kind: "output" | "input",
diff --git a/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.test.tsx
index 6d5c09b71c..62ebf53b27 100644
--- a/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.test.tsx
@@ -1,4 +1,10 @@
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { AudioDevicesGroup } from "./AudioDevicesGroup";
@@ -129,4 +135,45 @@ describe("AudioDevicesGroup", () => {
expect(output.value).toBe("Jabra Evolve2 65");
});
});
+
+ it("rescans when the browser reports an audio-device change", async () => {
+ let deviceChange: EventListener | undefined;
+ const mediaDevices = {
+ addEventListener: vi.fn((type: string, listener: EventListener) => {
+ if (type === "devicechange") deviceChange = listener;
+ }),
+ removeEventListener: vi.fn(),
+ };
+ const previous = Object.getOwnPropertyDescriptor(
+ window.navigator,
+ "mediaDevices",
+ );
+ Object.defineProperty(window.navigator, "mediaDevices", {
+ configurable: true,
+ value: mediaDevices,
+ });
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => DESKTOP,
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const view = render(<AudioDevicesGroup />);
+ try {
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ act(() => deviceChange?.(new Event("devicechange")));
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ view.unmount();
+ expect(mediaDevices.removeEventListener).toHaveBeenCalledWith(
+ "devicechange",
+ deviceChange,
+ );
+ } finally {
+ if (previous) {
+ Object.defineProperty(window.navigator, "mediaDevices", previous);
+ } else {
+ Reflect.deleteProperty(window.navigator, "mediaDevices");
+ }
+ }
+ });
});
diff --git a/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.tsx
index 94b9f147c1..043c328840 100644
--- a/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.tsx
@@ -13,8 +13,9 @@ import { useT } from "@/i18n";
* listens with). The first option is always "Automatic (recommended)" — the
* auto-headset resolver; concrete entries are physical devices by display
* name (stable across reboots, unlike device indices). A pick saves
- * immediately and applies live to the running voice pipeline; the rescan
- * button re-enumerates after plugging in a headset. On a host without audio
+ * immediately and applies live when safe; a device connected after app start
+ * is activated on the next start. The picker rescans on OS device-change
+ * events, while the button remains a manual fallback. On a host without audio
* hardware the card degrades to a caption instead of empty dropdowns.
*/
export function AudioDevicesGroup() {
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 3cd313316e..135696d55c 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -2464,13 +2464,29 @@ def _selected_audio_devices(request: Request) -> tuple[str, str]:
return out, inp
+def _audio_device_available_in_live_table(value: str, *, output: bool) -> bool:
+ """Whether the running PortAudio instance can open an explicit device.
+
+ A fresh Settings probe can see hardware connected after this process
+ initialized PortAudio, while the live table remains frozen. Such a pick is
+ still persisted, but it must wait for the next app start instead of being
+ falsely reported as live-applied (or resolving to a different old index).
+ """
+ if value == AUDIO_AUTO_DEVICE:
+ return True
+ from jarvis.audio.devices import resolve_device_by_name
+
+ return resolve_device_by_name(value, output=output) is not None
+
+
@router.get("/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
+ from jarvis.audio.devices import list_device_options
- outputs = await asyncio.to_thread(lambda: list_devices(output=True))
- inputs = await asyncio.to_thread(lambda: list_devices(output=False))
+ outputs, inputs = await asyncio.to_thread(
+ lambda: list_device_options(fresh=True)
+ )
selected_output, selected_input = _selected_audio_devices(request)
return {
"available": bool(outputs or inputs),
@@ -2486,7 +2502,26 @@ async def get_audio_devices(request: Request) -> dict[str, object]:
async def put_audio_devices(
body: AudioDeviceSelectBody, request: Request
) -> dict[str, object]:
- """Persist + live-apply the audio device selection (name or auto)."""
+ """Persist an audio selection and live-apply it when the table is current."""
+ output_live = (
+ await asyncio.to_thread(
+ _audio_device_available_in_live_table,
+ body.output_device,
+ output=True,
+ )
+ if body.output_device is not None
+ else False
+ )
+ input_live = (
+ await asyncio.to_thread(
+ _audio_device_available_in_live_table,
+ body.input_device,
+ output=False,
+ )
+ if body.input_device is not None
+ else False
+ )
+
# Best-effort in-memory cfg update so later cfg reads (voice-offline
# alerts, the voice watchdog restart path) agree pre-restart.
cfg = _config(request)
@@ -2523,7 +2558,10 @@ async def put_audio_devices(
# 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
+ applied_sides = 0
+ requested_sides = int(body.output_device is not None) + int(
+ body.input_device is not None
+ )
pipeline = getattr(request.app.state, "speech_pipeline", None)
if pipeline is not None and hasattr(pipeline, "set_audio_devices"):
try:
@@ -2534,18 +2572,33 @@ async def put_audio_devices(
# whole API/WS surface. The INPUT side must stay ON the loop: it
# only sets an attribute and flips the asyncio wake-reload Event,
# and asyncio primitives are not thread-safe.
- if body.output_device is not None:
+ if body.output_device is not None and output_live:
await asyncio.to_thread(
pipeline.set_audio_devices, output_device=body.output_device
)
- if body.input_device is not None:
+ applied_sides += 1
+ if body.input_device is not None and input_live:
pipeline.set_audio_devices(input_device=body.input_device)
- applied_live = True
+ applied_sides += 1
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,
)
+ if body.output_device is not None and not output_live:
+ log.info(
+ "audio output %r is not present in the live PortAudio table; "
+ "saved for the next app start",
+ body.output_device,
+ )
+ if body.input_device is not None and not input_live:
+ log.info(
+ "audio input %r is not present in the live PortAudio table; "
+ "saved for the next app start",
+ body.input_device,
+ )
+
+ applied_live = applied_sides == requested_sides
selected_output, selected_input = _selected_audio_devices(request)
return {
diff --git a/tests/unit/audio/test_devices.py b/tests/unit/audio/test_devices.py
index 80699b7871..4355617841 100644
--- a/tests/unit/audio/test_devices.py
+++ b/tests/unit/audio/test_devices.py
@@ -17,10 +17,14 @@ Guards for :mod:`jarvis.audio.devices`:
"""
from __future__ import annotations
+import json
+import sys
+from pathlib import Path
from types import SimpleNamespace
import pytest
+from jarvis.audio import device_probe
from jarvis.audio import devices as dv
@@ -154,6 +158,138 @@ def test_list_devices_without_sounddevice_returns_empty(monkeypatch) -> None:
assert dv.list_devices(output=False) == []
+def test_fresh_probe_without_sounddevice_returns_empty_headless_snapshot(
+ monkeypatch,
+) -> None:
+ monkeypatch.setitem(sys.modules, "sounddevice", None)
+
+ snapshot = device_probe.collect_snapshot()
+
+ assert snapshot == {
+ "ok": True,
+ "devices": [],
+ "hostapis": [],
+ "default": [-1, -1],
+ }
+
+
+def test_device_probe_main_writes_marker_file(monkeypatch, tmp_path) -> None:
+ payload = {"ok": True, "devices": [], "hostapis": [], "default": [-1, -1]}
+ monkeypatch.setattr(device_probe, "collect_snapshot", lambda: payload)
+ output_path = tmp_path / "snapshot.json"
+
+ assert device_probe.main(str(output_path)) == 0
+
+ record = output_path.read_text(encoding="utf-8").strip()
+ assert record.startswith(device_probe.SNAPSHOT_MARKER)
+ assert json.loads(record.removeprefix(device_probe.SNAPSHOT_MARKER)) == payload
+
+
+def test_fresh_options_use_isolated_snapshot_instead_of_stale_live_table(
+ monkeypatch,
+) -> None:
+ """A headset connected after startup must appear without reinitializing the
+ live PortAudio instance that owns the wake and playback streams."""
+ stale_hostapis = [{"name": "Core Audio", "devices": [0, 1]}]
+ stale_devices = [
+ {
+ "name": "Built-in Microphone",
+ "hostapi": 0,
+ "max_input_channels": 1,
+ "max_output_channels": 0,
+ },
+ {
+ "name": "Built-in Speakers",
+ "hostapi": 0,
+ "max_input_channels": 0,
+ "max_output_channels": 2,
+ },
+ ]
+ _patch_tables(monkeypatch, stale_hostapis, stale_devices, default=(0, 1))
+ fresh_payload = {
+ "ok": True,
+ "hostapis": [{"name": "Core Audio", "devices": [0, 1, 2, 3]}],
+ "devices": [
+ {
+ "name": "External Microphone",
+ "hostapi": 0,
+ "max_input_channels": 1,
+ "max_output_channels": 0,
+ },
+ {
+ "name": "External Headphones",
+ "hostapi": 0,
+ "max_input_channels": 0,
+ "max_output_channels": 2,
+ },
+ *stale_devices,
+ ],
+ "default": [0, 1],
+ }
+ calls: list[tuple[list[str], dict]] = []
+
+ def fake_run(command, **kwargs):
+ calls.append((command, kwargs))
+ Path(command[-1]).write_text(
+ dv.SNAPSHOT_MARKER + json.dumps(fresh_payload) + "\n",
+ encoding="utf-8",
+ )
+ return SimpleNamespace(returncode=0)
+
+ monkeypatch.setattr(dv.subprocess, "run", fake_run)
+
+ outputs, inputs = dv.list_device_options(fresh=True)
+
+ assert [entry.name for entry in outputs] == [
+ "External Headphones",
+ "Built-in Speakers",
+ ]
+ assert [entry.name for entry in inputs] == [
+ "External Microphone",
+ "Built-in Microphone",
+ ]
+ assert outputs[0].is_default is True
+ assert inputs[0].is_default is True
+ assert calls[0][0][1:3] == ["-m", "jarvis.audio.device_probe"]
+ assert calls[0][1]["creationflags"] == dv.NO_WINDOW_CREATIONFLAGS
+
+
+def test_fresh_probe_uses_internal_mode_in_frozen_desktop(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(dv.sys, "frozen", True, raising=False)
+ output_path = tmp_path / "snapshot.json"
+
+ command = dv._fresh_probe_command(output_path)
+
+ assert command == [
+ dv.sys.executable,
+ "--audio-device-probe",
+ str(output_path),
+ ]
+
+
+def test_fresh_probe_failure_falls_back_to_live_table(monkeypatch) -> None:
+ hostapis = [{"name": "ALSA", "devices": [0]}]
+ devices = [
+ {
+ "name": "USB Audio",
+ "hostapi": 0,
+ "max_input_channels": 1,
+ "max_output_channels": 2,
+ }
+ ]
+ _patch_tables(monkeypatch, hostapis, devices, default=(0, 0))
+ monkeypatch.setattr(
+ dv.subprocess,
+ "run",
+ lambda *args, **kwargs: SimpleNamespace(stdout="", returncode=1),
+ )
+
+ outputs, inputs = dv.list_device_options(fresh=True)
+
+ assert [entry.name for entry in outputs] == ["USB Audio"]
+ assert [entry.name for entry in inputs] == ["USB Audio"]
+
+
# --------------------------------------------------------------------------- #
# Name resolution #
# --------------------------------------------------------------------------- #
diff --git a/tests/unit/ui/test_audio_devices_route.py b/tests/unit/ui/test_audio_devices_route.py
index 092559cc9f..9c44c11ef2 100644
--- a/tests/unit/ui/test_audio_devices_route.py
+++ b/tests/unit/ui/test_audio_devices_route.py
@@ -3,20 +3,32 @@
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.
+when its PortAudio table contains that device. A fresh-probe-only selection is
+saved for the next app start. Headless hosts degrade to available=false /
+restart_required=true — never a 500.
"""
from __future__ import annotations
from types import SimpleNamespace
+import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from jarvis.audio.devices import AudioDeviceInfo
+from jarvis.ui.web import settings_routes
from jarvis.ui.web.settings_routes import router
[email protected](autouse=True)
+def _assume_requested_device_is_in_live_table(monkeypatch):
+ monkeypatch.setattr(
+ settings_routes,
+ "_audio_device_available_in_live_table",
+ lambda value, *, output: True,
+ )
+
+
def _client(*, output_device="auto-headset", input_device="auto-headset", pipeline=None):
app = FastAPI()
app.include_router(router)
@@ -33,8 +45,14 @@ def _client(*, output_device="auto-headset", input_device="auto-headset", pipeli
def _fake_lists(monkeypatch, outputs, inputs):
import jarvis.audio.devices as dv
+ def fresh_options(*, fresh=False):
+ assert fresh is True
+ return outputs, inputs
+
monkeypatch.setattr(
- dv, "list_devices", lambda *, output: outputs if output else inputs
+ dv,
+ "list_device_options",
+ fresh_options,
)
@@ -136,6 +154,43 @@ def test_put_input_only_and_auto_reset(monkeypatch):
assert body["restart_required"] is True
+def test_put_hotplugged_device_waits_for_safe_next_start(monkeypatch):
+ """A fresh-probe-only index must never be applied to the stale live table."""
+ persisted: dict[str, str] = {}
+ import jarvis.core.config_writer as cw
+
+ monkeypatch.setattr(
+ cw,
+ "set_audio_device",
+ lambda kind, value, **kwargs: persisted.setdefault(kind, value),
+ )
+ monkeypatch.setattr(
+ settings_routes,
+ "_audio_device_available_in_live_table",
+ lambda value, *, output: value != "External Headphones",
+ )
+
+ applied: list[dict[str, str]] = []
+
+ class FakePipeline:
+ def set_audio_devices(self, **devices):
+ applied.append(devices)
+
+ response = _client(pipeline=FakePipeline()).put(
+ "/api/settings/audio-devices",
+ json={"output_device": "External Headphones", "persist": True},
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["selected_output"] == "External Headphones"
+ assert body["persisted"] is True
+ assert body["applied_live"] is False
+ assert body["restart_required"] is True
+ assert persisted == {"output": "External Headphones"}
+ assert applied == []
+
+
def test_put_requires_at_least_one_side():
r = _client().put("/api/settings/audio-devices", json={"persist": True})
assert r.status_code == 422