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(macos): make the Music/Spotify Automation consent a first-class permission
Harald Herzd83380411bf1
diff --git a/jarvis/audio/ducking/macos.py b/jarvis/audio/ducking/macos.pyindex cf83d549ec..8686f187bb 100644--- a/jarvis/audio/ducking/macos.py+++ b/jarvis/audio/ducking/macos.py@@ -6,16 +6,21 @@ the previous volume afterwards. Optionally (opt-in) falls back to lowering theMASTER output volume when no known player was ducked — note the masterfallback 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.+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.++The Automation consent itself is owned by ``jarvis.platform.permissions``+(the ``automation`` row asks for every player up front); the player list is+shared with it so the scripts and the permission row can never disagree.CRITICAL script shape: a bare ``tell application ...`` LAUNCHES the app, soevery script guards with ``if application id "..." is running`` INSIDE thesame script and returns ``"-"`` when the player is not running."""+from __future__ import annotationsimport logging@@ -24,33 +29,43 @@ from collections.abc import Callablefrom typing import Anyfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.platform.permissions import AUTOMATION_TARGETSlog = 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"),-}+_PLAYERS: dict[int, tuple[str, str]] = dict(enumerate(AUTOMATION_TARGETS, start=1))_MASTER_TOKEN = 100# Sentinel a script returns when the player is not running._NOT_RUNNING = "-"+# A duck/restore script must never stall a voice session; a consent prompt+# is answered by a human. Killing osascript at 3 s tore the Automation dialog+# down before the user could click — every session asked again.+_SCRIPT_TIMEOUT_S = 3.0+_CONSENT_TIMEOUT_S = 120.0+-def _run_osascript(script: str) -> subprocess.CompletedProcess:+def _run_osascript(+ script: str, *, timeout: float = _SCRIPT_TIMEOUT_S+) -> 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,+ timeout=timeout,check=False,creationflags=NO_WINDOW_CREATIONFLAGS,)+def _run_consent_osascript(script: str) -> subprocess.CompletedProcess:+ return _run_osascript(script, timeout=_CONSENT_TIMEOUT_S)++def _duck_script(bundle_id: str, target: int) -> str:"""Read the player volume and duck it — one script, is-running-guarded."""return (@@ -111,10 +126,14 @@ class MacOSScriptDucker:master_fallback: bool = False,duck_volume_percent: int = 0,run: Callable[[str], subprocess.CompletedProcess] | None = None,+ consent_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+ # An injected runner (tests) covers the consent path too unless a+ # dedicated one is given; production waits for the dialog there.+ self._consent_run = consent_run or (run if run is not None else _run_consent_osascript)self._saved: dict[int, int] = {} # token -> previous volume@classmethod@@ -123,9 +142,7 @@ class MacOSScriptDucker: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- ),+ duck_volume_percent=int(getattr(ducking, "duck_volume_percent", 0) or 0),)except Exception: # noqa: BLE001 — malformed config degrades to defaultslog.debug("ducking config read failed; using defaults", exc_info=True)@@ -174,7 +191,9 @@ class MacOSScriptDucker:# silent for good. Hand it to THIS session's restore.log.info("ducking: re-adopting %s (still at the duck volume with "- "an unrestored level of %d)", name, self._saved[token],+ "an unrestored level of %d)",+ name,+ self._saved[token],)ducked.append(token)except Exception: # noqa: BLE001 — timeout/TCC denial: skip player@@ -245,7 +264,7 @@ class MacOSScriptDucker:"""for _token, (name, bundle_id) in _PLAYERS.items():try:- self._run(_prewarm_script(bundle_id))+ self._consent_run(_prewarm_script(bundle_id))except Exception: # noqa: BLE001log.debug("ducking prewarm skip (%s)", name, exc_info=True)diff --git a/jarvis/platform/permissions.py b/jarvis/platform/permissions.pyindex 3b8c625edb..c2ab3af743 100644--- a/jarvis/platform/permissions.py+++ b/jarvis/platform/permissions.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport importlibimport loggingimport os+import sysimport timefrom collections.abc import Callablefrom dataclasses import asdict, dataclass@@ -65,6 +66,8 @@ def record_identity_reset(services: tuple[str, ...] | list[str]) -> None:)except OSError:log.debug("Could not record the macOS TCC reset marker.", exc_info=True)+ # The Automation answers on file belonged to the old identity too.+ _clear_automation_consent()def _read_identity_reset() -> dict[str, Any] | None:@@ -101,6 +104,52 @@ def _clear_identity_reset() -> None:log.debug("Could not clear the macOS TCC reset marker.", exc_info=True)+# Automation (Apple Events) has no query API for a target that is not+# running: macOS only answers for a live process. The answer the user gave the+# last time a target WAS running is kept here so the row does not flip back+# to "not requested" every time Music quits. It is a record of the user's+# decision, never a cached probe — a running target is always asked live and+# overrides it — and every reset path (tccutil, identity change) drops it.+_AUTOMATION_CONSENT_FILENAME = "macos-automation-consent.json"+++def automation_consent_path() -> Path:+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / _AUTOMATION_CONSENT_FILENAME+++def _read_automation_consent() -> dict[str, str]:+ import json++ try:+ payload = json.loads(automation_consent_path().read_text(encoding="utf-8"))+ except (OSError, ValueError):+ # Missing, unreadable or not JSON all mean the same: nothing recorded.+ return {}+ if not isinstance(payload, dict):+ return {}+ return {str(key): str(value) for key, value in payload.items() if isinstance(value, str)}+++def _write_automation_consent(answers: dict[str, str]) -> None:+ import json++ path = automation_consent_path()+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(answers, sort_keys=True), encoding="utf-8")+ except OSError:+ log.debug("Could not record the macOS Automation answers.", exc_info=True)+++def _clear_automation_consent() -> None:+ try:+ automation_consent_path().unlink(missing_ok=True)+ except OSError:+ log.debug("Could not clear the macOS Automation answers.", exc_info=True)++class PermissionId(StrEnum):"""Stable identifiers shared by the API and desktop permission UI."""@@ -109,6 +158,10 @@ class PermissionId(StrEnum):ACCESSIBILITY = "accessibility"INPUT_MONITORING = "input_monitoring"EVENT_POSTING = "event_posting"+ # Apple Events consent for the media players the ducking scripts talk to+ # (Music, Spotify). Invisible before this row existed: the dialog fired+ # mid-dictation, a rebuild orphaned the answer, and nothing could reset it.+ AUTOMATION = "automation"# Not a TCC grant: the macOS Keychain prompts per item at first access# (typically right at app start, when API keys are read). Users who deny# it silently land on the file fallback and read the prompt as suspicious@@ -116,6 +169,15 @@ class PermissionId(StrEnum):CREDENTIAL_STORE = "credential_store"+# ``(display name, bundle id)`` of every app Jarvis scripts through Apple+# Events. The ducking backend reads this list too, so the permission row and+# the scripts can never disagree about which apps need consent.+AUTOMATION_TARGETS: tuple[tuple[str, str], ...] = (+ ("Music", "com.apple.Music"),+ ("Spotify", "com.spotify.client"),+)++class PermissionState(StrEnum):"""Cross-platform permission states; never infer denial from uncertainty."""@@ -140,6 +202,7 @@ FEATURE_REQUIREMENTS: dict[str, tuple[PermissionId, ...]] = {PermissionId.INPUT_MONITORING,),"window_control": (PermissionId.ACCESSIBILITY,),+ "audio_ducking": (PermissionId.AUTOMATION,),"api_keys": (PermissionId.CREDENTIAL_STORE,),}@@ -149,6 +212,7 @@ _LABELS: dict[PermissionId, str] = {PermissionId.ACCESSIBILITY: "Accessibility",PermissionId.INPUT_MONITORING: "Input Monitoring",PermissionId.EVENT_POSTING: "Input Control",+ PermissionId.AUTOMATION: "Automation (Music & Spotify)",PermissionId.CREDENTIAL_STORE: "Keychain (API keys)",}@@ -168,8 +232,81 @@ _SETTINGS_URLS: dict[PermissionId, str] = {PermissionId.EVENT_POSTING: ("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"),+ PermissionId.AUTOMATION: (+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Automation"+ ),}+# Apple Event Manager constants for AEDeterminePermissionToAutomateTarget+# (macOS 10.14+). Four-char codes are big-endian uint32; the OSStatus values+# are stable ABI (AE.framework / MacErrors.h).+_AE_TYPE_APPLICATION_BUNDLE_ID = 0x62756E64 # 'bund'+_AE_TYPE_WILDCARD = 0x2A2A2A2A # '****'+_AE_NO_ERR = 0+_AE_PROC_NOT_FOUND = -600 # target not running: no answer possible+_AE_EVENT_NOT_PERMITTED = -1743 # the user denied+_AE_EVENT_WOULD_REQUIRE_USER_CONSENT = -1744 # not asked yet+_AUTOMATION_STATES: dict[int, PermissionState] = {+ _AE_NO_ERR: PermissionState.GRANTED,+ _AE_EVENT_NOT_PERMITTED: PermissionState.DENIED,+ _AE_EVENT_WOULD_REQUIRE_USER_CONSENT: PermissionState.NOT_DETERMINED,+}+_CONSENT_ANSWERS = frozenset({PermissionState.GRANTED, PermissionState.DENIED})+# A hidden launch of Music/Spotify for the consent dialog: how long to wait+# for the process before giving up on that target for this request.+_AUTOMATION_LAUNCH_TIMEOUT_S = 10.0+++def _default_automation_probe(bundle_id: str, ask: bool) -> int | None:+ """``AEDeterminePermissionToAutomateTarget`` for one bundle id.++ Returns the raw OSStatus, or ``None`` when the framework cannot be+ called. With ``ask`` the call blocks until the user answers the system+ dialog — the only supported way to obtain Automation consent up front+ instead of in the middle of a dictation.+ """+ if sys.platform != "darwin":+ return None+ import ctypes++ class _AEDesc(ctypes.Structure):+ _fields_ = [("descriptorType", ctypes.c_uint32), ("dataHandle", ctypes.c_void_p)]++ try:+ services = ctypes.CDLL(+ "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices"+ )+ services.AECreateDesc.argtypes = [+ ctypes.c_uint32,+ ctypes.c_void_p,+ ctypes.c_long,+ ctypes.POINTER(_AEDesc),+ ]+ services.AECreateDesc.restype = ctypes.c_int32+ services.AEDisposeDesc.argtypes = [ctypes.POINTER(_AEDesc)]+ services.AEDisposeDesc.restype = ctypes.c_int32+ determine = services.AEDeterminePermissionToAutomateTarget+ determine.argtypes = [+ ctypes.POINTER(_AEDesc),+ ctypes.c_uint32,+ ctypes.c_uint32,+ ctypes.c_ubyte,+ ]+ determine.restype = ctypes.c_int32+ except (OSError, AttributeError):+ return None+ target = _AEDesc()+ data = bundle_id.encode("utf-8")+ if services.AECreateDesc(_AE_TYPE_APPLICATION_BUNDLE_ID, data, len(data), ctypes.byref(target)):+ return None+ try:+ return int(+ determine(ctypes.byref(target), _AE_TYPE_WILDCARD, _AE_TYPE_WILDCARD, 1 if ask else 0)+ )+ finally:+ services.AEDisposeDesc(ctypes.byref(target))++# IOKit HID access constants (IOHIDCheckAccess, macOS 10.15+). The SDK header# (IOKit/hidsystem/IOHIDLib.h) declares both as PLAIN C enums — 32-bit int,# not CF_ENUM(uint64_t); the raw values are stable ABI.@@ -290,6 +427,7 @@ _TCC_RESET_SERVICES: dict[PermissionId, str] = {PermissionId.ACCESSIBILITY: "Accessibility",PermissionId.INPUT_MONITORING: "ListenEvent",PermissionId.EVENT_POSTING: "PostEvent",+ PermissionId.AUTOMATION: "AppleEvents",}_READY_STATES = frozenset({PermissionState.GRANTED, PermissionState.NOT_REQUIRED})@@ -366,6 +504,7 @@ class SystemPermissionPort:screen_capture_live_check: Callable[[], bool | None] = _default_screen_capture_live_check,credential_store_backend: Callable[[], str] = _default_credential_store_backend,credential_store_recover: Callable[[], bool] = _default_credential_store_recover,+ automation_probe: Callable[[str, bool], int | None] = _default_automation_probe,) -> None:self._platform_name = platform_nameself._module_loader = module_loader@@ -373,6 +512,7 @@ class SystemPermissionPort:self._screen_capture_live_check = screen_capture_live_checkself._credential_store_backend = credential_store_backendself._credential_store_recover = credential_store_recover+ self._automation_probe = automation_probe# This is operation state, not a cached permission probe. The set lives# only for the current process and therefore clears exactly when the# required app restart has happened.@@ -552,11 +692,145 @@ class SystemPermissionPort:return PermissionState.NOT_GRANTEDreturn PermissionState.UNAVAILABLE+ # ---- Automation (Apple Events) ---------------------------------------++ def _installed_automation_targets(self) -> list[str] | None:+ """Bundle ids of the scriptable players present; ``None`` = no AppKit."""+ appkit = self._load("AppKit")+ if appkit is None:+ return None+ try:+ workspace = appkit.NSWorkspace.sharedWorkspace()+ except Exception: # noqa: BLE001 - a broken native bridge fails closed+ return None+ locate = getattr(workspace, "URLForApplicationWithBundleIdentifier_", None)+ if not callable(locate):+ # No lookup API: nothing can be scripted, so nothing to consent to.+ return []+ installed: list[str] = []+ for _name, bundle_id in AUTOMATION_TARGETS:+ try:+ if locate(bundle_id) is not None:+ installed.append(bundle_id)+ except Exception: # noqa: BLE001 - one bad lookup skips one player+ log.debug("Could not locate %s.", bundle_id, exc_info=True)+ return installed++ def _running_automation_targets(self, appkit: Any, bundle_id: str) -> list[Any]:+ lookup = getattr(+ getattr(appkit, "NSRunningApplication", None),+ "runningApplicationsWithBundleIdentifier_",+ None,+ )+ if not callable(lookup):+ return []+ try:+ return list(lookup(bundle_id) or [])+ except Exception: # noqa: BLE001 - treat as not running+ return []++ def _live_automation_state(self, bundle_id: str, *, ask: bool) -> PermissionState | None:+ """The OS answer for a RUNNING target; ``None`` when there is none."""+ try:+ status = self._automation_probe(bundle_id, ask)+ except Exception: # noqa: BLE001 - native probes never crash callers+ log.debug("Automation probe for %s failed.", bundle_id, exc_info=True)+ return None+ if status is None:+ return None+ return _AUTOMATION_STATES.get(int(status))++ def _automation_state(self) -> PermissionState:+ """One row for every scriptable player: live when running, else recorded.++ No player installed means nothing to consent to. Otherwise the+ strictest answer wins — a single denied or unanswered player makes+ the ducking feature incomplete, and the detail names which one.+ """+ installed = self._installed_automation_targets()+ if installed is None:+ return PermissionState.UNAVAILABLE+ if not installed:+ return PermissionState.NOT_REQUIRED+ appkit = self._load("AppKit")+ recorded = _read_automation_consent()+ updated = dict(recorded)+ states: list[PermissionState] = []+ for bundle_id in installed:+ state: PermissionState | None = None+ if appkit is not None and self._running_automation_targets(appkit, bundle_id):+ state = self._live_automation_state(bundle_id, ask=False)+ if state is None:+ try:+ state = PermissionState(recorded[bundle_id])+ except (KeyError, ValueError):+ state = PermissionState.NOT_DETERMINED+ elif state in _CONSENT_ANSWERS:+ updated[bundle_id] = state.value+ else:+ updated.pop(bundle_id, None)+ states.append(state)+ if updated != recorded:+ _write_automation_consent(updated)+ if PermissionState.DENIED in states:+ return PermissionState.DENIED+ if PermissionState.NOT_DETERMINED in states:+ return PermissionState.NOT_DETERMINED+ return PermissionState.GRANTED++ def _request_automation(self) -> None:+ """Ask for every installed player up front, launching it hidden if needed.++ Apple only shows the Automation dialog for a running target, so a+ player that is closed is started hidden, asked, and closed again —+ only the ones this call started. Each answer lands in the consent+ record straight away, so the row is final before the dialog closes.+ """+ appkit = self._load("AppKit")+ if appkit is None:+ raise RuntimeError("AppKit is unavailable")+ workspace = appkit.NSWorkspace.sharedWorkspace()+ answers = _read_automation_consent()+ launched: list[Any] = []+ try:+ for bundle_id in self._installed_automation_targets() or []:+ if not self._running_automation_targets(appkit, bundle_id):+ url = workspace.URLForApplicationWithBundleIdentifier_(bundle_id)+ configuration = appkit.NSWorkspaceOpenConfiguration.configuration()+ configuration.setActivates_(False)+ configuration.setHides_(True)+ workspace.openApplicationAtURL_configuration_completionHandler_(+ url, configuration, lambda _app, _error: None+ )+ deadline = time.monotonic() + _AUTOMATION_LAUNCH_TIMEOUT_S+ running: list[Any] = []+ while time.monotonic() < deadline and not running:+ time.sleep(0.1)+ running = self._running_automation_targets(appkit, bundle_id)+ if not running:+ log.warning("%s did not start; Automation consent skipped.", bundle_id)+ continue+ launched.extend(running)+ state = self._live_automation_state(bundle_id, ask=True)+ if state in _CONSENT_ANSWERS:+ answers[bundle_id] = state.value+ else:+ answers.pop(bundle_id, None)+ finally:+ _write_automation_consent(answers)+ for app in launched:+ try:+ app.terminate()+ except Exception: # noqa: BLE001 - closing what we opened is best-effort+ log.debug("Could not close a player opened for consent.", exc_info=True)+def _state(self, permission_id: PermissionId) -> PermissionState:if self.platform != "darwin":return PermissionState.NOT_REQUIREDif permission_id is PermissionId.CREDENTIAL_STORE:return self._credential_store_state()+ if permission_id is PermissionId.AUTOMATION:+ return self._automation_state()if permission_id is PermissionId.MICROPHONE:return self._microphone_state()if permission_id is PermissionId.SCREEN_RECORDING:@@ -644,6 +918,9 @@ class SystemPermissionPort:def _requester_available(self, permission_id: PermissionId) -> bool:if permission_id is PermissionId.CREDENTIAL_STORE:return True+ if permission_id is PermissionId.AUTOMATION:+ module = self._load("AppKit")+ return callable(getattr(getattr(module, "NSWorkspace", None), "sharedWorkspace", None))if permission_id is PermissionId.MICROPHONE:module = self._load("AVFoundation")owner = getattr(module, "AVCaptureDevice", None)@@ -856,6 +1133,11 @@ class SystemPermissionPort:# once more) lands honestly in the after-snapshot.self._credential_store_recover()return None+ if permission_id is PermissionId.AUTOMATION:+ # Synchronous: every dialog is answered by the time this returns,+ # so the after-snapshot already carries the final state.+ self._request_automation()+ return Noneif permission_id is PermissionId.MICROPHONE:av = self._load("AVFoundation")av.AVCaptureDevice.requestAccessForMediaType_completionHandler_(@@ -1081,6 +1363,9 @@ class SystemPermissionPort:before,)self._restart_required.discard(permission_id)+ if permission_id is PermissionId.AUTOMATION:+ # The recorded answers described rows tccutil just deleted.+ _clear_automation_consent()return PermissionOperation(True,permission_id.value,@@ -1176,6 +1461,7 @@ def get_system_permission_port() -> SystemPermissionPort:__all__ = ["APP_NAME",+ "AUTOMATION_TARGETS","EXPECTED_BUNDLE_ID","FEATURE_REQUIREMENTS","AppIdentity",diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsxindex 97eb2b611a..f7e1f97bbf 100644--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx@@ -8,6 +8,7 @@ const IDS = ["accessibility","input_monitoring","event_posting",+ "automation","credential_store",] as const;diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsxindex f4fe2f0857..4e4dc43cd1 100644--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsx+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsx@@ -11,6 +11,7 @@ const EXPECTED_MACOS_PERMISSIONS = new Set<PermissionId>(["accessibility","input_monitoring","event_posting",+ "automation","credential_store",]);diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts b/jarvis/ui/web/frontend/src/hooks/usePermissions.tsindex 6676849f6b..54674abce4 100644--- a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts+++ b/jarvis/ui/web/frontend/src/hooks/usePermissions.ts@@ -8,6 +8,7 @@ export type PermissionId =| "accessibility"| "input_monitoring"| "event_posting"+ | "automation"| "credential_store";export type PermissionState =diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex be064cc000..a340b685cb 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -485,10 +485,10 @@"pin_chat": "Chat anheften","unpin_chat": "Chat lösen",- "jarvis_tools": "Jarvis Tools",- "scheduled": "Geplant",- "more": "Mehr",-+ "jarvis_tools": "Jarvis Tools",+ "scheduled": "Geplant",+ "more": "Mehr",+"instance_dev_hint": "Dev-Instanz — eine zweite, frei neustartbare Kopie der App mit eigenen Daten, Ports und eigenem Icon. Die normale App läuft daneben weiter.","surface_voice": "Voice","surface_chat": "Chat",@@ -2197,6 +2197,10 @@"title": "Eingabesteuerung","description": "Erforderlich, damit Computer-Use Maus- und Tastaturereignisse senden kann."},+ "automation": {+ "title": "Automation (Musik & Spotify)",+ "description": "Erlaubt Jarvis, Musik und Spotify beim Diktieren leiser zu stellen und danach wieder lauter. Wird einmal pro Player gefragt — ein geschlossener Player wird für den Dialog kurz im Hintergrund geöffnet."+ },"credential_store": {"title": "Schlüsselbund (API-Keys)","description": "Speichert deine API-Keys verschlüsselt im macOS-Schlüsselbund statt in einer Klartextdatei — genau dafür fragt macOS beim Start der App. Deine Keys bleiben auf deinem Mac und werden nirgendwohin gesendet."@@ -2214,6 +2218,7 @@"computer_use": "Computer-Use","global_hotkeys": "Globale Kurzbefehle","window_control": "Fenstersteuerung",+ "audio_ducking": "Musik leiser beim Diktieren","api_keys": "Sichere API-Key-Ablage"},"restart_deferred": "Neu erteilte Freigaben werden mit dem automatischen Neustart am Ende der Einrichtung aktiv - jetzt ist nichts zu tun.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 5e6f20c263..17ef5e000f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -485,10 +485,10 @@"pin_chat": "Pin chat","unpin_chat": "Unpin chat",- "jarvis_tools": "Jarvis Tools",- "scheduled": "Scheduled",- "more": "More",-+ "jarvis_tools": "Jarvis Tools",+ "scheduled": "Scheduled",+ "more": "More",+"instance_dev_hint": "Dev instance — a second, freely restartable copy of the app with its own data, ports and icon. The regular app keeps running beside it.","surface_voice": "Voice","surface_chat": "Chat",@@ -2230,6 +2230,10 @@"title": "Input control","description": "Required for Computer-Use to send mouse and keyboard events."},+ "automation": {+ "title": "Automation (Music & Spotify)",+ "description": "Lets Jarvis turn Music and Spotify down while you dictate and back up afterwards. Asked once per player — a closed player is opened briefly in the background for the dialog."+ },"credential_store": {"title": "Keychain (API keys)","description": "Stores your API keys encrypted in the macOS Keychain instead of a plain file — that is the Keychain prompt you see when the app starts. Your keys stay on your Mac and are never sent anywhere."@@ -2247,6 +2251,7 @@"computer_use": "Computer-Use","global_hotkeys": "Global shortcuts","window_control": "Window control",+ "audio_ducking": "Music ducking while dictating","api_keys": "Secure API-key storage"},"restart_deferred": "Newly granted access turns on with the automatic restart at the end of setup - nothing to do now.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 6f7e88c4a6..94cfe3b22c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -485,10 +485,10 @@"pin_chat": "Fijar chat","unpin_chat": "Desfijar chat",- "jarvis_tools": "Herramientas Jarvis",- "scheduled": "Programado",- "more": "Más",-+ "jarvis_tools": "Herramientas Jarvis",+ "scheduled": "Programado",+ "more": "Más",+"instance_dev_hint": "Instancia de desarrollo: una segunda copia de la app que puedes reiniciar libremente, con sus propios datos, puertos e icono. La app normal sigue funcionando al lado.","surface_voice": "Voz","surface_chat": "Chat",@@ -2197,6 +2197,10 @@"title": "Control de entrada","description": "Necesario para que Computer-Use envíe eventos de ratón y teclado."},+ "automation": {+ "title": "Automatización (Música y Spotify)",+ "description": "Permite a Jarvis bajar el volumen de Música y Spotify mientras dictas y subirlo después. Se pregunta una vez por reproductor; un reproductor cerrado se abre brevemente en segundo plano para el diálogo."+ },"credential_store": {"title": "Llavero (claves API)","description": "Guarda tus claves API cifradas en el Llavero de macOS en lugar de un archivo de texto plano — ese es el aviso del Llavero que ves al iniciar la app. Tus claves se quedan en tu Mac y nunca se envían a ningún sitio."@@ -2214,6 +2218,7 @@"computer_use": "Computer-Use","global_hotkeys": "Atajos globales","window_control": "Control de ventanas",+ "audio_ducking": "Bajar la música al dictar","api_keys": "Almacenamiento seguro de claves API"},"restart_deferred": "Los permisos recién concedidos se activan con el reinicio automático al final de la configuración; no hay nada que hacer ahora.",diff --git a/tests/unit/platform/test_permissions.py b/tests/unit/platform/test_permissions.pyindex 5e15c47319..3b286d0890 100644--- a/tests/unit/platform/test_permissions.py+++ b/tests/unit/platform/test_permissions.py@@ -140,6 +140,7 @@ def _port(credential_backend: Callable[[], str] = lambda: "platform",credential_recover: Callable[[], bool] = lambda: True,screen_capture_live: Callable[[], bool | None] = lambda: None,+ automation_probe: Callable[[str, bool], int | None] = lambda _bundle_id, _ask: None,) -> SystemPermissionPort:def load(name: str) -> object:if name not in modules:@@ -157,6 +158,7 @@ def _port(screen_capture_live_check=screen_capture_live,credential_store_backend=credential_backend,credential_store_recover=credential_recover,+ automation_probe=automation_probe,)@@ -918,3 +920,226 @@ def test_open_settings_works_while_the_app_sits_in_the_background() -> None:assert _permission(snapshot, PermissionId.MICROPHONE)["can_open_settings"] is Trueassert operation.ok is Trueassert workspace.opened_urls+++# --- Automation (Apple Events): the Music/Spotify consent row+++_MUSIC = "com.apple.Music"+_SPOTIFY = "com.spotify.client"+++class _Player:+ """An ``NSRunningApplication`` stand-in for one scriptable player."""++ def __init__(self, bundle_id: str, running: set[str]) -> None:+ self.bundle_id = bundle_id+ self._running = running+ self.terminated = False++ def terminate(self) -> None:+ self.terminated = True+ self._running.discard(self.bundle_id)+++class _OpenConfiguration:+ def __init__(self) -> None:+ self.activates: bool | None = None+ self.hides: bool | None = None++ def setActivates_(self, value: bool) -> None:+ self.activates = value++ def setHides_(self, value: bool) -> None:+ self.hides = value+++def _automation_fixture(+ tmp_path: Path,+ monkeypatch,+ *,+ installed: set[str],+ running: set[str],+ answers: dict[str, int],+) -> tuple[+ dict[str, object],+ list[tuple[str, bool | None, bool | None]],+ list[tuple[str, bool]],+ Callable[[str, bool], int | None],+]:+ """Native fakes for the Automation row plus the launch log, probe log and probe."""+ import jarvis.platform.permissions as permissions_module++ modules, _screen, workspace = _native_modules()+ workspace.URLForApplicationWithBundleIdentifier_ = ( # type: ignore[attr-defined]+ lambda bundle_id: (+ f"file:///Applications/{bundle_id}.app" if bundle_id in installed else None+ )+ )+ players: dict[str, _Player] = {}++ def running_apps(bundle_id: str) -> list[_Player]:+ if bundle_id not in running:+ return []+ return [players.setdefault(bundle_id, _Player(bundle_id, running))]++ launches: list[tuple[str, bool | None, bool | None]] = []++ def open_app(url: str, configuration: _OpenConfiguration, _handler) -> None:+ launches.append((url, configuration.activates, configuration.hides))+ running.add(url.removeprefix("file:///Applications/").removesuffix(".app"))++ workspace.openApplicationAtURL_configuration_completionHandler_ = open_app # type: ignore[attr-defined]+ appkit = modules["AppKit"]+ appkit.NSRunningApplication = SimpleNamespace( # type: ignore[attr-defined]+ currentApplication=lambda: workspace.current,+ runningApplicationsWithBundleIdentifier_=running_apps,+ )+ appkit.NSWorkspaceOpenConfiguration = SimpleNamespace( # type: ignore[attr-defined]+ configuration=_OpenConfiguration+ )+ monkeypatch.setattr(+ permissions_module, "automation_consent_path", lambda: tmp_path / "consent.json"+ )+ probes: list[tuple[str, bool]] = []++ def probe(bundle_id: str, ask: bool) -> int | None:+ probes.append((bundle_id, ask))+ return answers.get(bundle_id)++ return modules, launches, probes, probe+++def _consent_file(tmp_path: Path) -> dict:+ import json++ path = tmp_path / "consent.json"+ return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {}+++def test_automation_is_not_required_without_a_scriptable_player(tmp_path: Path, monkeypatch):+ modules, _launches, _probes, probe = _automation_fixture(+ tmp_path, monkeypatch, installed=set(), running=set(), answers={}+ )++ snapshot = _port(modules, automation_probe=probe).snapshot()++ row = _permission(snapshot, PermissionId.AUTOMATION)+ assert row["status"] == PermissionState.NOT_REQUIRED+ assert row["required"] == ["audio_ducking"]+ assert snapshot["features"]["audio_ducking"]["ready"] is True+++def test_automation_reads_a_running_player_live_and_records_the_answer(tmp_path: Path, monkeypatch):+ modules, _launches, probes, probe = _automation_fixture(+ tmp_path, monkeypatch, installed={_MUSIC}, running={_MUSIC}, answers={_MUSIC: 0}+ )++ snapshot = _port(modules, automation_probe=probe).snapshot()++ assert _permission(snapshot, PermissionId.AUTOMATION)["status"] == PermissionState.GRANTED+ assert probes == [(_MUSIC, False)] # a status probe never raises the dialog+ assert _consent_file(tmp_path) == {_MUSIC: "granted"}+++def test_automation_request_opens_a_closed_player_hidden_asks_and_closes_it(+ tmp_path: Path, monkeypatch+):+ """Apple only shows the dialog for a running target — so start it, quietly."""+ modules, launches, probes, probe = _automation_fixture(+ tmp_path, monkeypatch, installed={_MUSIC}, running=set(), answers={_MUSIC: 0}+ )+ port = _port(modules, automation_probe=probe)+ before = _permission(port.snapshot(), PermissionId.AUTOMATION)+ assert before["status"] == PermissionState.NOT_DETERMINED+ assert before["can_request"] is True++ result = port.request(PermissionId.AUTOMATION)++ assert result.ok and result.performed and result.restart_required is False+ assert launches == [(f"file:///Applications/{_MUSIC}.app", False, True)]+ assert (_MUSIC, True) in probes+ # Closed again — and the answer survives the player being closed.+ assert (+ _permission(result.snapshot, PermissionId.AUTOMATION)["status"] == PermissionState.GRANTED+ )+ assert _consent_file(tmp_path) == {_MUSIC: "granted"}+ assert launches and not port._running_automation_targets(modules["AppKit"], _MUSIC)+++def test_automation_request_leaves_an_already_running_player_open(tmp_path: Path, monkeypatch):+ modules, launches, _probes, probe = _automation_fixture(+ tmp_path, monkeypatch, installed={_MUSIC}, running={_MUSIC}, answers={_MUSIC: -1744}+ )+ port = _port(modules, automation_probe=probe)++ port.request(PermissionId.AUTOMATION)++ assert launches == []+ assert port._running_automation_targets(modules["AppKit"], _MUSIC)+++def test_automation_denial_offers_the_reset_and_the_reset_forgets_the_answer(+ tmp_path: Path, monkeypatch+):+ modules, _launches, _probes, probe = _automation_fixture(+ tmp_path, monkeypatch, installed={_MUSIC}, running={_MUSIC}, answers={_MUSIC: -1743}+ )+ port = _port(modules, automation_probe=probe)+ row = _permission(port.snapshot(), PermissionId.AUTOMATION)+ assert row["status"] == PermissionState.DENIED+ assert row["can_request"] is False and row["can_reset"] is True+ assert _consent_file(tmp_path) == {_MUSIC: "denied"}++ commands: list[list[str]] = []++ def fake_run(argv, **_kwargs):+ commands.append(list(argv))+ return SimpleNamespace(returncode=0, stdout="", stderr="")++ monkeypatch.setattr("subprocess.run", fake_run)+ result = port.reset(PermissionId.AUTOMATION)++ assert result.ok and result.performed+ assert commands == [["/usr/bin/tccutil", "reset", "AppleEvents", BUNDLE_ID]]+ # The reset dropped the recorded answer; the after-snapshot then asked the+ # still-running player live again (the fake keeps saying denied) — a+ # closed player would have read "not requested" from the empty record.+ assert _consent_file(tmp_path) == {_MUSIC: "denied"}+ (tmp_path / "consent.json").unlink()+ closed = _port(modules, automation_probe=lambda _b, _a: -600).snapshot()+ assert _permission(closed, PermissionId.AUTOMATION)["status"] == PermissionState.NOT_DETERMINED+++def test_automation_strictest_player_wins(tmp_path: Path, monkeypatch):+ modules, _launches, _probes, probe = _automation_fixture(+ tmp_path,+ monkeypatch,+ installed={_MUSIC, _SPOTIFY},+ running={_SPOTIFY},+ answers={_SPOTIFY: -1744},+ )+ (tmp_path / "consent.json").write_text('{"com.apple.Music": "granted"}', encoding="utf-8")++ snapshot = _port(modules, automation_probe=probe).snapshot()++ assert (+ _permission(snapshot, PermissionId.AUTOMATION)["status"] == PermissionState.NOT_DETERMINED+ )+ assert snapshot["features"]["audio_ducking"]["ready"] is False+++def test_identity_reset_forgets_the_automation_answers(tmp_path: Path, monkeypatch):+ import jarvis.platform.permissions as permissions_module++ monkeypatch.setattr(+ permissions_module, "identity_reset_marker_path", lambda: tmp_path / "reset.json"+ )+ monkeypatch.setattr(+ permissions_module, "automation_consent_path", lambda: tmp_path / "consent.json"+ )+ (tmp_path / "consent.json").write_text('{"com.apple.Music": "granted"}', encoding="utf-8")++ permissions_module.record_identity_reset(("Microphone", "AppleEvents"))++ assert not (tmp_path / "consent.json").exists()