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): macOS audio ducking via AppleScript (Music/Spotify)
Joana Lütke4a660a82b2b4
diff --git a/jarvis/audio/ducking/__init__.py b/jarvis/audio/ducking/__init__.pyindex 0758a54c8c..f5ffee8e3a 100644--- a/jarvis/audio/ducking/__init__.py+++ b/jarvis/audio/ducking/__init__.py@@ -1,8 +1,10 @@"""Audio ducking — "Mute music while dictating".-Mutes other apps' audio sessions for the duration of a voice session and-restores them afterwards. Windows-only (pycaw); a logged no-op elsewhere so the-base headless install boots unaffected.+Lowers other apps' audio for the duration of a voice session and restores it+afterwards. Windows: per-app session mute via pycaw. macOS: AppleScript volume+duck of the known players (Music, Spotify) with an opt-in master-output+fallback. A logged no-op elsewhere so the base headless install boots+unaffected."""from __future__ import annotationsdiff --git a/jarvis/audio/ducking/controller.py b/jarvis/audio/ducking/controller.pyindex f85f7520bc..4419f74de5 100644--- a/jarvis/audio/ducking/controller.py+++ b/jarvis/audio/ducking/controller.py@@ -1,7 +1,7 @@"""AudioDuckController — mutes other apps' audio for the duration of a session.Subscribes ``VoiceSessionStarted`` (mute others) / ``VoiceSessionEnded``-(restore). The blocking pycaw/COM work runs in ``asyncio.to_thread`` with+(restore). The blocking backend work runs in ``asyncio.to_thread`` with``CoInitialize`` so it never touches the event loop. Our own PID is excludedfrom the mute sweep, which automatically protects Jarvis's own TTS voice."""@@ -82,6 +82,12 @@ class AudioDuckController:log.debug("in-memory ducking.enabled update skipped", exc_info=True)if not enabled:await self._restore_locked()+ return+ # Best-effort backend prewarm (macOS: fires the one-time Automation+ # TCC consent prompt at enable time instead of mid-session).+ pre = getattr(self._ducker, "prewarm", None)+ if callable(pre):+ await self._run(pre)async def restore(self) -> None:"""Force-restore (live path: turning the toggle off)."""@@ -159,4 +165,4 @@ class AudioDuckController:def make_audio_duck_controller(bus: Any, cfg: Any) -> AudioDuckController:"""Construct a controller with the platform-appropriate ducker backend."""- return AudioDuckController(bus=bus, cfg=cfg, ducker=make_audio_ducker())+ return AudioDuckController(bus=bus, cfg=cfg, ducker=make_audio_ducker(cfg))diff --git a/jarvis/audio/ducking/factory.py b/jarvis/audio/ducking/factory.pyindex 036d873269..340ae54a7b 100644--- a/jarvis/audio/ducking/factory.py+++ b/jarvis/audio/ducking/factory.py@@ -3,7 +3,9 @@ from __future__ import annotationsimport importlib.utilimport logging+import shutilimport sys+from typing import Anyfrom jarvis.audio.ducking.null import NullDuckerfrom jarvis.audio.ducking.protocol import AudioDucker@@ -15,11 +17,21 @@ def _pycaw_available() -> bool:return importlib.util.find_spec("pycaw") is not None-def make_audio_ducker() -> AudioDucker:- """Windows + pycaw → WindowsPycawDucker; otherwise a logged NullDucker."""+def _osascript_available() -> bool:+ return shutil.which("osascript") is not None+++def make_audio_ducker(cfg: Any | None = None) -> AudioDucker:+ """Windows + pycaw → WindowsPycawDucker; macOS + osascript →+ MacOSScriptDucker; otherwise a logged NullDucker.+ """if sys.platform == "win32" and _pycaw_available():from jarvis.audio.ducking.windows import WindowsPycawDuckerreturn WindowsPycawDucker()+ if sys.platform == "darwin" and _osascript_available():+ from jarvis.audio.ducking.macos import MacOSScriptDucker++ return MacOSScriptDucker.from_config(cfg)log.info("Audio ducking unavailable (platform=%s) — no-op.", sys.platform)return NullDucker()diff --git a/jarvis/audio/ducking/macos.py b/jarvis/audio/ducking/macos.pynew file mode 100644index 0000000000..40adeed0b7--- /dev/null+++ b/jarvis/audio/ducking/macos.py@@ -0,0 +1,211 @@+"""macOS AppleScript audio ducking (tiered: known players, then master volume).++Lowers the app-internal ``sound volume`` of the known media players (Music,+Spotify) via ``osascript`` for the duration of a voice session and restores+the previous volume afterwards. Optionally (opt-in) falls back to lowering the+MASTER output volume when no known player was ducked — note the master+fallback also lowers Jarvis's own TTS voice.++Pure stdlib and safe to import on any OS: the factory only constructs this+class when ``sys.platform == 'darwin'`` and ``osascript`` is on PATH. Every+osascript call is wrapped — a timeout, a non-zero exit (e.g. the Automation+TCC denial ``-1743``), or an unparsable volume degrades to a skipped player,+never an exception out of the runtime path.++CRITICAL script shape: a bare ``tell application ...`` LAUNCHES the app, so+every script guards with ``if application id "..." is running`` INSIDE the+same script and returns ``"-"`` when the player is not running.+"""+from __future__ import annotations++import logging+import subprocess+from collections.abc import Callable+from typing import Any++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++log = logging.getLogger("jarvis.audio.ducking")++# Opaque restore tokens — the controller treats them as an opaque list[int]+# of "PIDs", so player tokens and the master token just have to be distinct.+_PLAYERS: dict[int, tuple[str, str]] = {+ 1: ("Music", "com.apple.Music"),+ 2: ("Spotify", "com.spotify.client"),+}+_MASTER_TOKEN = 100++# Sentinel a script returns when the player is not running.+_NOT_RUNNING = "-"+++def _run_osascript(script: str) -> subprocess.CompletedProcess:+ """Default runner: one bounded, windowless osascript invocation."""+ return subprocess.run( # noqa: S603, S607 — fixed argv, no shell+ ["osascript", "-e", script],+ capture_output=True,+ text=True,+ timeout=3.0,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+++def _duck_script(bundle_id: str, target: int) -> str:+ """Read the player volume and duck it — one script, is-running-guarded."""+ return (+ f'if application id "{bundle_id}" is running then\n'+ f' tell application id "{bundle_id}"\n'+ f" set prev to sound volume\n"+ f" if prev > {target} then set sound volume to {target}\n"+ f" return prev\n"+ f" end tell\n"+ f"else\n"+ f' return "{_NOT_RUNNING}"\n'+ f"end if"+ )+++def _restore_script(bundle_id: str, volume: int) -> str:+ return (+ f'if application id "{bundle_id}" is running then\n'+ f' tell application id "{bundle_id}" to set sound volume to {volume}\n'+ f"end if"+ )+++def _prewarm_script(bundle_id: str) -> str:+ """Benign guarded query — enough to fire the Automation TCC prompt."""+ return (+ f'if application id "{bundle_id}" is running then\n'+ f' tell application id "{bundle_id}" to get player state\n'+ f"end if"+ )+++def _master_duck_script(target: int) -> str:+ return (+ "set prev to output volume of (get volume settings)\n"+ f"if prev > {target} then set volume output volume {target}\n"+ "return prev"+ )+++class MacOSScriptDucker:+ """Tiered AppleScript ducker: known players first, opt-in master fallback."""++ def __init__(+ self,+ *,+ master_fallback: bool = False,+ duck_volume_percent: int = 0,+ run: Callable[[str], subprocess.CompletedProcess] | None = None,+ ) -> None:+ self._master_fallback = bool(master_fallback)+ self._duck = max(0, min(100, int(duck_volume_percent)))+ self._run = run or _run_osascript+ self._saved: dict[int, int] = {} # token -> previous volume++ @classmethod+ def from_config(cls, cfg: Any | None) -> MacOSScriptDucker:+ try:+ ducking = getattr(cfg, "ducking", None)+ return cls(+ master_fallback=bool(getattr(ducking, "macos_master_fallback", False)),+ duck_volume_percent=int(+ getattr(ducking, "duck_volume_percent", 0) or 0+ ),+ )+ except Exception: # noqa: BLE001 — malformed config degrades to defaults+ log.debug("ducking config read failed; using defaults", exc_info=True)+ return cls()++ # ---- protocol ---------------------------------------------------------+ def mute_others(self, *, own_pid: int, never: frozenset[str]) -> list[int]:+ """Duck every running known player; master fallback if none was ducked.++ ``own_pid`` is unused (protocol conformance): the player tier changes+ per-app volumes, so Jarvis's own TTS is never affected by it. Returns+ opaque restore tokens (the controller treats them as PIDs).+ """+ del own_pid # per-app player volumes never touch our own process+ skip = self._normalized_never(never)+ ducked: list[int] = []+ for token, (name, bundle_id) in _PLAYERS.items():+ if name.lower() in skip:+ continue+ try:+ proc = self._run(_duck_script(bundle_id, self._duck))+ prev = self._parse_volume(proc, name)+ if prev is not None and prev > self._duck:+ self._saved[token] = prev+ ducked.append(token)+ except Exception: # noqa: BLE001 — timeout/TCC denial: skip player+ log.debug("ducking skip (%s)", name, exc_info=True)+ if not ducked and self._master_fallback:+ try:+ proc = self._run(_master_duck_script(self._duck))+ prev = self._parse_volume(proc, "master")+ if prev is not None and prev > self._duck:+ self._saved[_MASTER_TOKEN] = prev+ ducked.append(_MASTER_TOKEN)+ except Exception: # noqa: BLE001+ log.debug("ducking skip (master)", exc_info=True)+ return ducked++ def restore(self, pids: list[int]) -> None:+ """Restore exactly the given tokens. Idempotent; unknown token = no-op."""+ for token in pids:+ prev = self._saved.get(token)+ if prev is None:+ continue+ try:+ if token == _MASTER_TOKEN:+ self._run(f"set volume output volume {prev}")+ else:+ _name, bundle_id = _PLAYERS[token]+ self._run(_restore_script(bundle_id, prev))+ self._saved.pop(token, None)+ except Exception: # noqa: BLE001+ log.debug("ducking restore skip (token=%s)", token, exc_info=True)++ def prewarm(self) -> None:+ """Fire benign guarded queries so the one-time macOS Automation consent+ prompt appears at enable time rather than mid-session. Best-effort.+ """+ for _token, (name, bundle_id) in _PLAYERS.items():+ try:+ self._run(_prewarm_script(bundle_id))+ except Exception: # noqa: BLE001+ log.debug("ducking prewarm skip (%s)", name, exc_info=True)++ # ---- internals ---------------------------------------------------------+ @staticmethod+ def _normalized_never(never: frozenset[str]) -> set[str]:+ """Map never-mute entries to player names: case-insensitive, and the+ Windows-style ``.exe`` / macOS ``.app`` suffixes are stripped so one+ allowlist entry ("Spotify.exe") covers both platforms.+ """+ out: set[str] = set()+ for name in never:+ n = name.strip().lower()+ for suffix in (".exe", ".app"):+ if n.endswith(suffix):+ n = n[: -len(suffix)]+ out.add(n)+ return out++ def _parse_volume(self, proc: Any, target: str) -> int | None:+ """Previous volume from a duck script, or None when not duckable."""+ if getattr(proc, "returncode", 1) != 0:+ log.debug(+ "ducking osascript rc=%s (%s): %s",+ getattr(proc, "returncode", None),+ target,+ (getattr(proc, "stderr", "") or "").strip(),+ )+ return None+ out = (getattr(proc, "stdout", "") or "").strip()+ if not out or out == _NOT_RUNNING:+ return None # player not running+ return int(float(out)) # ValueError degrades via the caller's exceptdiff --git a/jarvis/audio/ducking/null.py b/jarvis/audio/ducking/null.pyindex 75f18e46d0..f87f2f1ba7 100644--- a/jarvis/audio/ducking/null.py+++ b/jarvis/audio/ducking/null.py@@ -1,4 +1,4 @@-"""No-op ducker (non-Windows / pycaw absent)."""+"""No-op ducker (no platform ducking backend available on this host)."""from __future__ import annotationsimport loggingdiff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 43cc51a01d..8be9af174d 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -1395,10 +1395,12 @@ class UIConfig(BaseModel):class DuckingConfig(BaseModel):"""Audio ducking — "Mute music while dictating" (Taskbar section).- When ``enabled``, the audio-duck controller mutes every OTHER app's audio- session for the duration of a voice session (excluding Jarvis's own PID, so- the TTS voice is never muted) and restores them when the session ends.- Windows-only (pycaw); a graceful no-op elsewhere. Default off (opt-in).+ When ``enabled``, the audio-duck controller lowers every OTHER app's audio+ for the duration of a voice session and restores it when the session ends.+ Windows: per-app session mute via pycaw (excluding Jarvis's own PID, so the+ TTS voice is never muted). macOS: AppleScript volume duck of the known+ players (Music, Spotify) plus an opt-in master-output fallback. A graceful+ no-op elsewhere. Default off (opt-in)."""model_config = ConfigDict(extra="allow")@@ -1406,8 +1408,14 @@ class DuckingConfig(BaseModel):enabled: bool = False# Grace before restoring other apps' volume (lets the TTS tail finish).restore_delay_ms: int = 400- # App process names never to mute (e.g. "Discord.exe"). Empty = mute all others.+ # App names never to mute — Windows process names ("Discord.exe") or plain+ # app names ("Spotify"). Empty = mute all others.never_mute: list[str] = Field(default_factory=list)+ # Volume other apps are ducked to (0 = full duck/mute of the app volume).+ duck_volume_percent: int = Field(default=0, ge=0, le=100)+ # macOS only: when no known player was ducked, lower the MASTER output+ # volume instead. Opt-in — the master volume also lowers Jarvis's own TTS.+ macos_master_fallback: bool = Falseclass AutostartConfig(BaseModel):diff --git a/tests/unit/audio/test_ducking_factory.py b/tests/unit/audio/test_ducking_factory.pyindex d2be53f020..414e390392 100644--- a/tests/unit/audio/test_ducking_factory.py+++ b/tests/unit/audio/test_ducking_factory.py@@ -1,11 +1,15 @@-"""make_audio_ducker selects NullDucker when pycaw/Windows unavailable."""+"""make_audio_ducker picks the platform backend, NullDucker otherwise."""from __future__ import annotations+from types import SimpleNamespace+from jarvis.audio.ducking.factory import make_audio_ducker+from jarvis.audio.ducking.macos import MacOSScriptDuckerfrom jarvis.audio.ducking.null import NullDuckerdef test_factory_returns_null_when_pycaw_absent(monkeypatch):+ monkeypatch.setattr("jarvis.audio.ducking.factory.sys.platform", "win32")monkeypatch.setattr("jarvis.audio.ducking.factory._pycaw_available", lambda: False)@@ -17,6 +21,56 @@ def test_factory_returns_null_off_windows(monkeypatch):assert isinstance(make_audio_ducker(), NullDucker)+def test_factory_returns_windows_backend_on_win32_with_pycaw(monkeypatch):+ from jarvis.audio.ducking.windows import WindowsPycawDucker++ monkeypatch.setattr("jarvis.audio.ducking.factory.sys.platform", "win32")+ monkeypatch.setattr(+ "jarvis.audio.ducking.factory._pycaw_available", lambda: True+ )+ assert isinstance(make_audio_ducker(), WindowsPycawDucker)+++def test_factory_returns_macos_backend_on_darwin_with_osascript(monkeypatch):+ monkeypatch.setattr("jarvis.audio.ducking.factory.sys.platform", "darwin")+ monkeypatch.setattr(+ "jarvis.audio.ducking.factory._osascript_available", lambda: True+ )+ assert isinstance(make_audio_ducker(), MacOSScriptDucker)+++def test_factory_returns_null_on_darwin_without_osascript(monkeypatch):+ monkeypatch.setattr("jarvis.audio.ducking.factory.sys.platform", "darwin")+ monkeypatch.setattr(+ "jarvis.audio.ducking.factory._osascript_available", lambda: False+ )+ assert isinstance(make_audio_ducker(), NullDucker)+++def test_factory_threads_cfg_into_the_macos_backend(monkeypatch):+ monkeypatch.setattr("jarvis.audio.ducking.factory.sys.platform", "darwin")+ monkeypatch.setattr(+ "jarvis.audio.ducking.factory._osascript_available", lambda: True+ )+ cfg = SimpleNamespace(+ ducking=SimpleNamespace(duck_volume_percent=20, macos_master_fallback=True)+ )+ d = make_audio_ducker(cfg)+ assert isinstance(d, MacOSScriptDucker)+ assert d._duck == 20+ assert d._master_fallback is True+++def test_factory_no_arg_call_still_works(monkeypatch):+ monkeypatch.setattr("jarvis.audio.ducking.factory.sys.platform", "darwin")+ monkeypatch.setattr(+ "jarvis.audio.ducking.factory._osascript_available", lambda: True+ )+ d = make_audio_ducker() # source-compatible: cfg is optional+ assert isinstance(d, MacOSScriptDucker)+ assert d._duck == 0 and d._master_fallback is False++def test_null_ducker_is_noop():d = NullDucker()assert d.mute_others(own_pid=123, never=frozenset()) == []diff --git a/tests/unit/audio/test_ducking_macos.py b/tests/unit/audio/test_ducking_macos.pynew file mode 100644index 0000000000..0732acf595--- /dev/null+++ b/tests/unit/audio/test_ducking_macos.py@@ -0,0 +1,149 @@+"""MacOSScriptDucker: tiered AppleScript duck/restore with a fake runner."""+from __future__ import annotations++import subprocess++from jarvis.audio.ducking.macos import _MASTER_TOKEN, MacOSScriptDucker++_MUSIC = "com.apple.Music"+_SPOTIFY = "com.spotify.client"+++class FakeRunner:+ """Records every script; returns scripted results per app / master.++ ``results`` maps a bundle id (or ``"master"``) to a stdout string, a+ ``CompletedProcess``, or an exception instance to raise.+ """++ def __init__(self, results: dict[str, object]):+ self.scripts: list[str] = []+ self._results = results++ def __call__(self, script: str) -> subprocess.CompletedProcess:+ self.scripts.append(script)+ for key, res in self._results.items():+ if key != "master" and key in script:+ return self._result(res)+ if "output volume" in script:+ return self._result(self._results.get("master", "50"))+ raise AssertionError(f"unexpected script: {script}")++ @staticmethod+ def _result(res: object) -> subprocess.CompletedProcess:+ if isinstance(res, BaseException):+ raise res+ if isinstance(res, subprocess.CompletedProcess):+ return res+ return subprocess.CompletedProcess(+ ["osascript"], 0, stdout=f"{res}\n", stderr=""+ )+++def _ducker(runner: FakeRunner, **kwargs) -> MacOSScriptDucker:+ return MacOSScriptDucker(run=runner, **kwargs)+++def test_ducks_running_players_and_skips_stopped_ones():+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "-"})+ d = _ducker(run)+ tokens = d.mute_others(own_pid=123, never=frozenset())+ assert tokens == [1]+ assert d._saved == {1: 65} # Spotify not running → never tokenized+++def test_every_script_carries_the_is_running_guard():+ # Regression pin: a bare tell-application LAUNCHES the app; every player+ # script must guard with "is running" inside the same script.+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "40"})+ d = _ducker(run)+ tokens = d.mute_others(own_pid=123, never=frozenset())+ d.restore(tokens)+ d.prewarm()+ assert run.scripts, "no scripts were run"+ assert all("is running" in s for s in run.scripts)+++def test_restore_sets_previous_volume_and_clears_state():+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "-"})+ d = _ducker(run)+ assert d.mute_others(own_pid=1, never=frozenset()) == [1]+ d.restore([1])+ assert any("set sound volume to 65" in s for s in run.scripts)+ assert d._saved == {}+++def test_restore_is_idempotent_and_unknown_token_is_noop():+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "-"})+ d = _ducker(run)+ d.mute_others(own_pid=1, never=frozenset())+ d.restore([1])+ calls_after_first = len(run.scripts)+ d.restore([1]) # already restored → no further osascript call+ d.restore([42]) # unknown token → no-op+ assert len(run.scripts) == calls_after_first+++def test_never_mute_maps_names_case_insensitively_stripping_suffixes():+ for entry in ("Spotify", "spotify", "Spotify.exe", "Spotify.app"):+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "40"})+ d = _ducker(run)+ tokens = d.mute_others(own_pid=1, never=frozenset({entry}))+ assert tokens == [1], entry+ assert not any(_SPOTIFY in s for s in run.scripts), entry+++def test_runner_timeout_skips_player_but_others_still_duck():+ run = FakeRunner(+ {+ _MUSIC: subprocess.TimeoutExpired(cmd="osascript", timeout=3.0),+ _SPOTIFY: "70",+ }+ )+ d = _ducker(run)+ tokens = d.mute_others(own_pid=1, never=frozenset())+ assert tokens == [2]+ assert d._saved == {2: 70}+++def test_nonzero_returncode_skips_player_but_others_still_duck():+ # rc=1 covers the Automation TCC denial (-1743) shape as well.+ denied = subprocess.CompletedProcess(+ ["osascript"], 1, stdout="", stderr="Not authorized to send Apple events (-1743)"+ )+ run = FakeRunner({_MUSIC: denied, _SPOTIFY: "70"})+ d = _ducker(run)+ assert d.mute_others(own_pid=1, never=frozenset()) == [2]+++def test_master_fallback_off_and_no_players_ducks_nothing():+ run = FakeRunner({_MUSIC: "-", _SPOTIFY: "-"})+ d = _ducker(run, master_fallback=False)+ assert d.mute_others(own_pid=1, never=frozenset()) == []+ assert not any("output volume" in s for s in run.scripts)+++def test_master_fallback_on_and_no_players_ducks_master_and_restores():+ run = FakeRunner({_MUSIC: "-", _SPOTIFY: "-", "master": "80"})+ d = _ducker(run, master_fallback=True)+ tokens = d.mute_others(own_pid=1, never=frozenset())+ assert tokens == [_MASTER_TOKEN]+ assert d._saved == {_MASTER_TOKEN: 80}+ assert any("set volume output volume" in s for s in run.scripts)+ d.restore(tokens)+ assert any("set volume output volume 80" in s for s in run.scripts)+ assert d._saved == {}+++def test_master_fallback_untouched_when_a_player_was_ducked():+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "-", "master": "80"})+ d = _ducker(run, master_fallback=True)+ assert d.mute_others(own_pid=1, never=frozenset()) == [1]+ assert not any("output volume" in s for s in run.scripts)+++def test_already_quiet_player_is_not_tokenized():+ run = FakeRunner({_MUSIC: "0", _SPOTIFY: "-"})+ d = _ducker(run, duck_volume_percent=0)+ assert d.mute_others(own_pid=1, never=frozenset()) == []+ assert d._saved == {}